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

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

Introduction

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

Prototype

public static MultipartEntityBuilder create() 

Source Link

Usage

From source file:de.siegmar.securetransfer.controller.MvcTest.java

@Test
public void messageWithFileWithPassword() throws Exception {
    final String messageToSend = "my secret message";
    final String password = "top secret password";
    final String fileContent = "test file content";

    final String boundary = "------TestBoundary" + UUID.randomUUID();
    final MultipartEntityBuilder builder = MultipartEntityBuilder.create().setBoundary(boundary)
            .addTextBody("expirationDays", "1").addTextBody("message", messageToSend)
            .addTextBody("password", password).addBinaryBody("files",
                    fileContent.getBytes(StandardCharsets.UTF_8), ContentType.APPLICATION_OCTET_STREAM,
                    "test.txt");

    // Create new message and expect redirect with flash message after store
    final MvcResult createMessageResult = mockMvc
            .perform(post("/send").content(ByteStreams.toByteArray(builder.build().getContent()))
                    .contentType(MediaType.MULTIPART_FORM_DATA_VALUE + "; boundary=" + boundary))
            .andExpect(status().isFound()).andExpect(redirectedUrlPattern("/send/**"))
            .andExpect(flash().attribute("message", messageToSend)).andReturn();

    // receive data after redirect
    final String messageStatusUrl = createMessageResult.getResponse().getRedirectedUrl();

    final String linkSecret = messageStatusUrl.replaceFirst(".*linkSecret=", "");
    HashCode.fromString(linkSecret);/* ww w . j a v a 2s  . c om*/

    final MvcResult messageStatusResult = mockMvc.perform(get(messageStatusUrl)).andExpect(status().isOk())
            .andExpect(content().contentType("text/html;charset=UTF-8"))
            .andExpect(view().name("send/message_status")).andReturn();

    final SenderMessage senderMessage = (SenderMessage) messageStatusResult.getModelAndView().getModel()
            .get("senderMessage");

    assertNotNull(senderMessage);
    assertNotNull(senderMessage.getId());
    assertNotNull(senderMessage.getReceiverId());
    assertNotNull(senderMessage.getExpiration());
    assertNull(senderMessage.getReceived());
    assertTrue(senderMessage.isPasswordEncrypted());

    final String receiveUrl = (String) messageStatusResult.getModelAndView().getModel().get("receiveUrl");

    assertNotNull(receiveUrl);

    // call receiver URL
    final MvcResult confirmPage = mockMvc.perform(get(receiveUrl)).andExpect(status().isOk())
            .andExpect(content().contentType("text/html;charset=UTF-8"))
            .andExpect(view().name("receive/message_ask_password")).andReturn();

    final Document confirmPageDoc = Jsoup.parse(confirmPage.getResponse().getContentAsString());
    final String passwordUrl = confirmPageDoc.getElementsByTag("form").attr("action");

    // Receive message
    final MvcResult messageResult = mockMvc
            .perform(post(passwordUrl).param("linkSecret", linkSecret).param("password", password))
            .andExpect(status().isOk()).andExpect(content().contentType("text/html;charset=UTF-8"))
            .andExpect(view().name("receive/message")).andReturn();

    final DecryptedMessage decryptedMessage = (DecryptedMessage) messageResult.getModelAndView().getModel()
            .get("decryptedMessage");

    assertEquals(messageToSend, decryptedMessage.getMessage());
    assertEquals(1, decryptedMessage.getFiles().size());

    final DecryptedFile file = decryptedMessage.getFiles().get(0);
    final String fileId = file.getId();
    final String fileKey = file.getKeyHex();

    // Download file
    final MvcResult downloadResult = mockMvc
            .perform(get("/receive/file/{id}/{key}", fileId, fileKey).sessionAttr("iv_file_" + fileId,
                    file.getKeyIv().getIv()))
            .andExpect(request().asyncStarted())
            //.andExpect(request().asyncResult("Deferred result"))
            .andExpect(status().isOk()).andExpect(content().contentType("application/octet-stream"))
            .andReturn();

    downloadResult.getAsyncResult();
    assertEquals(fileContent, downloadResult.getResponse().getContentAsString());

    // Check message is burned
    mockMvc.perform(get(receiveUrl)).andExpect(status().isNotFound())
            .andExpect(content().contentType("text/html;charset=UTF-8"))
            .andExpect(view().name("message_not_found"));

    // Check file is burned
    mockMvc.perform(get("/receive/file/{id}/{key}", fileId, fileKey).sessionAttr("iv_file_" + fileId,
            file.getKeyIv().getIv())).andExpect(status().isNotFound())
            .andExpect(content().contentType("text/html;charset=UTF-8"))
            .andExpect(view().name("message_not_found"));

    // Check sender status page
    final MvcResult messageStatusResult2 = mockMvc.perform(get(messageStatusUrl)).andExpect(status().isOk())
            .andExpect(content().contentType("text/html;charset=UTF-8"))
            .andExpect(view().name("send/message_status")).andReturn();

    final SenderMessage senderMessage2 = (SenderMessage) messageStatusResult2.getModelAndView().getModel()
            .get("senderMessage");

    assertNotNull(senderMessage2);
    assertNotNull(senderMessage2.getId());
    assertNotNull(senderMessage2.getReceiverId());
    assertNotNull(senderMessage2.getExpiration());
    assertNotNull(senderMessage2.getReceived());
    assertTrue(senderMessage.isPasswordEncrypted());
}

