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:org.kochka.android.weightlogger.tools.GarminConnect.java

public boolean uploadFitFile(File fitFile) {
    if (httpclient == null)
        return false;
    try {//w  ww  . j  a  v  a  2 s  . co  m
        HttpPost post = new HttpPost("http://connect.garmin.com/proxy/upload-service-1.1/json/upload/.fit");

        /*
        SimpleMultipartEntity mpEntity = new SimpleMultipartEntity();
        mpEntity.addPart("data", fitFile);
        mpEntity.addPart("responseContentType", "text/html");
        post.setEntity(mpEntity);
        */

        MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
        multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        multipartEntity.addBinaryBody("data", fitFile);
        multipartEntity.addTextBody("responseContentType", "text/html");
        post.setEntity(multipartEntity.build());

        HttpEntity entity = httpclient.execute(post).getEntity();
        JSONObject js_upload = new JSONObject(EntityUtils.toString(entity));
        entity.consumeContent();
        if (js_upload.getJSONObject("detailedImportResult").getJSONArray("failures").length() != 0)
            throw new Exception("upload error");

        return true;
    } catch (Exception e) {
        return false;
    }
}

From source file:org.kohsuke.stapler.RequestImplTest.java

private byte[] generateMultipartData() throws IOException {
    MultipartEntityBuilder reqEntityBuilder = MultipartEntityBuilder.create();

    reqEntityBuilder.setBoundary("mpboundary");
    reqEntityBuilder.addBinaryBody("pomFile", new File("./pom.xml"), ContentType.TEXT_XML, "pom.xml");
    reqEntityBuilder.addTextBody("text1", "text1_val");
    reqEntityBuilder.addTextBody("text2", "text2_val");

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try {//ww  w  .j ava2 s  . com
        reqEntityBuilder.build().writeTo(outputStream);
        outputStream.flush();
        return outputStream.toByteArray();
    } finally {
        outputStream.close();
    }
}

From source file:org.mule.modules.wechat.common.HttpsConnection.java

public Map<String, Object> postFile(String httpsURL, DataHandler attachment) throws Exception {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost post = new HttpPost(httpsURL);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();

    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    // Get extension of attachment
    TikaConfig config = TikaConfig.getDefaultConfig();
    MimeTypes allTypes = config.getMimeRepository();
    String ext = allTypes.forName(attachment.getContentType()).getExtension();
    if (ext.equals("")) {
        ContentTypeEnum contentTypeEnum = ContentTypeEnum
                .getContentTypeEnumByContentType(attachment.getContentType().toLowerCase());
        ext = java.util.Optional.ofNullable(contentTypeEnum.getExtension()).orElse("");
    }//from  w w  w .  ja  v a 2s.  co m

    // Create file
    InputStream fis = attachment.getInputStream();
    byte[] bytes = IOUtils.toByteArray(fis);
    File f = new File(
            System.getProperty("user.dir") + "/fileTemp/" + attachment.getName().replace(ext, "") + ext);
    FileUtils.writeByteArrayToFile(f, bytes);
    builder.addBinaryBody("media", f);

    // Post to wechat
    HttpEntity entity = builder.build();
    post.setEntity(entity);
    CloseableHttpResponse httpResponse = httpClient.execute(post);
    String content = "";
    try {
        HttpEntity _entity = httpResponse.getEntity();
        content = EntityUtils.toString(_entity);
        EntityUtils.consume(_entity);
    } finally {
        httpResponse.close();
    }
    f.delete();

    // Convert JSON string to Map
    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> map = mapper.readValue(content, new TypeReference<Map<String, Object>>() {
    });

    return map;
}

From source file:org.mule.modules.wechat.common.HttpsConnection.java

public Map<String, Object> postFile(String httpsURL, String title, DataHandler attachment) throws Exception {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost post = new HttpPost(httpsURL);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();

    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    // Get extension of attachment
    TikaConfig config = TikaConfig.getDefaultConfig();
    MimeTypes allTypes = config.getMimeRepository();
    String ext = allTypes.forName(attachment.getContentType()).getExtension();
    if (ext.equals("")) {
        ContentTypeEnum contentTypeEnum = ContentTypeEnum
                .getContentTypeEnumByContentType(attachment.getContentType().toLowerCase());
        ext = java.util.Optional.ofNullable(contentTypeEnum.getExtension()).orElse("");
    }//from  w  w  w  .ja  v  a 2s  .c  o m

    // Create file
    InputStream fis = attachment.getInputStream();
    byte[] bytes = IOUtils.toByteArray(fis);
    File f = new File(System.getProperty("user.dir") + "/fileTemp/" + title + ext);
    FileUtils.writeByteArrayToFile(f, bytes);
    builder.addBinaryBody("media", f);

    // Post to wechat
    HttpEntity entity = builder.build();
    post.setEntity(entity);
    CloseableHttpResponse httpResponse = httpClient.execute(post);
    String content = "";
    try {
        HttpEntity _entity = httpResponse.getEntity();
        content = EntityUtils.toString(_entity);
        EntityUtils.consume(_entity);
    } finally {
        httpResponse.close();
    }
    f.delete();

    // Convert JSON string to Map
    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> map = mapper.readValue(content, new TypeReference<Map<String, Object>>() {
    });

    return map;
}

