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

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

Introduction

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

Prototype

public MultipartEntityBuilder addBinaryBody(final String name, final InputStream stream,
            final ContentType contentType, final String filename) 

Source Link

Usage

From source file:hello.MyPostHTTP.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {

    final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
    requestConfigBuilder.setConnectionRequestTimeout(
            context.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    requestConfigBuilder.setConnectTimeout(
            context.getProperty(CONNECTION_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    requestConfigBuilder.setRedirectsEnabled(false);
    requestConfigBuilder//from   www  . ja  v  a2 s  .co  m
            .setSocketTimeout(context.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    final RequestConfig requestConfig = requestConfigBuilder.build();

    final StreamThrottler throttler = throttlerRef.get();
    final ProcessorLog logger = getLogger();

    String lastUrl = null;
    long bytesToSend = 0L;

    final List<FlowFile> toSend = new ArrayList<>();
    CloseableHttpClient client = null;
    final String transactionId = UUID.randomUUID().toString();

    final ObjectHolder<String> dnHolder = new ObjectHolder<>("none");
    while (true) {
        FlowFile flowFile = session.get();
        if (flowFile == null) {
            break;
        }

        final String url = context.getProperty(URL).evaluateAttributeExpressions(flowFile).getValue();
        try {
            new java.net.URL(url);
        } catch (final MalformedURLException e) {
            logger.error(
                    "After substituting attribute values for {}, URL is {}; this is not a valid URL, so routing to failure",
                    new Object[] { flowFile, url });
            flowFile = session.penalize(flowFile);
            session.transfer(flowFile, REL_FAILURE);
            continue;
        }

        // If this FlowFile doesn't have the same url, throw it back on the queue and stop grabbing FlowFiles
        if (lastUrl != null && !lastUrl.equals(url)) {
            session.transfer(flowFile);
            break;
        }

        lastUrl = url;
        toSend.add(flowFile);

        if (client == null) {
            final Config config = getConfig(url, context);
            final HttpClientConnectionManager conMan = config.getConnectionManager();

            final HttpClientBuilder clientBuilder = HttpClientBuilder.create();
            clientBuilder.setConnectionManager(conMan);
            clientBuilder.addInterceptorFirst(new HttpResponseInterceptor() {
                @Override
                public void process(final HttpResponse response, final HttpContext httpContext)
                        throws HttpException, IOException {
                    final HttpCoreContext coreContext = HttpCoreContext.adapt(httpContext);
                    final ManagedHttpClientConnection conn = coreContext
                            .getConnection(ManagedHttpClientConnection.class);
                    if (!conn.isOpen()) {
                        return;
                    }

                    final SSLSession sslSession = conn.getSSLSession();

                    if (sslSession != null) {
                        final X509Certificate[] certChain = sslSession.getPeerCertificateChain();
                        if (certChain == null || certChain.length == 0) {
                            throw new SSLPeerUnverifiedException("No certificates found");
                        }

                        final X509Certificate cert = certChain[0];
                        dnHolder.set(cert.getSubjectDN().getName().trim());
                    }
                }
            });

            clientBuilder.disableAutomaticRetries();
            clientBuilder.disableContentCompression();

            client = clientBuilder.build();
        }

        bytesToSend += flowFile.getSize();
        break;
    }

    if (toSend.isEmpty()) {
        return;
    }

    final String url = lastUrl;
    final HttpPost post = new HttpPost(url);
    final List<FlowFile> flowFileList = toSend;

    String userName = "Chris";
    String password = "password";
    final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addTextBody("userName", userName);
    builder.addTextBody("password", password);
    for (final FlowFile flowFile : flowFileList) {
        session.read(flowFile, new InputStreamCallback() {
            @Override
            public void process(final InputStream rawIn) throws IOException {
                InputStream in = new ByteArrayInputStream(IOUtils.toByteArray(rawIn));
                builder.addBinaryBody("file", in, ContentType.DEFAULT_BINARY, "filename");
            }
        });
    }

    final HttpEntity entity2 = builder.build();

    post.setEntity(entity2);
    post.setConfig(requestConfig);

    final String contentType;

    contentType = DEFAULT_CONTENT_TYPE;
    post.setHeader(CONTENT_TYPE_HEADER, contentType);
    post.setHeader(FLOWFILE_CONFIRMATION_HEADER, "true");
    post.setHeader(PROTOCOL_VERSION_HEADER, PROTOCOL_VERSION);
    post.setHeader(TRANSACTION_ID_HEADER, transactionId);

    // Do the actual POST
    final String flowFileDescription = toSend.size() <= 10 ? toSend.toString() : toSend.size() + " FlowFiles";

    final String uploadDataRate;
    final long uploadMillis;
    CloseableHttpResponse response = null;
    try {
        final StopWatch stopWatch = new StopWatch(true);
        response = client.execute(post);
        // consume input stream entirely, ignoring its contents. If we
        // don't do this, the Connection will not be returned to the pool
        EntityUtils.consume(response.getEntity());
        stopWatch.stop();
        uploadDataRate = stopWatch.calculateDataRate(bytesToSend);
        uploadMillis = stopWatch.getDuration(TimeUnit.MILLISECONDS);
    } catch (final IOException e) {
        logger.error("Failed to Post {} due to {}; transferring to failure",
                new Object[] { flowFileDescription, e });
        context.yield();
        for (FlowFile flowFile : toSend) {
            flowFile = session.penalize(flowFile);
            session.transfer(flowFile, REL_FAILURE);
        }
        return;
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (final IOException e) {
                getLogger().warn("Failed to close HTTP Response due to {}", new Object[] { e });
            }
        }
    }

    // If we get a 'SEE OTHER' status code and an HTTP header that indicates that the intent
    // of the Location URI is a flowfile hold, we will store this holdUri. This prevents us
    // from posting to some other webservice and then attempting to delete some resource to which
    // we are redirected
    final int responseCode = response.getStatusLine().getStatusCode();
    final String responseReason = response.getStatusLine().getReasonPhrase();
    String holdUri = null;
    if (responseCode == HttpServletResponse.SC_SEE_OTHER) {
        final Header locationUriHeader = response.getFirstHeader(LOCATION_URI_INTENT_NAME);
        if (locationUriHeader != null) {
            if (LOCATION_URI_INTENT_VALUE.equals(locationUriHeader.getValue())) {
                final Header holdUriHeader = response.getFirstHeader(LOCATION_HEADER_NAME);
                if (holdUriHeader != null) {
                    holdUri = holdUriHeader.getValue();
                }
            }
        }

        if (holdUri == null) {
            for (FlowFile flowFile : toSend) {
                flowFile = session.penalize(flowFile);
                logger.error(
                        "Failed to Post {} to {}: sent content and received status code {}:{} but no Hold URI",
                        new Object[] { flowFile, url, responseCode, responseReason });
                session.transfer(flowFile, REL_FAILURE);
            }
            return;
        }
    }

    if (holdUri == null) {
        if (responseCode == HttpServletResponse.SC_SERVICE_UNAVAILABLE) {
            for (FlowFile flowFile : toSend) {
                flowFile = session.penalize(flowFile);
                logger.error(
                        "Failed to Post {} to {}: response code was {}:{}; will yield processing, "
                                + "since the destination is temporarily unavailable",
                        new Object[] { flowFile, url, responseCode, responseReason });
                session.transfer(flowFile, REL_FAILURE);
            }
            context.yield();
            return;
        }

        if (responseCode >= 300) {
            for (FlowFile flowFile : toSend) {
                flowFile = session.penalize(flowFile);
                logger.error("Failed to Post {} to {}: response code was {}:{}",
                        new Object[] { flowFile, url, responseCode, responseReason });
                session.transfer(flowFile, REL_FAILURE);
            }
            return;
        }

        logger.info("Successfully Posted {} to {} in {} at a rate of {}", new Object[] { flowFileDescription,
                url, FormatUtils.formatMinutesSeconds(uploadMillis, TimeUnit.MILLISECONDS), uploadDataRate });

        for (final FlowFile flowFile : toSend) {
            session.getProvenanceReporter().send(flowFile, url, "Remote DN=" + dnHolder.get(), uploadMillis,
                    true);
            session.transfer(flowFile, REL_SUCCESS);
        }
        return;
    }

    //
    // the response indicated a Hold URI; delete the Hold.
    //
    // determine the full URI of the Flow File's Hold; Unfortunately, the responses that are returned have
    // changed over the past, so we have to take into account a few different possibilities.
    String fullHoldUri = holdUri;
    if (holdUri.startsWith("/contentListener")) {
        // If the Hold URI that we get starts with /contentListener, it may not really be /contentListener,
        // as this really indicates that it should be whatever we posted to -- if posting directly to the
        // ListenHTTP component, it will be /contentListener, but if posting to a proxy/load balancer, we may
        // be posting to some other URL.
        fullHoldUri = url + holdUri.substring(16);
    } else if (holdUri.startsWith("/")) {
        // URL indicates the full path but not hostname or port; use the same hostname & port that we posted
        // to but use the full path indicated by the response.
        int firstSlash = url.indexOf("/", 8);
        if (firstSlash < 0) {
            firstSlash = url.length();
        }
        final String beforeSlash = url.substring(0, firstSlash);
        fullHoldUri = beforeSlash + holdUri;
    } else if (!holdUri.startsWith("http")) {
        // Absolute URL
        fullHoldUri = url + (url.endsWith("/") ? "" : "/") + holdUri;
    }

    final HttpDelete delete = new HttpDelete(fullHoldUri);
    delete.setHeader(TRANSACTION_ID_HEADER, transactionId);

    while (true) {
        try {
            final HttpResponse holdResponse = client.execute(delete);
            EntityUtils.consume(holdResponse.getEntity());
            final int holdStatusCode = holdResponse.getStatusLine().getStatusCode();
            final String holdReason = holdResponse.getStatusLine().getReasonPhrase();
            if (holdStatusCode >= 300) {
                logger.error(
                        "Failed to delete Hold that destination placed on {}: got response code {}:{}; routing to failure",
                        new Object[] { flowFileDescription, holdStatusCode, holdReason });

                for (FlowFile flowFile : toSend) {
                    flowFile = session.penalize(flowFile);
                    session.transfer(flowFile, REL_FAILURE);
                }
                return;
            }

            logger.info("Successfully Posted {} to {} in {} milliseconds at a rate of {}",
                    new Object[] { flowFileDescription, url, uploadMillis, uploadDataRate });

            for (final FlowFile flowFile : toSend) {
                session.getProvenanceReporter().send(flowFile, url);
                session.transfer(flowFile, REL_SUCCESS);
            }
            return;
        } catch (final IOException e) {
            logger.warn("Failed to delete Hold that destination placed on {} due to {}",
                    new Object[] { flowFileDescription, e });
        }

        if (!isScheduled()) {
            context.yield();
            logger.warn(
                    "Failed to delete Hold that destination placed on {}; Processor has been stopped so routing FlowFile(s) to failure",
                    new Object[] { flowFileDescription });
            for (FlowFile flowFile : toSend) {
                flowFile = session.penalize(flowFile);
                session.transfer(flowFile, REL_FAILURE);
            }
            return;
        }
    }
}

From source file:com.buffalokiwi.api.API.java

/**
 * This will take a list of files, and attach them to the 
 * MultipartEntityBuilder instance//from  w ww .j ava  2  s .  com
 * @param files Files to add
 * @param builder builder 
 */
private void setMultipartFileData(final Map<String, PostFile> files, final MultipartEntityBuilder builder) {
    //..Check for input files
    if (files == null || builder == null)
        return;

    for (final String name : files.keySet()) {
        //..Ensure the file exists
        final PostFile pf = files.get(name);

        if (!pf.getFile().exists()) {
            throw new IllegalArgumentException(pf.getFile() + " (" + pf.getFilename()
                    + ") does not exist; cannot upload non-existent file.");
        }

        APILog.trace(LOG, "Added file", pf.getFile(), "(", pf.getFilename(), ")");

        builder.addBinaryBody(name, pf.getFile(), pf.getContentType(), pf.getFilename());
    }
}

From source file:org.andstatus.app.net.http.HttpConnectionApacheCommon.java

private void fillMultiPartPost(HttpPost postMethod, JSONObject formParams) throws ConnectionException {
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    Uri mediaUri = null;/*from w w  w.  j a  va 2  s.c om*/
    String mediaPartName = "";
    Iterator<String> iterator = formParams.keys();
    ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
    while (iterator.hasNext()) {
        String name = iterator.next();
        String value = formParams.optString(name);
        if (HttpConnection.KEY_MEDIA_PART_NAME.equals(name)) {
            mediaPartName = value;
        } else if (HttpConnection.KEY_MEDIA_PART_URI.equals(name)) {
            mediaUri = UriUtils.fromString(value);
        } else {
            // see http://stackoverflow.com/questions/19292169/multipartentitybuilder-and-charset
            builder.addTextBody(name, value, contentType);
        }
    }
    if (!TextUtils.isEmpty(mediaPartName) && !UriUtils.isEmpty(mediaUri)) {
        try {
            InputStream ins = MyContextHolder.get().context().getContentResolver().openInputStream(mediaUri);
            ContentType contentType2 = ContentType.create(MyContentType.uri2MimeType(mediaUri, null));
            builder.addBinaryBody(mediaPartName, ins, contentType2, mediaUri.getPath());
        } catch (SecurityException e) {
            throw new ConnectionException("mediaUri='" + mediaUri + "'", e);
        } catch (FileNotFoundException e) {
            throw new ConnectionException("mediaUri='" + mediaUri + "'", e);
        }
    }
    postMethod.setEntity(builder.build());
}

From source file:org.wso2.ml.client.MLClient.java

public CloseableHttpResponse createdDataSet(JSONObject datasetConf) throws IOException {
    CloseableHttpClient httpClient = HttpClients.createDefault();

    HttpPost httpPost = new HttpPost(mlHost + "/api/datasets/");
    httpPost.setHeader(MLConstants.AUTHORIZATION_HEADER, getBasicAuthKey());

    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
    multipartEntityBuilder.addPart("description",
            new StringBody(datasetConf.get("description").toString(), ContentType.TEXT_PLAIN));
    multipartEntityBuilder.addPart("sourceType",
            new StringBody(datasetConf.get("sourceType").toString(), ContentType.TEXT_PLAIN));
    multipartEntityBuilder.addPart("destination",
            new StringBody(datasetConf.get("destination").toString(), ContentType.TEXT_PLAIN));
    multipartEntityBuilder.addPart("dataFormat",
            new StringBody(datasetConf.get("dataFormat").toString(), ContentType.TEXT_PLAIN));
    multipartEntityBuilder.addPart("containsHeader",
            new StringBody(datasetConf.get("containsHeader").toString(), ContentType.TEXT_PLAIN));
    multipartEntityBuilder.addPart("datasetName",
            new StringBody(datasetConf.get("datasetName").toString(), ContentType.TEXT_PLAIN));
    multipartEntityBuilder.addPart("version",
            new StringBody(datasetConf.get("version").toString(), ContentType.TEXT_PLAIN));

    File file = new File(mlDatasetPath);
    multipartEntityBuilder.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM,
            datasetConf.get("file").toString());

    httpPost.setEntity(multipartEntityBuilder.build());
    return httpClient.execute(httpPost);

}

From source file:org.openscore.content.httpclient.build.EntityBuilder.java

public HttpEntity buildEntity() {
    AbstractHttpEntity httpEntity = null;
    if (!StringUtils.isEmpty(formParams)) {
        List<? extends NameValuePair> list;
        list = getNameValuePairs(formParams, !Boolean.parseBoolean(this.formParamsAreURLEncoded),
                HttpClientInputs.FORM_PARAMS, HttpClientInputs.FORM_PARAMS_ARE_URLENCODED);
        httpEntity = new UrlEncodedFormEntity(list, contentType.getCharset());
    } else if (!StringUtils.isEmpty(body)) {
        httpEntity = new StringEntity(body, contentType);
    } else if (!StringUtils.isEmpty(filePath)) {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new IllegalArgumentException(
                    "file set by input '" + HttpClientInputs.SOURCE_FILE + "' does not exist:" + filePath);
        }/*from  ww w  .  j a va  2 s .  c  o m*/
        httpEntity = new FileEntity(file, contentType);
    }
    if (httpEntity != null) {
        if (!StringUtils.isEmpty(chunkedRequestEntity)) {
            httpEntity.setChunked(Boolean.parseBoolean(chunkedRequestEntity));
        }
        return httpEntity;
    }

    if (!StringUtils.isEmpty(multipartBodies) || !StringUtils.isEmpty(multipartFiles)) {
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        if (!StringUtils.isEmpty(multipartBodies)) {
            List<? extends NameValuePair> list;
            list = getNameValuePairs(multipartBodies, !Boolean.parseBoolean(this.multipartValuesAreURLEncoded),
                    HttpClientInputs.MULTIPART_BODIES, HttpClientInputs.MULTIPART_VALUES_ARE_URLENCODED);
            ContentType bodiesCT = ContentType.parse(multipartBodiesContentType);
            for (NameValuePair nameValuePair : list) {
                multipartEntityBuilder.addTextBody(nameValuePair.getName(), nameValuePair.getValue(), bodiesCT);
            }
        }

        if (!StringUtils.isEmpty(multipartFiles)) {
            List<? extends NameValuePair> list;
            list = getNameValuePairs(multipartFiles, !Boolean.parseBoolean(this.multipartValuesAreURLEncoded),
                    HttpClientInputs.MULTIPART_FILES, HttpClientInputs.MULTIPART_VALUES_ARE_URLENCODED);
            ContentType filesCT = ContentType.parse(multipartFilesContentType);
            for (NameValuePair nameValuePair : list) {
                File file = new File(nameValuePair.getValue());
                multipartEntityBuilder.addBinaryBody(nameValuePair.getName(), file, filesCT, file.getName());
            }
        }
        return multipartEntityBuilder.build();
    }

    return null;
}

From source file:io.cloudslang.content.httpclient.build.EntityBuilder.java

public HttpEntity buildEntity() {
    AbstractHttpEntity httpEntity = null;
    if (!StringUtils.isEmpty(formParams)) {
        List<? extends NameValuePair> list;
        list = getNameValuePairs(formParams, !Boolean.parseBoolean(this.formParamsAreURLEncoded),
                HttpClientInputs.FORM_PARAMS, HttpClientInputs.FORM_PARAMS_ARE_URLENCODED);
        Charset charset = contentType != null ? contentType.getCharset() : null;
        httpEntity = new UrlEncodedFormEntity(list, charset);
    } else if (!StringUtils.isEmpty(body)) {
        httpEntity = new StringEntity(body, contentType);
    } else if (!StringUtils.isEmpty(filePath)) {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new IllegalArgumentException(
                    "file set by input '" + HttpClientInputs.SOURCE_FILE + "' does not exist:" + filePath);
        }/* ww  w.ja va  2  s .co m*/
        httpEntity = new FileEntity(file, contentType);
    }
    if (httpEntity != null) {
        if (!StringUtils.isEmpty(chunkedRequestEntity)) {
            httpEntity.setChunked(Boolean.parseBoolean(chunkedRequestEntity));
        }
        return httpEntity;
    }

    if (!StringUtils.isEmpty(multipartBodies) || !StringUtils.isEmpty(multipartFiles)) {
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        if (!StringUtils.isEmpty(multipartBodies)) {
            List<? extends NameValuePair> list;
            list = getNameValuePairs(multipartBodies, !Boolean.parseBoolean(this.multipartValuesAreURLEncoded),
                    HttpClientInputs.MULTIPART_BODIES, HttpClientInputs.MULTIPART_VALUES_ARE_URLENCODED);
            ContentType bodiesCT = ContentType.parse(multipartBodiesContentType);
            for (NameValuePair nameValuePair : list) {
                multipartEntityBuilder.addTextBody(nameValuePair.getName(), nameValuePair.getValue(), bodiesCT);
            }
        }

        if (!StringUtils.isEmpty(multipartFiles)) {
            List<? extends NameValuePair> list;
            list = getNameValuePairs(multipartFiles, !Boolean.parseBoolean(this.multipartValuesAreURLEncoded),
                    HttpClientInputs.MULTIPART_FILES, HttpClientInputs.MULTIPART_VALUES_ARE_URLENCODED);
            ContentType filesCT = ContentType.parse(multipartFilesContentType);
            for (NameValuePair nameValuePair : list) {
                File file = new File(nameValuePair.getValue());
                multipartEntityBuilder.addBinaryBody(nameValuePair.getName(), file, filesCT, file.getName());
            }
        }
        return multipartEntityBuilder.build();
    }

    return null;
}

