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

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

Introduction

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

Prototype

public static MultipartEntityBuilder create() 

Source Link

Usage

From source file:functionaltests.RestSchedulerJobTaskTest.java

@Test
public void testSubmit() throws Exception {
    String schedulerUrl = getResourceUrl("submit");
    HttpPost httpPost = new HttpPost(schedulerUrl);
    setSessionHeader(httpPost);
    File jobFile = RestFuncTHelper.getDefaultJobXmlfile();
    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().addPart("file",
            new FileBody(jobFile, ContentType.APPLICATION_XML));
    httpPost.setEntity(multipartEntityBuilder.build());
    HttpResponse response = executeUriRequest(httpPost);
    assertHttpStatusOK(response);//from  w  w w  .j  a v  a  2s . co m
    JSONObject jsonObj = toJsonObject(response);
    assertNotNull(jsonObj.get("id").toString());
}

From source file:org.zaproxy.zap.extension.zapwso2jiraplugin.JiraRestClient.java

public static void invokePutMethodWithFile(String auth, String url, String path) {

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httppost = new HttpPost(url);
    httppost.setHeader("X-Atlassian-Token", "nocheck");
    httppost.setHeader("Authorization", "Basic " + auth);

    File fileToUpload = new File(path);
    FileBody fileBody = new FileBody(fileToUpload);

    HttpEntity entity = MultipartEntityBuilder.create().addPart("file", fileBody).build();

    httppost.setEntity(entity);/*from ww  w . ja v  a2  s.c o m*/
    CloseableHttpResponse response = null;

    try {
        response = httpclient.execute(httppost);
    } catch (Exception e) {
        log.error("File upload failed when involing the update method with file ");
    } finally {
        try {
            httpclient.close();
        } catch (IOException e) {
            log.error("Exception occered when closing the connection");
        }
    }
}

From source file:com.vaushell.superpipes.tools.scribe.twitter.TwitterClient.java

/**
 * Tweet picture./*from  w w  w .j ava2s  . c o  m*/
 *
 * @param message Tweet's content
 * @param is InputStream of the picture
 * @return Tweet's ID
 * @throws IOException
 * @throws OAuthException
 */
public long tweetPicture(final String message, final InputStream is) throws IOException, OAuthException {
    if (message == null || is == null) {
        throw new IllegalArgumentException();
    }

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("[" + getClass().getSimpleName() + "] tweetPicture() : message=" + message);
    }

    final OAuthRequest request = new OAuthRequest(Verb.POST,
            "https://api.twitter.com/1.1/statuses/update_with_media.json");
    final HttpEntity entity = MultipartEntityBuilder.create().addBinaryBody("status", message.getBytes("UTF-8"))
            .addBinaryBody("media[]", is, ContentType.APPLICATION_OCTET_STREAM, "media").build();

    final Header contentType = entity.getContentType();
    request.addHeader(contentType.getName(), contentType.getValue());

    try (final ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
        entity.writeTo(bos);
        request.addPayload(bos.toByteArray());
    }

    final Response response = sendSignedRequest(request);

    final ObjectMapper mapper = new ObjectMapper();
    final JsonNode node = (JsonNode) mapper.readTree(response.getStream());

    checkErrors(response, node);

    return node.get("id").asLong();
}

From source file:Vdisk.java

public void upload_file(String local_filepath, String filepath)
        throws URISyntaxException, FileNotFoundException, IOException {
    File file = new File(local_filepath);
    URI uri = new URIBuilder().setScheme("http").setHost("upload-vdisk.sina.com.cn/2/files/sandbox/")
            .setPath(filepath).setParameter("access_token", this.access_token).build();
    HttpPost httpPost = new HttpPost(uri);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, local_filepath);
    HttpEntity entity = builder.build();
    httpPost.setEntity(entity);/*w w  w  . ja v  a2s.  c o m*/
    CloseableHttpClient postClient = HttpClients.createDefault();
    try (CloseableHttpResponse response = postClient.execute(httpPost)) {
        System.out.println(response);//check result
    } finally {
        postClient.close();
    }
}

From source file:com.microsoft.cognitive.speakerrecognition.SpeakerRestClientHelper.java

/**
 * Adds a stream to an HTTP entity//w  w  w .j a v a 2s.c  o m
 *
 * @param someStream Input stream to be added to an HTTP entity
 * @param fieldName A description of the entity content
 * @param fileName Name of the file attached as an entity
 * @return HTTP entity
 * @throws IOException Signals a failure while reading the input stream
 */