From source file:org.mule.modules.wechat.common.HttpsConnection.java

public Map<String, Object> postFile(String httpsURL, String title, String introduction, DataHandler attachment)
        throws Exception {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost post = new HttpPost(httpsURL);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();

    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    // Get extension of attachment
    TikaConfig config = TikaConfig.getDefaultConfig();
    MimeTypes allTypes = config.getMimeRepository();
    String ext = allTypes.forName(attachment.getContentType()).getExtension();
    if (ext.equals("")) {
        ContentTypeEnum contentTypeEnum = ContentTypeEnum
                .getContentTypeEnumByContentType(attachment.getContentType().toLowerCase());
        ext = java.util.Optional.ofNullable(contentTypeEnum.getExtension()).orElse("");
    }//  w  w w .  j  a  v a2 s  .c  o m

    // Create file
    InputStream fis = attachment.getInputStream();
    byte[] bytes = IOUtils.toByteArray(fis);
    File f = new File(System.getProperty("user.dir") + "/fileTemp/" + title + ext);
    FileUtils.writeByteArrayToFile(f, bytes);

    // Create JSON
    JSONObject obj = new JSONObject();
    obj.put("title", title);
    obj.put("introduction", introduction);
    ContentType contentType = ContentType.create("text/plain", Charset.forName("UTF-8"));
    builder.addBinaryBody("media", f);
    builder.addTextBody("description", obj.toString(), contentType);

    // Post to wechat
    HttpEntity entity = builder.build();
    post.setEntity(entity);
    CloseableHttpResponse httpResponse = httpClient.execute(post);
    String content = "";
    try {
        HttpEntity _entity = httpResponse.getEntity();
        content = EntityUtils.toString(_entity);
        EntityUtils.consume(_entity);
    } finally {
        httpResponse.close();
    }
    f.delete();

    // Convert JSON string to Map
    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> map = mapper.readValue(content, new TypeReference<Map<String, Object>>() {
    });

    return map;
}

From source file:org.olat.restapi.GroupFoldersTest.java

@Test
public void testCreateFoldersWithSpecialCharacter2() throws IOException, URISyntaxException {
    assertTrue(conn.login("rest-one", "A6B7C8"));
    URI request = UriBuilder.fromUri(getContextURI())
            .path("/groups/" + g1.getKey() + "/folder/New_folder_1/New_folder_1_1/").build();
    HttpPut method = conn.createPut(request, MediaType.APPLICATION_JSON, true);
    HttpEntity entity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
            .addTextBody("foldername", "New folder 1 2 3").build();
    method.setEntity(entity);/*from   www  . ja v  a 2s . c  o m*/

    HttpResponse response = conn.execute(method);
    assertEquals(200, response.getStatusLine().getStatusCode());
    FileVO file = conn.parse(response, FileVO.class);
    assertNotNull(file);
    assertNotNull(file.getHref());
    assertNotNull(file.getTitle());
    assertEquals("New folder 1 2 3", file.getTitle());
}

From source file:org.olat.restapi.RestConnection.java

public void addMultipart(HttpEntityEnclosingRequestBase post, String filename, File file)
        throws UnsupportedEncodingException {

    HttpEntity entity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
            .addTextBody("filename", filename)
            .addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM, filename).build();
    post.setEntity(entity);//w w w .  j a  v a2 s.  c om
}

From source file:org.opendatakit.briefcase.util.AggregateUtils.java