From source file:org.openestate.is24.restapi.hc43.HttpComponents43Client.java

@Override
protected Response sendXmlAttachmentRequest(URL url, RequestMethod method, String xml, InputStream input,
        String fileName, String mimeType) throws IOException, OAuthException {
    if (method == null)
        method = RequestMethod.POST;/*from   w w  w .  ja v  a  2 s . c  om*/
    if (!RequestMethod.POST.equals(method) && !RequestMethod.PUT.equals(method))
        throw new IllegalArgumentException("Invalid request method!");
    xml = (RequestMethod.POST.equals(method) || RequestMethod.PUT.equals(method)) ? StringUtils.trimToNull(xml)
            : null;

    HttpUriRequest request = null;
    if (RequestMethod.POST.equals(method)) {
        request = new HttpPost(url.toString());
    } else if (RequestMethod.PUT.equals(method)) {
        request = new HttpPut(url.toString());
    } else {
        throw new IOException("Unsupported request method '" + method + "'!");
    }

    MultipartEntityBuilder b = MultipartEntityBuilder.create();

    // add xml part to the multipart entity
    if (xml != null) {
        //InputStreamBody xmlPart = new InputStreamBody(
        //  new ByteArrayInputStream( xml.getBytes( getEncoding() ) ),
        //  ContentType.parse( "application/xml" ),
        //  "body.xml" );
        //b.addPart( "metadata", xmlPart );
        b.addTextBody("metadata", xml, ContentType.create("application/xml", getEncoding()));
    }

    // add file part to the multipart entity
    if (input != null) {
        mimeType = StringUtils.trimToNull(mimeType);
        if (mimeType == null)
            mimeType = "application/octet-stream";

        fileName = StringUtils.trimToNull(fileName);
        if (fileName == null)
            fileName = "upload.bin";

        //InputStreamBody filePart = new InputStreamBody(
        //  input, ContentType.create( mimeType ), fileName );
        //b.addPart( "attachment", filePart );
        b.addBinaryBody("attachment", input, ContentType.create(mimeType), fileName);
    }

    // add multipart entity to the request
    HttpEntity requestMultipartEntity = b.build();
    request.addHeader(requestMultipartEntity.getContentType());
    request.setHeader("Content-Language", "en-US");
    request.setHeader("Accept", "application/xml");
    ((HttpEntityEnclosingRequest) request).setEntity(requestMultipartEntity);

    // sign request
    getAuthConsumer().sign(request);

    // send request
    HttpResponse response = httpClient.execute(request);

    // create response
    return createResponse(response);
}