From source file:com.intuit.karate.http.apache.ApacheHttpClient.java

@Override
protected HttpEntity getEntity(List<MultiPartItem> items, String mediaType) {
    boolean hasNullName = false;
    for (MultiPartItem item : items) {
        if (item.getName() == null) {
            hasNullName = true;// w  w  w . jav a 2 s  .  c  o  m
            break;
        }
    }
    if (hasNullName) { // multipart/related
        String boundary = createBoundary();
        String text = getAsStringEntity(items, boundary);
        ContentType ct = ContentType.create(mediaType)
                .withParameters(new BasicNameValuePair("boundary", boundary));
        return new StringEntity(text, ct);
    } else {
        MultipartEntityBuilder builder = MultipartEntityBuilder.create()
                .setContentType(ContentType.create(mediaType));
        for (MultiPartItem item : items) {
            if (item.getValue() == null || item.getValue().isNull()) {
                logger.warn("ignoring null multipart value for key: {}", item.getName());
                continue;
            }
            String name = item.getName();
            ScriptValue sv = item.getValue();
            if (name == null) {
                // builder.addPart(bodyPart);
            } else {
                FormBodyPartBuilder formBuilder = FormBodyPartBuilder.create().setName(name);
                ContentBody contentBody;
                switch (sv.getType()) {
                case INPUT_STREAM:
                    InputStream is = (InputStream) sv.getValue();
                    contentBody = new InputStreamBody(is, ContentType.APPLICATION_OCTET_STREAM, name);
                    break;
                case XML:
                    contentBody = new StringBody(sv.getAsString(), ContentType.APPLICATION_XML);
                    break;
                case JSON:
                    contentBody = new StringBody(sv.getAsString(), ContentType.APPLICATION_JSON);
                    break;
                default:
                    contentBody = new StringBody(sv.getAsString(), ContentType.TEXT_PLAIN);
                }
                formBuilder = formBuilder.setBody(contentBody);
                builder = builder.addPart(formBuilder.build());
            }
        }
        return builder.build();
    }
}

From source file:de.vanita5.twittnuker.util.net.TwidereHttpClientImpl.java