public static final boolean uploadFilesToServer(ServerConnectionInfo serverInfo, URI u,
        String distinguishedFileTagName, File file, List<File> files, DocumentDescription description,
        SubmissionResponseAction action, TerminationFuture terminationFuture, FormStatus formToTransfer) {

    boolean allSuccessful = true;
    formToTransfer.setStatusString("Preparing for upload of " + description.getDocumentDescriptionType()
            + " with " + files.size() + " media attachments", true);
    EventBus.publish(new FormStatusEvent(formToTransfer));

    boolean first = true; // handles case where there are no media files
    int lastJ = 0;
    int j = 0;//from   www.  j  a  va2s.  co  m
    while (j < files.size() || first) {
        lastJ = j;
        first = false;

        if (terminationFuture.isCancelled()) {
            formToTransfer.setStatusString("Aborting upload of " + description.getDocumentDescriptionType()
                    + " with " + files.size() + " media attachments", true);
            EventBus.publish(new FormStatusEvent(formToTransfer));
            return false;
        }

        HttpPost httppost = WebUtils.createOpenRosaHttpPost(u);

        long byteCount = 0L;

        // mime post
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();

        // add the submission file first...
        FileBody fb = new FileBody(file, ContentType.TEXT_XML);
        builder.addPart(distinguishedFileTagName, fb);
        log.info("added " + distinguishedFileTagName + ": " + file.getName());
        byteCount += file.length();

        for (; j < files.size(); j++) {
            File f = files.get(j);
            String fileName = f.getName();
            int idx = fileName.lastIndexOf(".");
            String extension = "";
            if (idx != -1) {
                extension = fileName.substring(idx + 1);
            }

            // we will be processing every one of these, so
            // we only need to deal with the content type determination...
            if (extension.equals("xml")) {
                fb = new FileBody(f, ContentType.TEXT_XML);
                builder.addPart(f.getName(), fb);
                byteCount += f.length();
                log.info("added xml file " + f.getName());
            } else if (extension.equals("jpg")) {
                fb = new FileBody(f, ContentType.create("image/jpeg"));
                builder.addPart(f.getName(), fb);
                byteCount += f.length();
                log.info("added image file " + f.getName());
            } else if (extension.equals("3gpp")) {
                fb = new FileBody(f, ContentType.create("audio/3gpp"));
                builder.addPart(f.getName(), fb);
                byteCount += f.length();
                log.info("added audio file " + f.getName());
            } else if (extension.equals("3gp")) {
                fb = new FileBody(f, ContentType.create("video/3gpp"));
                builder.addPart(f.getName(), fb);
                byteCount += f.length();
                log.info("added video file " + f.getName());
            } else if (extension.equals("mp4")) {
                fb = new FileBody(f, ContentType.create("video/mp4"));
                builder.addPart(f.getName(), fb);
                byteCount += f.length();
                log.info("added video file " + f.getName());
            } else if (extension.equals("csv")) {
                fb = new FileBody(f, ContentType.create("text/csv"));
                builder.addPart(f.getName(), fb);
                byteCount += f.length();
                log.info("added csv file " + f.getName());
            } else if (extension.equals("xls")) {
                fb = new FileBody(f, ContentType.create("application/vnd.ms-excel"));
                builder.addPart(f.getName(), fb);
                byteCount += f.length();
                log.info("added xls file " + f.getName());
            } else {
                fb = new FileBody(f, ContentType.create("application/octet-stream"));
                builder.addPart(f.getName(), fb);
                byteCount += f.length();
                log.warn("added unrecognized file (application/octet-stream) " + f.getName());
            }

            // we've added at least one attachment to the request...
            if (j + 1 < files.size()) {
                if ((j - lastJ + 1) > 100 || byteCount + files.get(j + 1).length() > 10000000L) {
                    // more than 100 attachments or the next file would exceed the 10MB threshold...
                    log.info("Extremely long post is being split into multiple posts");
                    try {
                        StringBody sb = new StringBody("yes",
                                ContentType.DEFAULT_TEXT.withCharset(Charset.forName("UTF-8")));
                        builder.addPart("*isIncomplete*", sb);
                    } catch (Exception e) {
                        log.error("impossible condition", e);
                        throw new IllegalStateException("never happens");
                    }
                    ++j; // advance over the last attachment added...
                    break;
                }
            }
        }

        httppost.setEntity(builder.build());

        int[] validStatusList = { 201 };

        try {
            if (j != files.size()) {
                formToTransfer.setStatusString("Uploading " + description.getDocumentDescriptionType()
                        + " and media files " + (lastJ + 1) + " through " + (j + 1) + " of " + files.size()
                        + " media attachments", true);
            } else if (j == 0) {
                formToTransfer.setStatusString(
                        "Uploading " + description.getDocumentDescriptionType() + " with no media attachments",
                        true);
            } else {
                formToTransfer.setStatusString("Uploading " + description.getDocumentDescriptionType() + " and "
                        + (j - lastJ) + ((lastJ != 0) ? " remaining" : "") + " media attachments", true);
            }
            EventBus.publish(new FormStatusEvent(formToTransfer));

            httpRetrieveXmlDocument(httppost, validStatusList, serverInfo, false, description, action);
        } catch (XmlDocumentFetchException e) {
            allSuccessful = false;
            log.error("upload failed", e);
            formToTransfer.setStatusString("UPLOAD FAILED: " + e.getMessage(), false);
            EventBus.publish(new FormStatusEvent(formToTransfer));

            if (description.isCancelled())
                return false;
        }
    }

    return allSuccessful;
}

