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

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

Introduction

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

Prototype

public MultipartEntityBuilder addPart(final String name, final ContentBody contentBody) 

Source Link

Usage

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

/**
 * Upload a sample datatset from resources
 * //from ww  w .j a  v a 2s .com
 * @param datasetName   Name for the dataset
 * @param version       Version for the dataset
 * @param tableName  Relative path the CSV file in resources
 * @return              Response from the backend
 * @throws              MLHttpClientException 
 */
public CloseableHttpResponse uploadDatasetFromDAS(String datasetName, String version, String tableName)
        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("das", ContentType.TEXT_PLAIN));
        multipartEntityBuilder.addPart("destination", new StringBody("file", ContentType.TEXT_PLAIN));
        multipartEntityBuilder.addPart("dataFormat", new StringBody("CSV", ContentType.TEXT_PLAIN));
        multipartEntityBuilder.addPart("sourcePath", new StringBody(tableName, 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));
        }
        multipartEntityBuilder.addBinaryBody("file", new byte[] {}, 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 DAS " + tableName, e);
    }
}

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

/**
 * Upload a sample datatset from resources
 * /*w ww .  j  a va 2 s. c om*/
 * @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.google.appinventor.components.runtime.MediaStore.java

/**
 * Asks the Web service to store the given media file.
 *
 * @param mediafile The value to store./* w ww.ja  va2  s  .co  m*/
 */
@SimpleFunction
public void PostMedia(String mediafile) throws FileNotFoundException {
    AsyncCallbackPair<String> myCallback = new AsyncCallbackPair<String>() {
        public void onSuccess(final String response) {
            androidUIHandler.post(new Runnable() {
                public void run() {
                    MediaStored(response);
                }
            });
        }

        public void onFailure(final String message) {
            androidUIHandler.post(new Runnable() {
                public void run() {
                    WebServiceError(message);
                }
            });
        }
    };

    try {
        HttpClient client = new DefaultHttpClient();

        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
        entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

        String[] pathtokens = mediafile.split("/");
        String newMediaPath;

        if (pathtokens[0].equals("file:")) {
            newMediaPath = new java.io.File(new URL(mediafile).toURI()).getAbsolutePath();
        } else {
            newMediaPath = mediafile;
        }

        File media = new File(newMediaPath);
        entityBuilder.addPart("file", new FileBody(media));

        HttpEntity entity = entityBuilder.build();

        String uploadURL = getUploadUrl();
        HttpPost post = new HttpPost(uploadURL);
        post.setEntity(entity);
        HttpResponse response = client.execute(post);

        HttpEntity httpEntity = response.getEntity();
        String result = EntityUtils.toString(httpEntity);
        myCallback.onSuccess(result);
    } catch (Exception e) {
        e.printStackTrace();
        myCallback.onFailure(e.getMessage());
    }
}

From source file:org.syncany.plugins.php.PhpTransferManager.java

@Override
public void upload(File localFile, RemoteFile remoteFile) throws StorageException {
    logger.info("Uploading: " + localFile.getName() + " to " + remoteFile.getName());
    try {/*  w  ww  .j av a 2 s .c o  m*/
        final String remote_name = remoteFile.getName();
        final File f = localFile;
        int r = operate("upload", new IPost() {
            List<NameValuePair> _nvps;

            public void mutateNVPS(List<NameValuePair> nvps) throws Exception {
                _nvps = nvps;
                nvps.add(new BasicNameValuePair("filename", remote_name));
            }

            public int mutatePost(HttpPost p) throws Exception {
                MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
                builder.addPart("file", new FileBody(f));
                Iterator<NameValuePair> it = _nvps.iterator();
                while (it.hasNext()) {
                    NameValuePair nvp = it.next();
                    builder.addTextBody(nvp.getName(), nvp.getValue());
                }
                p.setEntity(builder.build());
                return -1;
            }

            @Override
            public int consumeResponse(InputStream s) throws Exception {
                String response = getAnswer(s);
                if (response.equals("true")) {
                    return 1;
                } else {
                    throw new Exception(response);
                }
            }

        });
        if (r != 1) {
            throw new Exception("Unexpected error, result code = " + r);
        }

    } catch (Exception e) {
        throw new StorageException("Cannot upload file " + remoteFile, e);
    }
}

From source file:com.osbitools.ws.shared.web.BasicWebUtils.java

