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:com.redhat.jenkins.plugins.bayesian.Bayesian.java

public BayesianStepResponse submitStackForAnalysis(Collection<FilePath> manifests) throws BayesianException {
    String stackAnalysesUrl = getApiUrl() + "/stack-analyses";
    HttpPost httpPost = new HttpPost(stackAnalysesUrl);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    for (FilePath manifest : manifests) {
        byte[] content = null;
        try (InputStream in = manifest.read()) {
            content = ByteStreams.toByteArray(in);
            builder.addBinaryBody("manifest[]", content, ContentType.DEFAULT_BINARY, manifest.getName());
        } catch (IOException | InterruptedException e) {
            throw new BayesianException(e);
        } finally {
            content = null;//from  ww w  .j ava 2 s . c  om
        }
    }
    HttpEntity multipart = builder.build();
    builder = null;
    httpPost.setEntity(multipart);
    httpPost.setHeader("Authorization", "Bearer " + getAuthToken());

    BayesianResponse responseObj = null;
    Gson gson;
    try (CloseableHttpClient client = HttpClients.createDefault();
            CloseableHttpResponse response = client.execute(httpPost)) {
        HttpEntity entity = response.getEntity();
        // Yeah, the endpoint actually returns 200 from some reason;
        // I wonder what happened to the good old-fashioned 202 :)
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new BayesianException("Bayesian error: " + response.getStatusLine().getStatusCode());
        }

        Charset charset = ContentType.get(entity).getCharset();
        try (InputStream is = entity.getContent();
                Reader reader = new InputStreamReader(is,
                        charset != null ? charset : HTTP.DEF_CONTENT_CHARSET)) {
            gson = new GsonBuilder().create();
            responseObj = gson.fromJson(reader, BayesianResponse.class);
            String analysisUrl = stackAnalysesUrl + "/" + responseObj.getId();
            return new BayesianStepResponse(responseObj.getId(), "", analysisUrl, true);
        }
    } catch (IOException e) {
        throw new BayesianException("Bayesian error", e);
    } finally {
        // just to be sure...
        responseObj = null;
        httpPost = null;
        multipart = null;
        gson = null;
    }
}

From source file:org.brunocvcunha.instagram4j.requests.InstagramUploadAlbumRequest.java

/**
 * Creates required multipart entity with the image binary
 * @return HttpEntity to send on the post
 * @throws ClientProtocolException//from w  ww .  j a  va  2s .c om
 * @throws IOException
 */
protected HttpEntity createMultipartEntity(File imageFile, String uploadId)
        throws ClientProtocolException, IOException {
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addTextBody("upload_id", uploadId);
    builder.addTextBody("_uuid", api.getUuid());
    builder.addTextBody("_csrftoken", api.getOrFetchCsrf());
    builder.addTextBody("image_compression",
            "{\"lib_name\":\"jt\",\"lib_version\":\"1.3.0\",\"quality\":\"87\"}");
    builder.addBinaryBody("photo", imageFile, ContentType.APPLICATION_OCTET_STREAM,
            "pending_media_" + uploadId + ".jpg");
    builder.setBoundary(api.getUuid());

    HttpEntity entity = builder.build();
    return entity;
}

From source file:org.brunocvcunha.instagram4j.requests.InstagramUploadStoryPhotoRequest.java

/**
 * Creates required multipart entity with the image binary
 * @return HttpEntity to send on the post
 * @throws ClientProtocolException//from ww  w  .j  a  va  2 s . c om
 * @throws IOException
 */
protected HttpEntity createMultipartEntity(String uploadId) throws ClientProtocolException, IOException {
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addTextBody("upload_id", uploadId);
    builder.addTextBody("_uuid", api.getUuid());
    builder.addTextBody("_csrftoken", api.getOrFetchCsrf());
    builder.addTextBody("image_compression",
            "{\"lib_name\":\"jt\",\"lib_version\":\"1.3.0\",\"quality\":\"87\"}");
    builder.addBinaryBody("photo", imageFile, ContentType.APPLICATION_OCTET_STREAM,
            "pending_media_" + uploadId + ".jpg");
    builder.setBoundary(api.getUuid());

    HttpEntity entity = builder.build();
    return entity;
}