private static HttpEntity getAsEntity(final HttpParameter[] params) throws UnsupportedEncodingException {
    if (params == null)
        return null;
    if (!HttpParameter.containsFile(params))
        return new HttpParameterFormEntity(params);
    final MultipartEntityBuilder me = MultipartEntityBuilder.create();
    for (final HttpParameter param : params) {
        if (param.isFile()) {
            final ContentType contentType = ContentType.create(param.getContentType());
            final ContentBody body;
            if (param.getFile() != null) {
                body = new FileBody(param.getFile(), ContentType.create(param.getContentType()));
            } else {
                body = new InputStreamBody(param.getFileBody(), contentType, param.getFileName());
            }//w w w.  j  ava  2s  .  c  o m
            me.addPart(param.getName(), body);
        } else {
            final ContentType contentType = ContentType.TEXT_PLAIN.withCharset(Consts.UTF_8);
            final ContentBody body = new StringBody(param.getValue(), contentType);
            me.addPart(param.getName(), body);
        }
    }
    return me.build();
}

From source file:de.yaio.commons.http.HttpUtils.java

/** 
 * execute POST-Request for url with params
 * @param baseUrl                the url to call
 * @param username               username for auth
 * @param password               password for auth
 * @param params                 params for the request
 * @param textFileParams         text-files to upload
 * @param binFileParams          bin-files to upload
 * @return                       HttpResponse
 * @throws IOException           possible Exception if Request-state <200 > 299 
 *///from www  .  j  a  v  a  2 s . c om
public static HttpResponse callPatchUrlPure(final String baseUrl, final String username, final String password,
        final Map<String, String> params, final Map<String, String> textFileParams,
        final Map<String, String> binFileParams) throws IOException {
    // create request
    HttpPatch request = new HttpPatch(baseUrl);

    // map params
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    if (MapUtils.isNotEmpty(params)) {
        for (String key : params.keySet()) {
            builder.addTextBody(key, params.get(key), ContentType.TEXT_PLAIN);
        }
    }

    // map files
    if (MapUtils.isNotEmpty(textFileParams)) {
        for (String key : textFileParams.keySet()) {
            File file = new File(textFileParams.get(key));
            builder.addBinaryBody(key, file, ContentType.DEFAULT_TEXT, textFileParams.get(key));
        }
    }
    // map files
    if (MapUtils.isNotEmpty(binFileParams)) {
        for (String key : binFileParams.keySet()) {
            File file = new File(binFileParams.get(key));
            builder.addBinaryBody(key, file, ContentType.DEFAULT_BINARY, binFileParams.get(key));
        }
    }

    // set request
    HttpEntity multipart = builder.build();
    request.setEntity(multipart);

    // add request header
    request.addHeader("User-Agent", "YAIOCaller");

    // call url
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Sending 'PATCH' request to URL : " + baseUrl);
    }
    HttpResponse response = executeRequest(request, username, password);

    // get response
    int retCode = response.getStatusLine().getStatusCode();
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Response Code : " + retCode);
    }
    return response;
}

From source file:org.teiid.arquillian.IntegrationTestRestWebserviceGeneration.java

