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:org.openbaton.marketplace.core.VNFPackageManagement.java

public void dispatch3(VNFPackageMetadata packageMetadata) throws IOException, ArchiveException, SDKException {
    log.debug("Trying to upload package to FITEagle");

    String url = "http://" + fitEagleIp + ":" + fitEaglePort + "/OpenBaton/upload/v2";

    log.debug("FITEagle URL is: " + url);

    //    HttpClient client = HttpClientBuilder.create().build();
    HttpClient client = HttpClients.createDefault();
    HttpPost request = new HttpPost(url);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();

    byte[] vnfPackageFile = packageMetadata.getVnfPackageFile();
    log.debug("Trying to add binary file of length: " + vnfPackageFile.length);
    builder.addBinaryBody("file", vnfPackageFile, ContentType.APPLICATION_OCTET_STREAM,
            packageMetadata.getName());/*from w ww .ja v  a2 s .  co m*/

    String currentUser = userManagement.getCurrentUser();
    request.addHeader("username", currentUser);
    log.debug("Added username header: " + currentUser);

    request.setEntity(builder.build());
    log.debug("Added binary file of length: " + vnfPackageFile.length);
    HttpResponse response = client.execute(request);
    log.debug("Executed POST!");
    log.debug("Response Code from FITEAGLE: " + response.getStatusLine().getStatusCode());
}

From source file:com.tremolosecurity.proxy.postProcess.PushRequestProcess.java

@Override
public void postProcess(HttpFilterRequest req, HttpFilterResponse resp, UrlHolder holder, HttpFilterChain chain)
        throws Exception {
    boolean isText;

    HashMap<String, String> uriParams = (HashMap<String, String>) req.getAttribute("TREMOLO_URI_PARAMS");

    StringBuffer proxyToURL = new StringBuffer();

    proxyToURL.append(holder.getProxyURL(uriParams));

    boolean first = true;
    for (NVP p : req.getQueryStringParams()) {
        if (first) {
            proxyToURL.append('?');
            first = false;// w w w. j  av a2  s  .  co m
        } else {
            proxyToURL.append('&');
        }

        proxyToURL.append(p.getName()).append('=').append(URLEncoder.encode(p.getValue(), "UTF-8"));
    }

    HttpEntity entity = null;

    if (req.isMultiPart()) {

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

        for (String name : req.getFormParams()) {

            /*if (queryParams.contains(name)) {
               continue;
            }*/

            for (String val : req.getFormParamVals(name)) {
                //ent.addPart(name, new StringBody(val));
                mpeb.addTextBody(name, val);
            }

        }

        HashMap<String, ArrayList<FileItem>> files = req.getFiles();
        for (String name : files.keySet()) {
            for (FileItem fi : files.get(name)) {
                //ent.addPart(name, new InputStreamBody(fi.getInputStream(),fi.getContentType(),fi.getName()));

                mpeb.addBinaryBody(name, fi.get(), ContentType.create(fi.getContentType()), fi.getName());

            }
        }

        entity = mpeb.build();

    } else if (req.isParamsInBody()) {
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();

        for (String paramName : req.getFormParams()) {

            for (String val : req.getFormParamVals(paramName)) {

                formparams.add(new BasicNameValuePair(paramName, val));
            }
        }

        entity = new UrlEncodedFormEntity(formparams, "UTF-8");
    } else {

        byte[] msgData = (byte[]) req.getAttribute(ProxySys.MSG_BODY);
        ByteArrayEntity bentity = new ByteArrayEntity(msgData);
        bentity.setContentType(req.getContentType());

        entity = bentity;
    }

    MultipartRequestEntity frm;

    CloseableHttpClient httpclient = this.getHttp(proxyToURL.toString(), req.getServletRequest(),
            holder.getConfig());

    //HttpPost httppost = new HttpPost(proxyToURL.toString());
    HttpEntityEnclosingRequestBase httpMethod = new EntityMethod(req.getMethod(), proxyToURL.toString());//this.getHttpMethod(proxyToURL.toString());

    setHeadersCookies(req, holder, httpMethod, proxyToURL.toString());

    httpMethod.setEntity(entity);

    HttpContext ctx = (HttpContext) req.getSession().getAttribute(ProxySys.HTTP_CTX);
    HttpResponse response = httpclient.execute(httpMethod, ctx);

    postProcess(req, resp, holder, response, proxyToURL.toString(), chain, httpMethod);

}

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