From source file:org.apache.nifi.api.client.impl.AbstractNiFiAPIClient.java

public <U extends Entity> Object post(Class<? extends ApplicationResource> resourceClass, Method nifiApiMethod,
        U u, Map<String, String> pathParams, InputStream payloadData) {

    StringBuilder stringBuilder = new StringBuilder(this.baseUrl);
    stringBuilder.append(resourceClass.getAnnotation(Path.class).value());
    stringBuilder.append("/");
    stringBuilder.append(nifiApiMethod.getAnnotation(Path.class).value());

    String fullRequest = replaceUriWithPathParams(stringBuilder.toString(), pathParams);

    HttpPost request = new HttpPost(fullRequest);

    StringBuffer result = new StringBuffer();
    try {/* www. j a va2  s. c  o  m*/

        //Set the Accept and Content-Type headers appropriately.
        String produces = nifiApiMethod.getAnnotation(Produces.class).value()[0];
        String consumes = nifiApiMethod.getAnnotation(Consumes.class).value()[0];

        //Set POST request payload. Can only upload either Inputstream OR Object currently.
        if (u != null || payloadData != null) {
            if (u != null) {
                StringEntity input = new StringEntity(mapper.writeValueAsString(u));
                request.setEntity(input);
                request.setHeader("Content-type", consumes);
            } else {
                InputStreamEntity inputStreamEntity = new InputStreamEntity(payloadData);
                request.setEntity(inputStreamEntity);

                MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                //builder.addTextBody("field1", "yes", ContentType.TEXT_PLAIN);

                // This attaches the file to the POST:
                builder.addBinaryBody("template", payloadData, ContentType.APPLICATION_OCTET_STREAM,
                        "SomethingTest.xml");

                HttpEntity multipart = builder.build();
                request.setEntity(multipart);
            }
        }

        request.addHeader("Accept", produces);

        HttpResponse response = client.execute(request);

        //Examine the return type and handle that data appropriately.
        Header rCT = response.getHeaders("Content-Type")[0];
        if (rCT.getValue().equalsIgnoreCase("application/xml")) {
            //                TemplateDTO templateDTO = TemplateDeserializer.deserialize(response.getEntity().getContent());
            //                return templateDTO;
            return null;
        } else {
            return mapper.readValue(response.getEntity().getContent(),
                    nifiApiMethod.getAnnotation(ApiOperation.class).response());
        }

    } catch (Exception ex) {
        logger.error("Unable to complete HTTP POST due to {}", ex.getMessage());
        return null;
    }
}

From source file:com.nridge.ds.solr.SolrConfigSet.java

/**
 * Uploads the Solr config set ZIP file into the search cluster.
 *
 * @see <a href="http://lucene.apache.org/solr/guide/7_6/configsets-api.html">Solr ConfigSets API</a>
 * @see <a href="https://www.baeldung.com/httpclient-post-http-request">Upload Binary File with HttpClient 4</a>
 *
 * @param aPathFileName Path file name of ZIP containing the configuration set.
 * @param aConfigSetName Config set name.
 *
 * @throws DSException Solr Data Source exception.
 *//*from  ww w  .  j  a v  a  2  s.  c  o  m*/