From source file:org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest.java

public RestResponse httpSendPostMultipart(String url, Map<String, String> headers, String jsonLocation,
        String zipLocation) throws IOException {

    Gson gson = new Gson();
    String gsonToSend = null;//from ww  w .  ja  va2  s  .c o m
    RestResponse restResponse = new RestResponse();
    BufferedReader br = null;
    //
    //
    //
    //
    // try {
    //
    // String sCurrentLine;
    //
    // br = new BufferedReader(new FileReader(jsonLocation));
    //
    // while ((sCurrentLine = br.readLine()) != null) {
    // System.out.println(sCurrentLine);
    // }
    //
    // } catch (IOException e) {
    // e.printStackTrace();
    // } finally {
    // try {
    // if (br != null)br.close();
    // gsonToSend = br.toString();
    // } catch (IOException ex) {
    // ex.printStackTrace();
    // }
    // }

    gsonToSend = new Scanner(new File(jsonLocation)).useDelimiter("\\Z").next();
    logger.debug("gsonToSend: {}", gsonToSend);

    MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
    mpBuilder.addPart("resourceZip", new FileBody(new File(zipLocation)));
    mpBuilder.addPart("resourceMetadata", new StringBody(gsonToSend, ContentType.APPLICATION_JSON));

    HttpPost httpPost = new HttpPost(url);
    httpPost.addHeader("USER_ID", "adminid");
    httpPost.setEntity(mpBuilder.build());

    CloseableHttpClient client = HttpClients.createDefault();
    CloseableHttpResponse response = client.execute(httpPost);
    try {
        logger.debug("----------------------------------------");
        logger.debug("response.getStatusLine(): {}", response.getStatusLine());
        HttpEntity resEntity = response.getEntity();
        if (resEntity != null) {
            logger.debug("Response content length: {}", resEntity.getContentLength());
        }
        EntityUtils.consume(resEntity);
    } finally {

        response.close();
        client.close();
    }

    restResponse.setErrorCode(response.getStatusLine().getStatusCode());
    restResponse.setResponse(response.getEntity().toString());

    return restResponse;

}

From source file:org.openecomp.sdc.ci.tests.execute.category.CategoriesTests.java

License:asdf

@Test
public void importCategories() throws Exception {

    String importResourceDir = config.getImportTypesConfigDir() + File.separator + "categoryTypesTest.zip";

    MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
    mpBuilder.addPart("categoriesZip", new FileBody(new File(importResourceDir)));

    RestResponse importResult = CategoryRestUtils.importCategories(mpBuilder, sdncAdminUserDetails.getUserId());
    assertEquals("Check response code after Import", BaseRestUtils.STATUS_CODE_CREATED,
            importResult.getErrorCode().intValue());

    Map<String, Object> map = ResponseParser.parseToObjectUsingMapper(importResult.getResponse(), Map.class);
    assertEquals("Check  entries count", 2, map.size());

    List<Map<String, Object>> resources = (List<Map<String, Object>>) map.get("resources");
    assertEquals("Check resource category  entries count", 1, resources.size());

    List<Map<String, Object>> services = (List<Map<String, Object>>) map.get("services");
    assertEquals("Check resource category  entries count", 2, services.size());

    RestResponse allCategories = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, "resources");
    List<CategoryDefinition> resourceCategories = ResponseParser.parseCategories(allCategories);
    for (Map<String, Object> resource : resources) {
        boolean exist = false;

        for (CategoryDefinition categ : resourceCategories) {
            if (categ.getName().equals(resource.get("name"))) {
                exist = true;//from ww  w .  j a  v a 2 s  . c o m
                break;
            }
        }
        assertTrue("Check existance resource category  " + resource.get("name"), exist);
    }

    allCategories = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, "services");
    List<CategoryDefinition> servicesCategories = ResponseParser.parseCategories(allCategories);
    for (Map<String, Object> service : services) {
        boolean exist = false;

        for (CategoryDefinition categ : servicesCategories) {
            if (categ.getName().equals(service.get("name"))) {
                exist = true;
                break;
            }
        }
        assertTrue("Check existance service category  " + service.get("name"), exist);
    }
}