@Ignore
@Test/*from w w  w . j  av  a 2s  .  c o m*/
public void testMultipartPostOperation() throws Exception {
    deployVDB();
    assertTrue(AdminUtil.waitForVDBLoad(admin, "sample", 1, 3));

    this.internalConnection = TeiidDriver.getInstance()
            .connect("jdbc:teiid:sample@mm://localhost:31000;user=user;password=user", null);

    execute("SELECT * FROM Txns.G1"); //$NON-NLS-1$
    this.internalResultSet.next();

    assertTrue("sample_1.war not found", AdminUtil.waitForDeployment(admin, "sample_1.war", 5));

    String params = URLEncoder.encode("p1", "UTF-8") + "=" + URLEncoder.encode("456", "UTF-8");
    HttpEntity entity = MultipartEntityBuilder.create().addTextBody("p1", "456").build();

    // post based call with default
    String response = httpMultipartPost(entity, "http://localhost:8080/sample_1/View/g1post");
    assertEquals("response did not match expected",
            "<rows p1=\"456\" p2=\"1\"><row><e1>ABCDEFGHIJ</e1><e2>0</e2></row></rows>", response);

    // post based call
    entity = MultipartEntityBuilder.create().addTextBody("p1", "456").addTextBody("p2", "2")
            .addTextBody("p3", "string value")
            .addBinaryBody("p4", "<root><p4>bar</p4></root>".getBytes("UTF-8"),
                    ContentType.create("application/xml", "UTF-8"), "foo.xml")
            .build();
    response = httpMultipartPost(entity, "http://localhost:8080/sample_1/View/g1post");
    assertEquals("response did not match expected",
            "<rows p1=\"456\" p2=\"2\" p3=\"string value\" p4=\"bar\"><row><e1>ABCDEFGHIJ</e1><e2>0</e2></row></rows>",
            response);

    // ad-hoc procedure
    params = URLEncoder.encode("sql", "UTF-8") + "=" + URLEncoder.encode(
            "SELECT XMLELEMENT(NAME \"rows\", XMLAGG(XMLELEMENT(NAME \"row\", XMLFOREST(e1, e2)))) AS xml_out FROM Txns.G1",
            "UTF-8");
    response = httpCall("http://localhost:8080/sample_1/View/query", "POST", params);
    assertEquals("response did not match expected", "<rows><row><e1>ABCDEFGHIJ</e1><e2>0</e2></row></rows>",
            response);

    // blob multipost
    entity = MultipartEntityBuilder.create().addBinaryBody("p1", "<root><p4>bar</p4></root>".getBytes("UTF-8"),
            ContentType.create("application/xml", "UTF-8"), "foo.xml").build();
    response = httpMultipartPost(entity, "http://localhost:8080/sample_1/View/blobpost");
    assertEquals("response did not match expected", "<root><p4>bar</p4></root>", response);

    // clob multipost
    entity = MultipartEntityBuilder.create().addBinaryBody("p1", "<root><p4>bar</p4></root>".getBytes("UTF-8"),
            ContentType.create("application/xml", "UTF-8"), "foo.xml").build();
    response = httpMultipartPost(entity, "http://localhost:8080/sample_1/View/clobpost");
    assertEquals("response did not match expected", "<root><p4>bar</p4></root>", response);

    // varbinary multipost -- doesn't work as multipart is not expected
    entity = MultipartEntityBuilder.create()
            .addBinaryBody("p1",
                    Base64.encodeBytes("<root><p4>bar</p4></root>".getBytes("UTF-8")).getBytes("UTF-8"),
                    ContentType.create("application/xml", "UTF-8"), "foo.xml")
            .build();
    response = httpMultipartPost(entity, "http://localhost:8080/sample_1/View/binarypost");
    assertEquals("response did not match expected", "", response);

    params = URLEncoder.encode("p1", "UTF-8") + "="
            + URLEncoder.encode(Base64.encodeBytes("<root><p4>bar</p4></root>".getBytes("UTF-8")), "UTF-8");
    response = httpCall("http://localhost:8080/sample_1/View/binarypost", "POST", params);
    assertEquals("response did not match expected", "<root><p4>bar</p4></root>", response);

    admin.undeploy("sample-vdb.xml");
    Thread.sleep(2000);
}

From source file:org.ensembl.gti.seqstore.database.cramstore.EnaCramSubmitter.java