public WebResponse uploadFile(String path, String fname, InputStream in, String stoken)
        throws ClientProtocolException, IOException {

    HttpPost post = new HttpPost(path);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    StringBody fn = new StringBody(fname, ContentType.MULTIPART_FORM_DATA);

    builder.addPart("fname", fn);
    builder.addBinaryBody("file", in, ContentType.APPLICATION_XML, fname);

    BasicCookieStore cookieStore = new BasicCookieStore();

    if (stoken != null) {
        BasicClientCookie cookie = new BasicClientCookie(Constants.SECURE_TOKEN_NAME, stoken);
        cookie.setDomain(TestConstants.JETTY_HOST);
        cookie.setPath("/");
        cookieStore.addCookie(cookie);//  w w w  . j  ava2s .  co m
    }

    TestConstants.LOG.debug("stoken=" + stoken);
    HttpClient client = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();
    HttpEntity entity = builder.build();

    post.setEntity(entity);
    HttpResponse response = client.execute(post);

    String body;
    ResponseHandler<String> handler = new BasicResponseHandler();
    try {
        body = handler.handleResponse(response);
    } catch (HttpResponseException e) {
        return new WebResponse(e.getStatusCode(), e.getMessage());
    }

    return new WebResponse(response.getStatusLine().getStatusCode(), body);
}

From source file:net.monofraps.gradlecurse.tasks.CurseDeployTask.java

private void uploadArtifact(final Deployment deployment) {
    getLogger().lifecycle("Curse Upload: " + "Uploading to Curse...");
    getLogger().lifecycle("Curse Upload: " + deployment.toString());

    //TODO: binary or app/zip, maybe an option or auto-detect from file extension ?!
    final FileBody fileBody = new FileBody(deployment.getSourceFile(), ContentType.DEFAULT_BINARY,
            deployment.getUploadFileName());

    final MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
    multipartEntityBuilder.addTextBody("name", deployment.getUploadFileName());
    multipartEntityBuilder.addTextBody("file_type", deployment.getFileType().toString());
    multipartEntityBuilder.addTextBody("change_log", deployment.getChangeLog());
    multipartEntityBuilder.addTextBody("change_markup_type", deployment.getChangeLogMarkup().toString());
    multipartEntityBuilder.addTextBody("known_caveats", deployment.getKnownCaveats());
    multipartEntityBuilder.addTextBody("caveats_markup_type", deployment.getCaveatMarkup().toString());
    multipartEntityBuilder.addPart("file", fileBody);
    multipartEntityBuilder.addTextBody("game_versions", StringUtils.join(deployment.getGameVersions(), ","));

    try {/*from w w  w .ja  v a2s  . c o  m*/
        final HttpPost httpPost = new HttpPost(probeForRedirect(deployment));
        httpPost.addHeader("User-Agent", "GradleCurse Uploader/1.0");
        httpPost.addHeader("X-API-Key", deployment.getApiKey());
        httpPost.setEntity(multipartEntityBuilder.build());

        final HttpClient httpClient = HttpClientBuilder.create().build();
        final HttpResponse httpResponse = httpClient.execute(httpPost);

        getLogger().lifecycle("Curse Upload: " + httpResponse.getStatusLine());
        getLogger().debug(EntityUtils.toString(httpResponse.getEntity()));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.ebixio.virtmus.stats.StatsLogger.java

/** Should only be called from uploadLogs(). Compresses all files that belong
 to the given log set, and uploads all compressed files to the server. */
private boolean uploadLogs(final String logSet) {
    if (logSet == null)
        return false;

    File logsDir = getLogsDir();//from  ww w .j a v  a2 s. c  o  m
    if (logsDir == null)
        return false;
    gzipLogs(logsDir, logSet);

    // Uploading only gz'd files
    FilenameFilter gzFilter = new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.toLowerCase().endsWith(".gz");
        }
    };
    File[] toUpload = logsDir.listFiles(gzFilter);

    String url = getUploadUrl();
    if (url == null) {
        /* This means the server is unable to accept the logs. */
        keepRecents(toUpload, 100);
        return false;
    }

    CloseableHttpClient client = HttpClients.createDefault();
    HttpPost post = new HttpPost(url);
    addHttpHeaders(post);

    MultipartEntityBuilder entity = MultipartEntityBuilder.create();
    entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    entity.addPart("InstallId", new StringBody(String.valueOf(MainApp.getInstallId()), ContentType.TEXT_PLAIN));

    ContentType ct = ContentType.create("x-application/gzip");
    for (File f : toUpload) {
        entity.addPart("VirtMusStats", new FileBody(f, ct, f.getName()));
    }
    post.setEntity(entity.build());

    boolean success = false;
    try (CloseableHttpResponse response = client.execute(post)) {
        int status = response.getStatusLine().getStatusCode();
        Log.log(Level.INFO, "Log upload result: {0}", status);
        if (status == HttpStatus.SC_OK) { // 200
            for (File f : toUpload) {
                try {
                    f.delete();
                } catch (SecurityException ex) {
                }
            }
            success = true;
        } else {
            LogRecord rec = new LogRecord(Level.INFO, "Server Err");
            rec.setParameters(new Object[] { url, "Status: " + status });
            getLogger().log(rec);
        }

        HttpEntity rspEntity = response.getEntity();
        EntityUtils.consume(rspEntity);
        client.close();
    } catch (IOException ex) {
        Log.log(ex);
    }

    keepRecents(toUpload, 100); // In case of exceptions or errors
    return success;
}