HttpEntity addStreamToEntity(InputStream someStream, String fieldName, String fileName) throws IOException {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    int bytesRead;
    byte[] bytes = new byte[1024];
    while ((bytesRead = someStream.read(bytes)) > 0) {
        byteArrayOutputStream.write(bytes, 0, bytesRead);
    }
    byte[] data = byteArrayOutputStream.toByteArray();

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.setStrictMode();
    builder.addBinaryBody(fieldName, data, ContentType.MULTIPART_FORM_DATA, fileName);
    return builder.build();
}

From source file:objective.taskboard.it.TemplateIT.java

private HttpResponse uploadTemplate(File file) throws URISyntaxException, IOException {
    FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    StringBody templateName = new StringBody(file.getName(), ContentType.MULTIPART_FORM_DATA);
    StringBody roles = new StringBody("Role", ContentType.MULTIPART_FORM_DATA);
    builder.addPart("file", fileBody);
    builder.addPart("name", templateName);
    builder.addPart("roles", roles);
    HttpEntity entity = builder.build();

    HttpPost post = new HttpPost();
    post.setURI(new URI("http://localhost:8900/api/templates"));
    post.setHeaders(session);//w  w  w. j  ava  2s  . c o m
    post.setEntity(entity);

    return client.execute(post);
}

From source file:be.samey.io.ServerConn.java

private HttpEntity makeEntity(String baits, String[] names, Path[] filepaths, double poscutoff,
        double negcutoff, String[] orthNames, Path[] orthPaths) throws UnsupportedEncodingException {

    MultipartEntityBuilder mpeb = MultipartEntityBuilder.create();

    //make hidden form fields, to the server knows to use the api
    mpeb.addPart("__controller", new StringBody("api"));
    mpeb.addPart("__action", new StringBody("execute_job"));

    //make the bait part
    StringBody baitspart = new StringBody(baits, ContentType.TEXT_PLAIN);
    mpeb.addPart("baits", baitspart);

    //make the species file upload parts
    for (int i = 0; i < CyModel.MAX_SPECIES_COUNT; i++) {
        if (i < names.length && i < filepaths.length) {
            mpeb.addBinaryBody("matrix[]", filepaths[i].toFile(), ContentType.TEXT_PLAIN, names[i]);
        }/*from   w  w  w.  j a  v a  2 s.c om*/
    }

    //make the cutoff parts
    StringBody poscpart = new StringBody(Double.toString(poscutoff));
    mpeb.addPart("positive_correlation", poscpart);
    StringBody negcpart = new StringBody(Double.toString(negcutoff));
    mpeb.addPart("negative_correlation", negcpart);

    //make the orthgroup file upload parts
    for (int i = 0; i < CyModel.MAX_ORTHGROUP_COUNT; i++) {
        if (cyModel.getOrthGroupPaths() != null && i < orthNames.length && i < orthPaths.length) {
            mpeb.addBinaryBody("orthologs[]", orthPaths[i].toFile(), ContentType.TEXT_PLAIN, orthNames[i]);
        }
    }

    return mpeb.build();
}

From source file:net.ychron.unirestinst.request.body.MultipartBody.java