/**
 * @throws MLHttpClientException/*  w  w  w  .jav a 2  s .c  o  m*/
 */
public CloseableHttpResponse predictFromCSV(long modelId, String resourcePath) throws MLHttpClientException {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {
        HttpPost httpPost = new HttpPost(getServerUrlHttps() + "/api/models/predict");
        httpPost.setHeader(MLIntegrationTestConstants.AUTHORIZATION_HEADER, getBasicAuthKey());

        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        multipartEntityBuilder.addPart("modelId", new StringBody(modelId + "", ContentType.TEXT_PLAIN));
        multipartEntityBuilder.addPart("dataFormat", new StringBody("CSV", ContentType.TEXT_PLAIN));

        if (resourcePath != null) {
            File file = new File(getResourceAbsolutePath(resourcePath));
            multipartEntityBuilder.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM,
                    "IndiansDiabetesPredict.csv");
        }
        httpPost.setEntity(multipartEntityBuilder.build());
        return httpClient.execute(httpPost);
    } catch (Exception e) {
        throw new MLHttpClientException("Failed to predict from csv " + resourcePath, e);
    }
}

From source file:org.biopax.validator.BiopaxValidatorClient.java

/**
 * Checks a BioPAX OWL file(s) or resource 
 * using the online BioPAX Validator //from  www  . ja  va  2  s  . c o  m
 * and prints the results to the output stream.
 * 
 * @param autofix true/false (experimental)
 * @param profile validation profile name
 * @param retFormat xml, html, or owl (no errors, just modified owl, if autofix=true)
 * @param biopaxUrl check the BioPAX at the URL
 * @param biopaxFiles an array of BioPAX files to validate
 * @param out
 * @throws IOException
 */
public void validate(boolean autofix, String profile, RetFormat retFormat, Behavior filterBy, Integer maxErrs,
        String biopaxUrl, File[] biopaxFiles, OutputStream out) throws IOException {
    MultipartEntityBuilder meb = MultipartEntityBuilder.create();
    meb.setCharset(Charset.forName("UTF-8"));

    if (autofix)
        meb.addTextBody("autofix", "true");

    //TODO add extra options (normalizer.fixDisplayName, normalizer.xmlBase)?

    if (profile != null && !profile.isEmpty())
        meb.addTextBody("profile", profile);
    if (retFormat != null)
        meb.addTextBody("retDesired", retFormat.toString().toLowerCase());
    if (filterBy != null)
        meb.addTextBody("filter", filterBy.toString());
    if (maxErrs != null && maxErrs > 0)
        meb.addTextBody("maxErrors", maxErrs.toString());
    if (biopaxFiles != null && biopaxFiles.length > 0)
        for (File f : biopaxFiles) //important: use MULTIPART_FORM_DATA content-type
            meb.addBinaryBody("file", f, ContentType.MULTIPART_FORM_DATA, f.getName());
    else if (biopaxUrl != null) {
        meb.addTextBody("url", biopaxUrl);
    } else {
        log.error("Nothing to do (no BioPAX data specified)!");
        return;
    }

    HttpEntity httpEntity = meb.build();
    //       if(log.isDebugEnabled()) httpEntity.writeTo(System.err);
    String content = Executor.newInstance().execute(Request.Post(url).body(httpEntity)).returnContent()
            .asString();

    //save: append to the output stream (file)
    BufferedReader res = new BufferedReader(new StringReader(content));
    String line;
    PrintWriter writer = new PrintWriter(out);
    while ((line = res.readLine()) != null) {
        writer.println(line);
    }
    writer.flush();
    res.close();
}