From source file:com.shenit.commons.utils.HttpUtils.java

/**
 * Create a multipart form//from  w  w  w.j  ava2 s. c o  m
 * 
 * @param request
 *            Request object
 * @param keyVals
 *            Key and value pairs, the even(begins with 0) position params
 *            are key and the odds are values
 * @return
 */
public static HttpUriRequest multipartForm(HttpPost request, Object... keyVals) {
    if (request == null || ValidationUtils.isEmpty(keyVals))
        return request;
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    boolean hasVal = false;

    String key;
    for (int i = 0; i < keyVals.length; i += 2) {
        key = ShenStrings.str(keyVals[i]);
        hasVal = i + 1 < keyVals.length;

        if (!hasVal || keyVals[i + 1] == null) {
            builder.addTextBody(key, StringUtils.EMPTY, CONTENT_TYPE_PLAIN_TEXT);
            break;
        }

        if (keyVals[i + 1].getClass().isAssignableFrom(File.class)) {
            builder.addPart(key, new FileBody((File) keyVals[i + 1]));
        } else {
            builder.addTextBody(key, keyVals[i + 1].toString(), CONTENT_TYPE_PLAIN_TEXT);
        }
    }
    request.setEntity(builder.build());
    return request;
}

From source file:com.liferay.sync.engine.session.Session.java

private MultipartEntityBuilder _getMultipartEntityBuilder(Map<String, Object> parameters) {

    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();

    for (Map.Entry<String, Object> entry : parameters.entrySet()) {
        if (_ignoredParameterKeys.contains(entry.getKey())) {
            continue;
        }/*w  ww . j a  v a2  s  .c  om*/

        multipartEntityBuilder.addPart(entry.getKey(), _getStringBody(entry.getValue()));
    }

    return multipartEntityBuilder;
}

From source file:com.mirth.connect.connectors.http.HttpDispatcher.java