public HttpEntity getEntity() {
    if (hasFile) {
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        if (mode != null) {
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        }//from   w w  w  .  j  a  va  2s  . c o  m
        for (String key : parameters.keySet()) {
            List<Object> value = parameters.get(key);
            ContentType contentType = contentTypes.get(key);
            for (Object cur : value) {
                if (cur instanceof File) {
                    File file = (File) cur;
                    builder.addPart(key, new FileBody(file, contentType, file.getName()));
                } else if (cur instanceof InputStreamBody) {
                    builder.addPart(key, (ContentBody) cur);
                } else if (cur instanceof ByteArrayBody) {
                    builder.addPart(key, (ContentBody) cur);
                } else {
                    builder.addPart(key, new StringBody(cur.toString(), contentType));
                }
            }
        }
        return builder.build();
    } else {
        try {
            return new UrlEncodedFormEntity(MapUtil.getList(parameters), UTF_8);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:io.wcm.maven.plugins.contentpackage.InstallMojo.java

/**
 * Deploy file via package manager//w ww . ja va  2 s .  com
 */
private void installFile(File file) throws MojoExecutionException {
    try (CloseableHttpClient httpClient = getHttpClient()) {

        // if bundles are still stopping/starting, wait for completion
        waitForBundlesActivation(httpClient);

        if (this.install) {
            getLog().info("Upload and install " + file.getName() + " to " + getCrxPackageManagerUrl());
        } else {
            getLog().info("Upload " + file.getName() + " to " + getCrxPackageManagerUrl());
        }

        // prepare post method
        HttpPost post = new HttpPost(getCrxPackageManagerUrl() + "/.json?cmd=upload");
        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create().addBinaryBody("package", file);
        if (this.force) {
            entityBuilder.addTextBody("force", "true");
        }
        post.setEntity(entityBuilder.build());

        // execute post
        JSONObject jsonResponse = executePackageManagerMethodJson(httpClient, post);
        boolean success = jsonResponse.optBoolean("success", false);
        String msg = jsonResponse.optString("msg", null);
        String path = jsonResponse.optString("path", null);

        if (success) {

            if (this.install) {
                getLog().info("Package uploaded, now installing...");

                try {
                    post = new HttpPost(getCrxPackageManagerUrl() + "/console.html"
                            + new URIBuilder().setPath(path).build().getRawPath() + "?cmd=install"
                            + (this.recursive ? "&recursive=true" : ""));
                } catch (URISyntaxException ex) {
                    throw new MojoExecutionException("Invalid path: " + path, ex);
                }

                // execute post
                executePackageManagerMethodHtml(httpClient, post, 0);
            } else {
                getLog().info("Package uploaded successfully (without installing).");
            }

        } else if (StringUtils.startsWith(msg, CRX_PACKAGE_EXISTS_ERROR_MESSAGE_PREFIX) && !this.force) {
            getLog().info("Package skipped because it was already uploaded.");
        } else {
            throw new MojoExecutionException("Package upload failed: " + msg);
        }

    } catch (IOException ex) {
        throw new MojoExecutionException("Install operation failed.", ex);
    }
}

From source file:at.gv.egiz.sl.util.BKUSLConnector.java

private String performHttpRequestToBKU(String xmlRequest, RequestPackage pack, SignParameter parameter)
        throws ClientProtocolException, IOException, IllegalStateException {
    CloseableHttpClient client = null;//from ww w  . ja v  a2s.co  m
    try {
        client = buildHttpClient();
        HttpPost post = new HttpPost(this.bkuUrl);

        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
        entityBuilder.setCharset(Charset.forName("UTF-8"));
        entityBuilder.addTextBody(XMLREQUEST, xmlRequest,
                ContentType.TEXT_XML.withCharset(Charset.forName("UTF-8")));

        if (parameter != null) {
            String transactionId = parameter.getTransactionId();
            if (transactionId != null) {
                entityBuilder.addTextBody("TransactionId_", transactionId);
            }
        }

        if (pack != null && pack.getSignatureData() != null) {
            entityBuilder.addBinaryBody("fileupload",
                    PDFUtils.blackOutSignature(pack.getSignatureData(), pack.getByteRange()));
        }
        post.setEntity(entityBuilder.build());

        HttpResponse response = client.execute(post);
        logger.debug("Response Code : " + response.getStatusLine().getStatusCode());

        if (parameter instanceof BKUHeaderHolder) {
            BKUHeaderHolder holder = (BKUHeaderHolder) parameter;
            Header[] headers = response.getAllHeaders();

            if (headers != null) {
                for (int i = 0; i < headers.length; i++) {
                    BKUHeader hdr = new BKUHeader(headers[i].getName(), headers[i].getValue());
                    logger.debug("Response Header : {}", hdr.toString());
                    if (hdr.toString().contains("Server")) {
                        BaseSLConnector.responseHeader = hdr.toString();
                    }

                    holder.getProcessInfo().add(hdr);

                }

            }

            BKUHeader hdr = new BKUHeader(ErrorConstants.STATUS_INFO_SIGDEVICE, SIGNATURE_DEVICE);
            logger.debug("Response Header : {}", hdr.toString());

            holder.getProcessInfo().add(hdr);

        }

        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        rd.close();
        response = null;
        rd = null;

        logger.trace(result.toString());
        return result.toString();
    } catch (PDFIOException e) {
        throw new PdfAsWrappedIOException(e);
    } finally {
        if (client != null) {
            client.close();
        }
    }
}