protected void submitXml(Collection<File> files) {
    try {//www  .ja v a2 s.c om
        HttpPost post = new HttpPost(submitUri.replaceAll("USERNAME", user).replaceAll("PASSWORD", password));
        Date date = new Date();
        File xml = getAnalysisXml(date, files);
        log.info("XML written to " + xml.getPath());
        File subXml = getSubmissionXml(date, xml);

        FileBody xmlBody = new FileBody(xml);
        FileBody subBody = new FileBody(subXml);
        HttpEntity entity = MultipartEntityBuilder.create().addPart("ANALYSIS", xmlBody)
                .addPart("SUBMISSION", subBody).build();
        post.setEntity(entity);

        log.info("Uploading XML as post");
        HttpResponse response = httpClient.execute(post);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new EnaSubmissionException(
                    "Could not submit XML to ENA: " + response.getStatusLine().toString());
        }
        log.info("Status: " + response.getStatusLine());
        String receipt = IOUtils.toString(response.getEntity().getContent());
        log.info("Receipt: " + receipt);
        Document receiptDoc = parseReceipt(receipt);

        if (isSuccess(receiptDoc)) {
            log.info("Successfully submitted to ENA with analysis accession "
                    + getElemAttrib(receiptDoc, "ANALYSIS", "accession") + " and submission accession "
                    + getElemAttrib(receiptDoc, "SUBMISSION", "accession"));
        } else {
            String msg = "Submission failed: " + StringUtils.join(getElems(receiptDoc, "ERROR"), "; ");
            log.error(msg);
            throw new EnaSubmissionException(msg);
        }
        for (File file : files) {
            log.info("Deleting file " + file);
            file.delete();
        }
        log.info("Completed submitting XML");
    } catch (IOException | UnsupportedOperationException e) {
        throw new EnaSubmissionException("Unexpected error during file submission", e);
    }
}

From source file:org.wso2.carbon.ml.integration.common.utils.MLHttpClient.java

/**
 * Upload a sample datatset from resources
 * //www  .j  av  a2s  .c  o m
 * @param datasetName   Name for the dataset
 * @param version       Version for the dataset
 * @param resourcePath  Relative path the CSV file in resources
 * @return              Response from the backend
 * @throws              MLHttpClientException 
 */
public CloseableHttpResponse uploadDatasetFromCSV(String datasetName, String version, String resourcePath)
        throws MLHttpClientException {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {
        HttpPost httpPost = new HttpPost(getServerUrlHttps() + "/api/datasets/");
        httpPost.setHeader(MLIntegrationTestConstants.AUTHORIZATION_HEADER, getBasicAuthKey());

        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        multipartEntityBuilder.addPart("description",
                new StringBody("Sample dataset for Testing", ContentType.TEXT_PLAIN));
        multipartEntityBuilder.addPart("sourceType", new StringBody("file", ContentType.TEXT_PLAIN));
        multipartEntityBuilder.addPart("destination", new StringBody("file", ContentType.TEXT_PLAIN));
        multipartEntityBuilder.addPart("dataFormat", new StringBody("CSV", ContentType.TEXT_PLAIN));
        multipartEntityBuilder.addPart("containsHeader", new StringBody("true", ContentType.TEXT_PLAIN));

        if (datasetName != null) {
            multipartEntityBuilder.addPart("datasetName", new StringBody(datasetName, ContentType.TEXT_PLAIN));
        }
        if (version != null) {
            multipartEntityBuilder.addPart("version", new StringBody(version, ContentType.TEXT_PLAIN));
        }
        if (resourcePath != null) {
            File file = new File(getResourceAbsolutePath(resourcePath));
            multipartEntityBuilder.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM,
                    "IndiansDiabetes.csv");
        }
        httpPost.setEntity(multipartEntityBuilder.build());
        return httpClient.execute(httpPost);
    } catch (Exception e) {
        throw new MLHttpClientException("Failed to upload dataset from csv " + resourcePath, e);
    }
}

From source file:com.frochr123.fabqr.FabQRFunctions.java