private HttpRequestBase buildHttpRequest(URI hostURI, HttpDispatcherProperties httpDispatcherProperties,
        ConnectorMessage connectorMessage, File tempFile, ContentType contentType, Charset charset)
        throws Exception {
    String method = httpDispatcherProperties.getMethod();
    boolean isMultipart = httpDispatcherProperties.isMultipart();
    Map<String, List<String>> headers = httpDispatcherProperties.getHeaders();
    Map<String, List<String>> parameters = httpDispatcherProperties.getParameters();

    Object content = null;//from w  w  w . ja va2s.  c  om
    if (httpDispatcherProperties.isDataTypeBinary()) {
        content = getAttachmentHandlerProvider().reAttachMessage(httpDispatcherProperties.getContent(),
                connectorMessage, null, true);
    } else {
        content = getAttachmentHandlerProvider().reAttachMessage(httpDispatcherProperties.getContent(),
                connectorMessage);

        // If text mode is used and a specific charset isn't already defined, use the one from the connector properties
        if (contentType.getCharset() == null) {
            contentType = HttpMessageConverter.setCharset(contentType, charset);
        }
    }

    // populate the query parameters
    List<NameValuePair> queryParameters = new ArrayList<NameValuePair>(parameters.size());

    for (Entry<String, List<String>> parameterEntry : parameters.entrySet()) {
        for (String value : parameterEntry.getValue()) {
            logger.debug("setting query parameter: [" + parameterEntry.getKey() + ", " + value + "]");
            queryParameters.add(new BasicNameValuePair(parameterEntry.getKey(), value));
        }
    }

    HttpRequestBase httpMethod = null;
    HttpEntity httpEntity = null;
    URIBuilder uriBuilder = new URIBuilder(hostURI);

    // create the method
    if ("GET".equalsIgnoreCase(method)) {
        setQueryString(uriBuilder, queryParameters);
        httpMethod = new HttpGet(uriBuilder.build());
    } else if ("POST".equalsIgnoreCase(method)) {
        if (isMultipart) {
            logger.debug("setting multipart file content");
            setQueryString(uriBuilder, queryParameters);
            httpMethod = new HttpPost(uriBuilder.build());

            if (content instanceof String) {
                FileUtils.writeStringToFile(tempFile, (String) content, contentType.getCharset(), false);
            } else {
                FileUtils.writeByteArrayToFile(tempFile, (byte[]) content, false);
            }

            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            multipartEntityBuilder.addPart(tempFile.getName(),
                    new FileBody(tempFile, contentType, tempFile.getName()));
            httpEntity = multipartEntityBuilder.build();
        } else if (StringUtils.startsWithIgnoreCase(contentType.getMimeType(),
                ContentType.APPLICATION_FORM_URLENCODED.getMimeType())) {
            httpMethod = new HttpPost(uriBuilder.build());
            httpEntity = new UrlEncodedFormEntity(queryParameters, contentType.getCharset());
        } else {
            setQueryString(uriBuilder, queryParameters);
            httpMethod = new HttpPost(uriBuilder.build());

            if (content instanceof String) {
                httpEntity = new StringEntity((String) content, contentType);
            } else {
                httpEntity = new ByteArrayEntity((byte[]) content);
            }
        }
    } else if ("PUT".equalsIgnoreCase(method)) {
        if (StringUtils.startsWithIgnoreCase(contentType.getMimeType(),
                ContentType.APPLICATION_FORM_URLENCODED.getMimeType())) {
            httpMethod = new HttpPut(uriBuilder.build());
            httpEntity = new UrlEncodedFormEntity(queryParameters, contentType.getCharset());
        } else {
            setQueryString(uriBuilder, queryParameters);
            httpMethod = new HttpPut(uriBuilder.build());

            if (content instanceof String) {
                httpEntity = new StringEntity((String) content, contentType);
            } else {
                httpEntity = new ByteArrayEntity((byte[]) content);
            }
        }
    } else if ("DELETE".equalsIgnoreCase(method)) {
        setQueryString(uriBuilder, queryParameters);
        httpMethod = new HttpDelete(uriBuilder.build());
    }

    if (httpMethod instanceof HttpEntityEnclosingRequestBase) {
        // Compress the request entity if necessary
        List<String> contentEncodingList = (List<String>) new CaseInsensitiveMap(headers)
                .get(HTTP.CONTENT_ENCODING);
        if (CollectionUtils.isNotEmpty(contentEncodingList)) {
            for (String contentEncoding : contentEncodingList) {
                if (contentEncoding != null && (contentEncoding.toLowerCase().equals("gzip")
                        || contentEncoding.toLowerCase().equals("x-gzip"))) {
                    httpEntity = new GzipCompressingEntity(httpEntity);
                    break;
                }
            }
        }

        ((HttpEntityEnclosingRequestBase) httpMethod).setEntity(httpEntity);
    }

    // set the headers
    for (Entry<String, List<String>> headerEntry : headers.entrySet()) {
        for (String value : headerEntry.getValue()) {
            logger.debug("setting method header: [" + headerEntry.getKey() + ", " + value + "]");
            httpMethod.addHeader(headerEntry.getKey(), value);
        }
    }

    // Only set the Content-Type for entity-enclosing methods, but not if multipart is used
    if (("POST".equalsIgnoreCase(method) || "PUT".equalsIgnoreCase(method)) && !isMultipart) {
        httpMethod.setHeader(HTTP.CONTENT_TYPE, contentType.toString());
    }

    return httpMethod;
}