public void uploadZipFile(String aPathFileName, String aConfigSetName) throws DSException {
    Logger appLogger = mAppMgr.getLogger(this, "uploadZipFile");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    initialize();

    String baseSolrURL = mSolrDS.getBaseURL(false);
    String solrURI = String.format("%s/admin/configs?action=UPLOAD&name=%s", baseSolrURL, aConfigSetName);

    File pathFile = new File(aPathFileName);
    CloseableHttpResponse httpResponse = null;
    HttpPost httpPost = new HttpPost(solrURI);
    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
    multipartEntityBuilder.addBinaryBody("file", pathFile, ContentType.APPLICATION_OCTET_STREAM, "file.zip");
    HttpEntity httpEntity = multipartEntityBuilder.build();
    httpPost.setEntity(httpEntity);
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {
        httpResponse = httpClient.execute(httpPost);
        StatusLine statusLine = httpResponse.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        String msgStr = String.format("%s [%d]: %s", solrURI, statusCode, statusLine);
        appLogger.debug(msgStr);
        if (statusCode == HttpStatus.SC_OK) {
            httpEntity = httpResponse.getEntity();
            EntityUtils.consume(httpEntity);
        } else {
            msgStr = String.format("%s [%d]: %s", solrURI, statusCode, statusLine);
            appLogger.error(msgStr);
            throw new DSException(msgStr);
        }
    } catch (IOException e) {
        String msgStr = String.format("%s: %s", solrURI, e.getMessage());
        appLogger.error(msgStr, e);
        throw new DSException(msgStr);
    } finally {
        if (httpResponse != null)
            IO.closeQuietly(httpResponse);
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

From source file:org.brunocvcunha.instagram4j.requests.InstagramUploadPhotoRequest.java

/**
 * Creates required multipart entity with the image binary
 * @return HttpEntity to send on the post
 * @throws ClientProtocolException/*from w ww  .j  a  va  2s .c o  m*/
 * @throws IOException
 */
protected HttpEntity createMultipartEntity() throws ClientProtocolException, IOException {
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addTextBody("upload_id", uploadId);
    builder.addTextBody("_uuid", api.getUuid());
    builder.addTextBody("_csrftoken", api.getOrFetchCsrf());
    builder.addTextBody("image_compression",
            "{\"lib_name\":\"jt\",\"lib_version\":\"1.3.0\",\"quality\":\"87\"}");
    builder.addBinaryBody("photo", bufferedImageToByteArray(imageFile), ContentType.APPLICATION_OCTET_STREAM,
            "pending_media_" + uploadId + ".jpg");
    builder.setBoundary(api.getUuid());

    HttpEntity entity = builder.build();
    return entity;
}

From source file:be.ugent.psb.coexpnetviz.io.JobServer.java

private HttpEntity makeRequestEntity(JobDescription job) throws UnsupportedEncodingException {

    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();

    // Action to request of server
    entityBuilder.addTextBody("__controller", "api");
    entityBuilder.addTextBody("__action", "execute_job");

    // Baits /*from   w w  w  .  j av  a  2 s. c  o  m*/
    if (job.getBaitGroupSource() == BaitGroupSource.FILE) {
        entityBuilder.addBinaryBody("baits_file", job.getBaitGroupPath().toFile(), ContentType.TEXT_PLAIN,
                job.getBaitGroupPath().getFileName().toString());
    } else if (job.getBaitGroupSource() == BaitGroupSource.TEXT) {
        entityBuilder.addTextBody("baits", job.getBaitGroupText());
    } else {
        assert false;
    }

    // Expression matrices
    for (Path path : job.getExpressionMatrixPaths()) {
        entityBuilder.addBinaryBody("matrix[]", path.toFile(), ContentType.TEXT_PLAIN, path.toString());
    }

    // Correlation method
    String correlationMethod = null;
    if (job.getCorrelationMethod() == CorrelationMethod.MUTUAL_INFORMATION) {
        correlationMethod = "mutual_information";
    } else if (job.getCorrelationMethod() == CorrelationMethod.PEARSON) {
        correlationMethod = "pearson_r";
    } else {
        assert false;
    }
    entityBuilder.addTextBody("correlation_method", correlationMethod);

    // Cutoffs
    entityBuilder.addTextBody("lower_percentile_rank", Double.toString(job.getLowerPercentile()));
    entityBuilder.addTextBody("upper_percentile_rank", Double.toString(job.getUpperPercentile()));

    // Gene families source
    String orthologsSource = null;
    if (job.getGeneFamiliesSource() == GeneFamiliesSource.PLAZA) {
        orthologsSource = "plaza";
    } else if (job.getGeneFamiliesSource() == GeneFamiliesSource.CUSTOM) {
        orthologsSource = "custom";
        entityBuilder.addBinaryBody("gene_families", job.getGeneFamiliesPath().toFile(), ContentType.TEXT_PLAIN,
                job.getGeneFamiliesPath().getFileName().toString());
    } else if (job.getGeneFamiliesSource() == GeneFamiliesSource.NONE) {
        orthologsSource = "none";
    } else {
        assert false;
    }
    entityBuilder.addTextBody("gene_families_source", orthologsSource);

    return entityBuilder.build();
}

From source file:org.geogig.geoserver.rest.GeoGigWebAPIIntegrationTest.java

@Test
public void testGeoPackageImport() throws Exception {

    URL url = getClass().getResource("places.gpkg");

    // create transaction
    final String beginTransactionUrl = BASE_URL + "/beginTransaction";

    Document dom = getAsDOM(beginTransactionUrl);
    assertXpathEvaluatesTo("true", "/response/success", dom);
    String transactionId = XMLUnit.newXpathEngine().evaluate("/response/Transaction/ID", dom);

    // import geopackage
    final String importUrl = BASE_URL + "/import?format=gpkg&message=Import%20GeoPackage&transactionId="
            + transactionId;//  ww  w .  j  ava2  s  . c  o  m
    final String endTransactionUrl = BASE_URL + "/endTransaction?transactionId=" + transactionId;

    // construct a multipart request with the fileUpload
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    File f = new File(url.getFile());
    builder.addBinaryBody("fileUpload", new FileInputStream(f), ContentType.APPLICATION_OCTET_STREAM,
            f.getName());

    HttpEntity multipart = builder.build();

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    multipart.writeTo(outputStream);
    MockHttpServletResponse response = postAsServletResponse(importUrl, outputStream.toByteArray(),
            multipart.getContentType().getValue());

    assertEquals(200, response.getStatus());

    dom = dom(new ByteArrayInputStream(response.getContentAsString().getBytes()), true);
    String taskId = XMLUnit.newXpathEngine().evaluate("/task/id", dom);
    final String taskUrl = "/geogig/tasks/" + taskId + ".xml";
    while ("RUNNING".equals(XMLUnit.newXpathEngine().evaluate("/task/status", dom))) {
        Thread.sleep(100);
        dom = getAsDOM(taskUrl);
    }
    assertXpathEvaluatesTo("FINISHED", "/task/status", dom);
    String commitId = XMLUnit.newXpathEngine().evaluate("//commit/id", dom);

    // close transaction
    dom = getAsDOM(endTransactionUrl);
    assertXpathEvaluatesTo("true", "/response/success", dom);

    // verify the repo contains the import
    Repository repository = geogigData.getGeogig().getRepository();
    RevCommit head = repository.getCommit(repository.getHead().get().getObjectId());
    assertEquals(commitId, head.getId().toString());
    assertEquals("Import GeoPackage", head.getMessage());
}

From source file:com.scoopit.weedfs.client.WeedFSClientImpl.java

private int write(WeedFSFile file, Location location, File fileToUpload, byte[] dataToUpload,
        InputStream inputToUpload, String fileName) throws IOException, WeedFSException {
    StringBuilder url = new StringBuilder();
    if (!location.publicUrl.contains("http")) {
        url.append("http://");
    }//from w  w  w.  j  a  v  a 2 s .c om
    url.append(location.publicUrl);
    url.append('/');
    url.append(file.fid);

    if (file.version > 0) {
        url.append('_');
        url.append(file.version);
    }

    HttpPost post = new HttpPost(url.toString());

    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
    if (fileToUpload != null) {
        if (fileName == null) {
            fileName = fileToUpload.getName();
        }
        multipartEntityBuilder.addBinaryBody("file", fileToUpload, ContentType.APPLICATION_OCTET_STREAM,
                sanitizeFileName(fileName));
    } else if (dataToUpload != null) {
        multipartEntityBuilder.addBinaryBody("file", dataToUpload, ContentType.APPLICATION_OCTET_STREAM,
                sanitizeFileName(fileName));
    } else {
        multipartEntityBuilder.addBinaryBody("file", inputToUpload, ContentType.APPLICATION_OCTET_STREAM,
                sanitizeFileName(fileName));
    }
    post.setEntity(multipartEntityBuilder.build());

    try {
        HttpResponse response = httpClient.execute(post);

        String content = getContentOrNull(response);
        ObjectMapper mapper = new ObjectMapper();
        try {
            WriteResult result = mapper.readValue(content, WriteResult.class);

            if (result.error != null) {
                throw new WeedFSException(result.error);
            }

            return result.size;
        } catch (JsonMappingException | JsonParseException e) {
            throw new WeedFSException("Unable to parse JSON from weed-fs from: " + content, e);
        }
    } finally {
        post.abort();
    }
}