From source file:nl.uva.mediamosa.impl.MediaMosaImpl.java

/**
 * @param postRequest/*from w  ww .j  a va2s .c o  m*/
 * @param postParams
 * @return
 * @throws java.io.IOException
 */
public Response doPostRequest(String uploadHost, String postRequest, String postParams, InputStream stream,
        String mimeType, String filename) throws IOException {
    HttpPost httpPost = new HttpPost(uploadHost + postRequest);

    MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
    mpBuilder.addBinaryBody("file", stream, ContentType.create(mimeType), filename);

    List<NameValuePair> nvps = URLEncodedUtils.parse(postParams, Charset.forName("UTF-8"));
    for (NameValuePair nameValuePair : nvps) {
        mpBuilder.addTextBody(nameValuePair.getName(), nameValuePair.getValue());
    }
    httpPost.setEntity(mpBuilder.build());

    return UnmarshallUtil.unmarshall(getXmlTransformedResponse(httpPost));
}

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

/**
 * Upload a sample datatset from resources
 * /*ww  w.  j av  a2 s .  c o  m*/
 * @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:com.lgallardo.youtorrentcontroller.JSONParser.java

public void postCommand(String command, String hash) throws JSONParserStatusCodeException {

    String key = "hash";

    String urlContentType = "application/x-www-form-urlencoded";

    String boundary = null;//from w w  w.j a  v a  2s  .c  o  m

    StringBuilder fileContent = null;

    HttpResponse httpResponse;
    DefaultHttpClient httpclient;

    String url = "";

    //        Log.d("Debug", "JSONParser - command: " + command);

    if ("start".equals(command) || "startSelected".equals(command)) {
        url = url + "gui/?action=start&hash=" + hash;
    }

    if ("pause".equals(command) || "pauseSelected".equals(command)) {
        url = url + "gui/?action=pause&hash=" + hash;
    }

    if ("stop".equals(command) || "stopSelected".equals(command)) {
        url = url + "gui/?action=stop&hash=" + hash;
        Log.d("Debug", "Stoping torrent " + hash);
    }

    if ("delete".equals(command) || "deleteSelected".equals(command)) {
        url = url + "gui/?action=remove&hash=" + hash.replace("|", "&hash=");
        key = "hashes";
    }

    if ("deleteDrive".equals(command) || "deleteDriveSelected".equals(command)) {
        url = url + "gui/?action=removedata&hash=" + hash.replace("|", "&hash=");
        key = "hashes";
    }

    if ("addTorrent".equals(command)) {

        URI hash_uri = null;

        try {
            hash_uri = new URI(hash);
            hash = hash_uri.toString();

            //                Log.d("Debug","Torrent URL: "+ hash);

        } catch (URISyntaxException e) {
            Log.e("Debug", "URISyntaxException: " + e.toString());
        }

        url = url + "gui/?action=add-url&s=" + hash;
        //            key = "urls";
    }

    if ("addTorrentFile".equals(command)) {
        url = url + "gui/?action=add-file";
        key = "urls";

        boundary = "-----------------------" + (new Date()).getTime();

        urlContentType = "multipart/form-data; boundary=" + boundary;
        //            urlContentType = "multipart/form-data";

    }

    //        if ("pauseall".equals(command)) {
    //            url = "command/pauseall";
    //        }
    //
    //        if ("pauseAll".equals(command)) {
    //            url = "command/pauseAll";
    //        }
    //
    //
    //        if ("resumeall".equals(command)) {
    //            url = "command/resumeall";
    //        }
    //
    //        if ("resumeAll".equals(command)) {
    //            url = "command/resumeAll";
    //        }

    if ("increasePrio".equals(command)) {
        url = url + "gui/?action=queueup&hash=" + hash.replace("|", "&hash=");
        key = "hashes";
    }

    if ("decreasePrio".equals(command)) {
        url = url + "gui/?action=queuedown&hash=" + hash.replace("|", "&hash=");
        key = "hashes";

    }

    if ("maxPrio".equals(command)) {
        url = url + "gui/?action=queuetop&hash=" + hash.replace("|", "&hash=");
        key = "hashes";
    }

    if ("minPrio".equals(command)) {
        url = url + "gui/?action=queuebottom&hash=" + hash.replace("|", "&hash=");
        key = "hashes";

    }

    if ("setQBittorrentPrefefrences".equals(command)) {
        url = "command/setPreferences";
        key = "json";
    }

    if ("recheckSelected".equals(command)) {
        url = url + "gui/?action=recheck&hash=" + hash.replace("|", "&hash=");
    }

    //        if ("toggleFirstLastPiecePrio".equals(command)) {
    //            url = "command/toggleFirstLastPiecePrio";
    //            key = "hashes";
    //
    //        }
    //
    //        if ("toggleSequentialDownload".equals(command)) {
    //            url = "command/toggleSequentialDownload";
    //            key = "hashes";
    //
    //        }

    // if server is publish in a subfolder, fix url
    if (subfolder != null && !subfolder.equals("")) {
        url = subfolder + "/" + url;
    }

    HttpParams httpParameters = new BasicHttpParams();

    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used.
    int timeoutConnection = connection_timeout * 1000;

    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = data_timeout * 1000;

    // Set http parameters
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    HttpProtocolParams.setUserAgent(httpParameters, "youTorrent Controller");
    HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8);

    // Making HTTP request
    HttpHost targetHost = new HttpHost(this.hostname, this.port, this.protocol);

    // httpclient = new DefaultHttpClient();
    httpclient = getNewHttpClient();

    // Set http parameters
    httpclient.setParams(httpParameters);

    try {

        AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());

        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password);

        httpclient.getCredentialsProvider().setCredentials(authScope, credentials);

        url = protocol + "://" + hostname + ":" + port + "/" + url + "&token=" + token;

        //            Log.d("Debug", "JSONParser - url: " + url);

        HttpPost httpget = new HttpPost(url);

        if ("addTorrent".equals(command)) {
            URI hash_uri = new URI(hash);
            hash = hash_uri.toString();
        }

        // In order to pass the has we must set the pair name value
        BasicNameValuePair bnvp = new BasicNameValuePair(key, hash);

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(bnvp);

        httpget.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

        // Set content type and urls
        if ("increasePrio".equals(command) || "decreasePrio".equals(command) || "maxPrio".equals(command)) {
            httpget.setHeader("Content-Type", urlContentType);

        }

        // Set cookie
        if (this.cookie != null) {
            httpget.setHeader("Cookie", this.cookie);
        }

        // Set content type and urls
        if ("addTorrentFile".equals(command)) {

            //                Log.d("Debug", "JSONParser - urlContentType: " +  urlContentType);
            //                Log.d("Debug", "JSONParser - hash: " +  Uri.decode(URLEncoder.encode(hash, "UTF-8")));
            //                Log.d("Debug", "JSONParser - hash: " +  hash);

            httpget.setHeader("Content-Type", urlContentType);

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

            // Add boundary
            builder.setBoundary(boundary);

            // Add torrent file as binary
            File file = new File(hash);
            // FileBody fileBody = new FileBody(file);
            // builder.addPart("file", fileBody);

            builder.addBinaryBody("torrent_file", file, ContentType.DEFAULT_BINARY, null);
            //                builder.addBinaryBody("upfile", file, ContentType.create(urlContentType), hash);

            // Build entity
            HttpEntity entity = builder.build();

            // Set entity to http post
            httpget.setEntity(entity);

        }

        httpResponse = httpclient.execute(targetHost, httpget);

        StatusLine statusLine = httpResponse.getStatusLine();

        int mStatusCode = statusLine.getStatusCode();

        if (mStatusCode != 200) {
            httpclient.getConnectionManager().shutdown();
            throw new JSONParserStatusCodeException(mStatusCode);
        }

        HttpEntity httpEntity = httpResponse.getEntity();

        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {

    } catch (ClientProtocolException e) {
        Log.e("Debug", "Client: " + e.toString());
        e.printStackTrace();
    } catch (IOException e) {
        Log.e("Debug", "IO: " + e.toString());
        // e.printStackTrace();
        httpclient.getConnectionManager().shutdown();
        throw new JSONParserStatusCodeException(TIMEOUT_ERROR);
    } catch (JSONParserStatusCodeException e) {
        httpclient.getConnectionManager().shutdown();
        throw new JSONParserStatusCodeException(e.getCode());
    } catch (Exception e) {
        Log.e("Debug", "Generic: " + e.toString());
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }

}