From source file:sx.blah.discord.handle.impl.obj.Channel.java

@Override
public IMessage sendFiles(String content, boolean tts, EmbedObject embed, AttachmentPartEntry... entries) {
    PermissionUtils.requirePermissions(this, client.getOurUser(), Permissions.SEND_MESSAGES,
            Permissions.ATTACH_FILES);

    try {/*from   w w  w .ja  v a  2  s .co  m*/
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        if (entries.length == 1) {
            builder.addBinaryBody("file", entries[0].getFileData(), ContentType.APPLICATION_OCTET_STREAM,
                    entries[0].getFileName());
        } else {
            for (int i = 0; i < entries.length; i++) {
                builder.addBinaryBody("file" + i, entries[i].getFileData(),
                        ContentType.APPLICATION_OCTET_STREAM, entries[i].getFileName());
            }
        }

        builder.addTextBody("payload_json",
                DiscordUtils.MAPPER_NO_NULLS.writeValueAsString(new FilePayloadObject(content, tts, embed)),
                ContentType.MULTIPART_FORM_DATA.withCharset("UTF-8"));

        HttpEntity fileEntity = builder.build();
        MessageObject messageObject = DiscordUtils.MAPPER
                .readValue(
                        client.REQUESTS.POST.makeRequest(DiscordEndpoints.CHANNELS + id + "/messages",
                                fileEntity, new BasicNameValuePair("Content-Type", "multipart/form-data")),
                        MessageObject.class);

        return DiscordUtils.getMessageFromJSON(this, messageObject);
    } catch (IOException e) {
        throw new DiscordException("JSON Parsing exception!", e);
    }
}

From source file:org.biopax.paxtools.client.BiopaxValidatorClient.java

/**
 * Checks a BioPAX OWL file(s) or resource 
 * using the online BioPAX Validator //  w ww  . jav  a  2  s .  c  o  m
 * and prints the results to the output stream.
 * 
 * @param autofix true/false (experimental)
 * @param profile validation profile name
 * @param retFormat xml, html, or owl (no errors, just modified owl, if autofix=true)
* @param filterBy filter validation issues by the error/warning level
* @param maxErrs errors threshold - max no. critical errors to collect before quitting
*                (warnings not counted; null/0/negative value means unlimited)
 * @param biopaxUrl check the BioPAX at the URL
 * @param biopaxFiles an array of BioPAX files to validate
 * @param out validation report data output stream
 * @throws IOException when there is an I/O error
 */
public void validate(boolean autofix, String profile, RetFormat retFormat, Behavior filterBy, Integer maxErrs,
        String biopaxUrl, File[] biopaxFiles, OutputStream out) throws IOException {
    MultipartEntityBuilder meb = MultipartEntityBuilder.create();
    meb.setCharset(Charset.forName("UTF-8"));

    if (autofix)
        meb.addTextBody("autofix", "true");
    //TODO add extra options (normalizer.fixDisplayName, normalizer.inferPropertyOrganism, normalizer.inferPropertyDataSource, normalizer.xmlBase)?
    if (profile != null && !profile.isEmpty())
        meb.addTextBody("profile", profile);
    if (retFormat != null)
        meb.addTextBody("retDesired", retFormat.toString().toLowerCase());
    if (filterBy != null)
        meb.addTextBody("filter", filterBy.toString());
    if (maxErrs != null && maxErrs > 0)
        meb.addTextBody("maxErrors", maxErrs.toString());
    if (biopaxFiles != null && biopaxFiles.length > 0)
        for (File f : biopaxFiles) //important: use MULTIPART_FORM_DATA content-type
            meb.addBinaryBody("file", f, ContentType.MULTIPART_FORM_DATA, f.getName());
    else if (biopaxUrl != null) {
        meb.addTextBody("url", biopaxUrl);
    } else {
        log.error("Nothing to do (no BioPAX data specified)!");
        return;
    }

    //execute the query and get results as string
    HttpEntity httpEntity = meb.build();
    //       httpEntity.writeTo(System.err);
    String content = Executor.newInstance()//Executor.newInstance(httpClient)
            .execute(Request.Post(url).body(httpEntity)).returnContent().asString();

    //save: append to the output stream (file)
    BufferedReader res = new BufferedReader(new StringReader(content));
    String line;
    PrintWriter writer = new PrintWriter(out);
    while ((line = res.readLine()) != null) {
        writer.println(line);
    }
    writer.flush();
    res.close();
}