public static void uploadFabQRProject(String name, String email, String projectName, int licenseIndex,
        String tools, String description, String location, BufferedImage imageReal, BufferedImage imageScheme,
        PlfFile plfFile, String lasercutterName, String lasercutterMaterial) throws Exception {
    // Check for valid situation, otherwise abort
    if (MainView.getInstance() == null || VisicutModel.getInstance() == null
            || VisicutModel.getInstance().getPlfFile() == null || !isFabqrActive()
            || getFabqrPrivateURL() == null || getFabqrPrivateURL().isEmpty()
            || MaterialManager.getInstance() == null || MappingManager.getInstance() == null
            || VisicutModel.getInstance().getSelectedLaserDevice() == null) {
        throw new Exception("FabQR upload exception: Critical error");
    }//from www  . j  a  v a2 s . co  m

    // Check valid data
    if (name == null || email == null || projectName == null || projectName.length() < 3 || licenseIndex < 0
            || tools == null || tools.isEmpty() || description == null || description.isEmpty()
            || location == null || location.isEmpty() || imageScheme == null || plfFile == null
            || lasercutterName == null || lasercutterName.isEmpty() || lasercutterMaterial == null
            || lasercutterMaterial.isEmpty()) {
        throw new Exception("FabQR upload exception: Invalid input data");
    }

    // Convert images to byte data for PNG, imageReal is allowed to be empty
    byte[] imageSchemeBytes = null;
    ByteArrayOutputStream imageSchemeOutputStream = new ByteArrayOutputStream();
    PreviewImageExport.writePngToOutputStream(imageSchemeOutputStream, imageScheme);
    imageSchemeBytes = imageSchemeOutputStream.toByteArray();

    if (imageSchemeBytes == null) {
        throw new Exception("FabQR upload exception: Error converting scheme image");
    }

    byte[] imageRealBytes = null;

    if (imageReal != null) {
        // Need to convert image, ImageIO.write messes up the color space of the original input image
        BufferedImage convertedImage = new BufferedImage(imageReal.getWidth(), imageReal.getHeight(),
                BufferedImage.TYPE_3BYTE_BGR);
        ColorConvertOp op = new ColorConvertOp(null);
        op.filter(imageReal, convertedImage);

        ByteArrayOutputStream imageRealOutputStream = new ByteArrayOutputStream();
        ImageIO.write(convertedImage, "jpg", imageRealOutputStream);
        imageRealBytes = imageRealOutputStream.toByteArray();
    }

    // Extract all URLs from used QR codes
    List<String> referencesList = new LinkedList<String>();
    List<PlfPart> plfParts = plfFile.getPartsCopy();

    for (PlfPart plfPart : plfParts) {
        if (plfPart.getQRCodeInfo() != null && plfPart.getQRCodeInfo().getQRCodeSourceURL() != null
                && !plfPart.getQRCodeInfo().getQRCodeSourceURL().trim().isEmpty()) {
            // Process url, if it is URL of a FabQR system, remove download flag and point to project page instead
            // Use regex to check for FabQR system URL structure
            String qrCodeUrl = plfPart.getQRCodeInfo().getQRCodeSourceURL().trim();

            // Check for temporary URL structure of FabQR system
            Pattern fabQRUrlTemporaryPattern = Pattern
                    .compile("^https{0,1}://.*?" + "/" + FABQR_TEMPORARY_MARKER + "/" + "([a-z]|[0-9]){7,7}$");

            // Do not include link if it is just temporary
            if (fabQRUrlTemporaryPattern.matcher(qrCodeUrl).find()) {
                continue;
            }

            // Check for download URL structure of FabQR system
            // Change URL to point to project page instead
            Pattern fabQRUrlDownloadPattern = Pattern
                    .compile("^https{0,1}://.*?" + "/" + FABQR_DOWNLOAD_MARKER + "/" + "([a-z]|[0-9]){7,7}$");

            if (fabQRUrlDownloadPattern.matcher(qrCodeUrl).find()) {
                qrCodeUrl = qrCodeUrl.replace("/" + FABQR_DOWNLOAD_MARKER + "/", "/");
            }

            // Add URL if it is not yet in list
            if (!referencesList.contains(qrCodeUrl)) {
                referencesList.add(qrCodeUrl);
            }
        }
    }

    String references = "";

    for (String ref : referencesList) {
        // Add comma for non first entries
        if (!references.isEmpty()) {
            references = references + ",";
        }

        references = references + ref;
    }

    // Get bytes for PLF file
    byte[] plfFileBytes = null;
    ByteArrayOutputStream plfFileOutputStream = new ByteArrayOutputStream();
    VisicutModel.getInstance().savePlfToStream(MaterialManager.getInstance(), MappingManager.getInstance(),
            plfFileOutputStream);
    plfFileBytes = plfFileOutputStream.toByteArray();

    if (plfFileBytes == null) {
        throw new Exception("FabQR upload exception: Error saving PLF file");
    }

    // Begin uploading data
    String uploadUrl = getFabqrPrivateURL() + FABQR_API_UPLOAD_PROJECT;

    // Create HTTP client and cusomized config for timeouts
    CloseableHttpClient httpClient = HttpClients.createDefault();
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(FABQR_UPLOAD_TIMEOUT)
            .setConnectTimeout(FABQR_UPLOAD_TIMEOUT).setConnectionRequestTimeout(FABQR_UPLOAD_TIMEOUT).build();

    // Create HTTP Post request and entity builder
    HttpPost httpPost = new HttpPost(uploadUrl);
    httpPost.setConfig(requestConfig);
    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();

    // Insert file uploads
    multipartEntityBuilder.addBinaryBody("imageScheme", imageSchemeBytes, ContentType.APPLICATION_OCTET_STREAM,
            "imageScheme.png");
    multipartEntityBuilder.addBinaryBody("inputFile", plfFileBytes, ContentType.APPLICATION_OCTET_STREAM,
            "inputFile.plf");

    // Image real is allowed to be null, if it is not, send it
    if (imageRealBytes != null) {
        multipartEntityBuilder.addBinaryBody("imageReal", imageRealBytes, ContentType.APPLICATION_OCTET_STREAM,
                "imageReal.png");
    }

    // Prepare content type for text data, especially needed for correct UTF8 encoding
    ContentType contentType = ContentType.create("text/plain", Consts.UTF_8);

    // Insert text data
    multipartEntityBuilder.addTextBody("name", name, contentType);
    multipartEntityBuilder.addTextBody("email", email, contentType);
    multipartEntityBuilder.addTextBody("projectName", projectName, contentType);
    multipartEntityBuilder.addTextBody("licenseIndex", new Integer(licenseIndex).toString(), contentType);
    multipartEntityBuilder.addTextBody("tools", tools, contentType);
    multipartEntityBuilder.addTextBody("description", description, contentType);
    multipartEntityBuilder.addTextBody("location", location, contentType);
    multipartEntityBuilder.addTextBody("lasercutterName", lasercutterName, contentType);
    multipartEntityBuilder.addTextBody("lasercutterMaterial", lasercutterMaterial, contentType);
    multipartEntityBuilder.addTextBody("references", references, contentType);

    // Assign entity to this post request
    HttpEntity httpEntity = multipartEntityBuilder.build();
    httpPost.setEntity(httpEntity);

    // Set authentication information
    String encodedCredentials = Helper.getEncodedCredentials(FabQRFunctions.getFabqrPrivateUser(),
            FabQRFunctions.getFabqrPrivatePassword());
    if (!encodedCredentials.isEmpty()) {
        httpPost.addHeader("Authorization", "Basic " + encodedCredentials);
    }

    // Send request
    CloseableHttpResponse res = httpClient.execute(httpPost);

    // React to possible server side errors
    if (res.getStatusLine() == null || res.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new Exception("FabQR upload exception: Server sent wrong HTTP status code: "
                + new Integer(res.getStatusLine().getStatusCode()).toString());
    }

    // Close everything correctly
    res.close();
    httpClient.close();
}

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;
}