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

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

Introduction

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

Prototype

public HttpEntity build() 

Source Link

Usage

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

/**
 * /*from w w w.  j a v a  2s.  com*/
 * @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();
}

From source file:org.ednovo.gooru.application.server.service.uploadServlet.java

public String fileUpload(byte[] bytes, String data, String fileName, Long fileSize, String urlVal)
        throws Exception {
    String ret = "";
    logger.info("upload Url:::" + urlVal);
    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpPost httppost = new HttpPost(urlVal);
    MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create();
    ByteArrayBody bab = new ByteArrayBody(bytes, fileName);
    reqEntity.addPart("image", bab);
    httppost.setEntity(reqEntity.build());
    HttpResponse response = httpClient.execute(httppost);
    HttpEntity resEntity = response.getEntity();
    if (resEntity != null) {
        ret = EntityUtils.toString(resEntity);
    }//from  w ww .  ja va 2 s  .  c  o m
    logger.info("upload response:::" + ret);
    return ret;
}

From source file:org.flowable.app.service.editor.AppDefinitionPublishService.java

protected void deployZipArtifact(String artifactName, byte[] zipArtifact, String deploymentKey,
        String deploymentName) {/* ww  w.ja  v a  2  s. c  o  m*/
    String deployApiUrl = environment.getRequiredProperty("deployment.api.url");
    String basicAuthUser = environment.getRequiredProperty("idm.admin.user");
    String basicAuthPassword = environment.getRequiredProperty("idm.admin.password");

    if (deployApiUrl.endsWith("/") == false) {
        deployApiUrl = deployApiUrl.concat("/");
    }
    deployApiUrl = deployApiUrl
            .concat(String.format("repository/deployments?deploymentKey=%s&deploymentName=%s",
                    encode(deploymentKey), encode(deploymentName)));

    HttpPost httpPost = new HttpPost(deployApiUrl);
    httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + new String(
            Base64.encodeBase64((basicAuthUser + ":" + basicAuthPassword).getBytes(Charset.forName("UTF-8")))));

    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    entityBuilder.addBinaryBody("artifact", zipArtifact, ContentType.DEFAULT_BINARY, artifactName);

    HttpEntity entity = entityBuilder.build();
    httpPost.setEntity(entity);

    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    SSLConnectionSocketFactory sslsf = null;
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        sslsf = new SSLConnectionSocketFactory(builder.build(),
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        clientBuilder.setSSLSocketFactory(sslsf);
    } catch (Exception e) {
        logger.error("Could not configure SSL for http client", e);
        throw new InternalServerErrorException("Could not configure SSL for http client", e);
    }

    CloseableHttpClient client = clientBuilder.build();

    try {
        HttpResponse response = client.execute(httpPost);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
            return;
        } else {
            logger.error("Invalid deploy result code: {}", response.getStatusLine());
            throw new InternalServerErrorException("Invalid deploy result code: " + response.getStatusLine());
        }
    } catch (IOException ioe) {
        logger.error("Error calling deploy endpoint", ioe);
        throw new InternalServerErrorException("Error calling deploy endpoint: " + ioe.getMessage());
    } finally {
        if (client != null) {
            try {
                client.close();
            } catch (IOException e) {
                logger.warn("Exception while closing http client", e);
            }
        }
    }
}

From source file:org.kaaproject.kaa.client.transport.DesktopHttpClient.java

@Override
public byte[] executeHttpRequest(String uri, LinkedHashMap<String, byte[]> entity, boolean verifyResponse)
        throws Exception { //NOSONAR
    byte[] responseDataRaw = null;
    method = new HttpPost(url + uri);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    for (String key : entity.keySet()) {
        builder.addBinaryBody(key, entity.get(key));
    }//  ww  w.  j a v  a2 s. c  om
    HttpEntity requestEntity = builder.build();
    method.setEntity(requestEntity);
    if (!Thread.currentThread().isInterrupted()) {
        LOG.debug("Executing request {}", method.getRequestLine());
        CloseableHttpResponse response = httpClient.execute(method);
        try {
            LOG.debug("Received {}", response.getStatusLine());
            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status < 300) {
                responseDataRaw = getResponseBody(response, verifyResponse);
            } else {
                throw new TransportException(status);
            }
        } finally {
            response.close();
            method = null;
        }
    } else {
        method = null;
        throw new InterruptedException();
    }

    return responseDataRaw;
}

From source file:org.kochka.android.weightlogger.tools.GarminConnect.java

public boolean uploadFitFile(File fitFile) {
    if (httpclient == null)
        return false;
    try {/* ww w  . j a  v  a2 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 {/*from  w  ww.j  a v  a 2s.c om*/
        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  www .  java 2s  . c  om*/

    // 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("");
    }//w  w  w.j a v  a 2s. c  om

    // 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("");
    }/*from   ww w  . ja  va 2  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.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;/*  ww w . ja  v a  2s.  c o  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;
}