From source file:com.smartsheet.api.internal.AbstractResources.java

/**
 * Create a multipart upload request./*  w  w  w .j a  v a  2  s.co  m*/
 *
 * @param url the url
 * @param t the object to create
 * @param partName the name of the part
 * @param inputstream the file inputstream
 * @param contentType the type of the file to be attached
 * @return the http request
 * @throws UnsupportedEncodingException the unsupported encoding exception
 */
public <T> Attachment attachFile(String url, T t, String partName, InputStream inputstream, String contentType,
        String attachmentName) throws SmartsheetException {
    Util.throwIfNull(inputstream, contentType);
    Attachment attachment = null;
    final String boundary = "----" + System.currentTimeMillis();

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost uploadFile = createHttpPost(this.getSmartsheet().getBaseURI().resolve(url));

    try {
        uploadFile.setHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setBoundary(boundary);
    builder.addTextBody(partName, this.getSmartsheet().getJsonSerializer().serialize(t),
            ContentType.APPLICATION_JSON);
    builder.addBinaryBody("file", inputstream, ContentType.create(contentType), attachmentName);
    org.apache.http.HttpEntity multipart = builder.build();

    uploadFile.setEntity(multipart);

    try {
        CloseableHttpResponse response = httpClient.execute(uploadFile);
        org.apache.http.HttpEntity responseEntity = response.getEntity();
        attachment = this.getSmartsheet().getJsonSerializer()
                .deserializeResult(Attachment.class, responseEntity.getContent()).getResult();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return attachment;
}

From source file:com.smartsheet.api.internal.AbstractResources.java

/**
 * Create a resource using Smartsheet REST API.
 *
 * Exceptions://from   ww  w.ja va2 s  . c o  m
 *   IllegalArgumentException : if any argument is null, or path is empty string
 *   InvalidRequestException : if there is any problem with the REST API request
 *   AuthorizationException : if there is any problem with the REST API authorization(access token)
 *   ServiceUnavailableException : if the REST API service is not available (possibly due to rate limiting)
 *   SmartsheetRestException : if there is any other REST API related error occurred during the operation
 *   SmartsheetException : if there is any other error occurred during the operation
 *
 * @param <T> the generic type
 * @param path the relative path of the resource collections
 * @param objectClass the resource object class
 * @param object the object to create
 * @return the created resource
 * @throws SmartsheetException the smartsheet exception
 */
protected <T> T createResourceWithAttachment(String path, Class<T> objectClass, T object, String partName,
        InputStream inputStream, String contentType, String attachmentName) throws SmartsheetException {
    Util.throwIfNull(path, object);
    Util.throwIfEmpty(path);

    HttpRequest request;
    final String boundary = "----" + System.currentTimeMillis();
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost uploadFile = createHttpPost(this.getSmartsheet().getBaseURI().resolve(path));

    try {
        uploadFile.setHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setBoundary(boundary);
    builder.addTextBody(partName, this.getSmartsheet().getJsonSerializer().serialize(object),
            ContentType.APPLICATION_JSON);
    builder.addBinaryBody("file", inputStream, ContentType.create(contentType), attachmentName);
    org.apache.http.HttpEntity multipart = builder.build();

    uploadFile.setEntity(multipart);

    T obj = null;
    //implement switch case
    try {
        CloseableHttpResponse response = httpClient.execute(uploadFile);
        org.apache.http.HttpEntity responseEntity = response.getEntity();
        obj = this.getSmartsheet().getJsonSerializer()
                .deserializeResult(objectClass, responseEntity.getContent()).getResult();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return obj;
}

From source file:nzilbb.bas.BAS.java

/**
 * Invoke the TextAlign service for aligning two representations of text, e.g. letters in orthographic transcript with phonemes in a phonemic transcription.
 * @param i CSV text file with two semicolon-separated columns. Each row contains a sequence pair to be aligned. The sequence elements must be separated by a blank. Example: a word and its canonical transcription like S c h e r z;S E6 t s.
 * @param cost Cost function for the edit operations substitution, deletion, and insertion to be used for the alignment.
 * <ul>/*  w  w w. j a  va2s  .c  o  m*/
 *  <li>"naive" - assigns cost 1 to all operations except of null-substitution, i.e. the substitution of a symbol by itself, which receives cost 0. This 'naive' cost function should be used only if the pairs to be aligned share the same vocabulary, which is NOT the case e.g. in grapheme-phoneme alignment (grapheme 'x' is not the same as phoneme 'x').</li>
 *  <li>"g2p_deu", "g2p_eng" etc. are predefined cost functions for grapheme-phoneme alignment for the respective language expressed as iso639-3.</li>
 *  <li>"intrinsic" -  a cost function is trained on the input data and returned in the output zip. Costs are derived from co-occurrence probabilities, thus the bigger the input file, the more reliable the emerging cost function.</li> 
 *  <li>"import" - the user can provide his/her own cost function file, that must be a semicolon-separated 3-column csv text file. Examples: v;w;0.7 - the substitution of 'v' by 'w' costs 0.7. v;_;0.8 - the delition of 'v' costs 0.8; _;w;0.9 - the insertion of 'w' costs 0.9. A typical usecase is to train a cost function on a big data set with cost='intrinsic', and to subsequently apply this cost function on smaller data sets with cost='import'.</li>
 * </ul>
 * @param costfile CSV text file with three semicolon-separated columns. Each row contains three columns of the form a;b;c, where c denotes the cost for substituting a by b. Insertion and deletion are are marked by an underscore.
 * @param displc whether alignment costs should be displayed in a third column in the output file. 
 * @param atype Alignment type:
 *  <ul>
 *   <li>"dir" - align the second column to the first.</li>
 *   <li>"sym" symmetric alignment.</li>
 *  </ul>
 * @return The response to the request.
 * @throws IOException If an IO error occurs.
 * @throws ParserConfigurationException If the XML parser for parsing the response could not be     */
public BASResponse TextAlign(InputStream i, String cost, InputStream costfile, Boolean displc, String atype)
        throws IOException, ParserConfigurationException {
    if (displc == null)
        displc = Boolean.FALSE;
    if (atype == null)
        atype = "dir";
    HttpPost request = new HttpPost(getTextAlignUrl());
    MultipartEntityBuilder builder = MultipartEntityBuilder.create()
            .addBinaryBody("i", i, ContentType.create("text/csv"), "BAS.csv").addTextBody("cost", cost)
            .addTextBody("displc", displc ? "yes" : "no").addTextBody("atype", atype);
    if (costfile != null)
        builder.addBinaryBody("costfile", costfile, ContentType.create("text/csv"), "BAS.cst.csv");
    HttpEntity entity = builder.build();
    request.setEntity(entity);
    HttpResponse httpResponse = httpclient.execute(request);
    HttpEntity result = httpResponse.getEntity();
    return new BASResponse(result.getContent());
}