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:org.matmaul.freeboxos.internal.RestManager.java

public HttpEntity createMultipartEntity(InputStream content, long length, String fileName) throws IOException {
    return MultipartEntityBuilder.create().addPart(fileName, new InpuStreamBody(content, length, fileName))
            .build();//  w  w  w .  j a va 2s  .com
}

From source file:SubmitResults.java

public boolean sendFile(Main parent, String hostname, String instanceFilePath, String status, String user,
        String password, boolean encrypted, String newIdent) {

    boolean submit_status = false;
    File tempFile = null;//from ww w.  ja va2s .c om

    // XSLT if ident needs to be changed
    final String changeIdXSLT = "<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">"
            + "<xsl:param name=\"surveyId\"/>" + "<xsl:template match=\"@*|node()\">" + "<xsl:copy>"
            + "<xsl:apply-templates select=\"@*|node()\"/>" + "</xsl:copy>" + "</xsl:template>"
            + "<xsl:template match=\"@id\">" + "<xsl:attribute name=\"id\">"
            + "<xsl:value-of select=\"$surveyId\"/>" + "</xsl:attribute>" + "</xsl:template>"
            + "</xsl:stylesheet>";

    //FileBody fb = null;
    ContentType ct = null;
    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    String urlString = null;
    HttpHost targetHost = null;
    if (encrypted) {
        urlString = "https://" + hostname + "/submission";
        targetHost = new HttpHost(hostname, 443, "https");
        parent.appendToStatus("   Using https");
        //credsProvider.setCredentials(
        //        new AuthScope(hostname, 443, "smap", "digest"),
        //        new UsernamePasswordCredentials(user, password));
        credsProvider.setCredentials(new AuthScope(hostname, 443, "smap", "basic"),
                new UsernamePasswordCredentials(user, password));
    } else {
        urlString = "http://" + hostname + "/submission";
        targetHost = new HttpHost(hostname, 80, "http");
        parent.appendToStatus("   Using http (not encrypted)");
        credsProvider.setCredentials(new AuthScope(hostname, 80, "smap", "digest"),
                new UsernamePasswordCredentials(user, password));
    }

    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();

    // get instance file
    File instanceFile = new File(instanceFilePath);

    if (!instanceFile.exists()) {
        parent.appendToStatus("   Error: Submission file " + instanceFilePath + " does not exist");
    } else {

        HttpPost req = new HttpPost(URI.create(urlString));
        //req.setHeader("form_status", status);                  // smap add form_status header

        tempFile = populateRequest(parent, status, instanceFilePath, req, changeIdXSLT, ct, entityBuilder,
                newIdent);

        // find all files in parent directory
        /*
        File[] allFiles = instanceFile.getParentFile().listFiles();
                
        // add media files ignoring invisible files and the submission file
        List<File> files = new ArrayList<File>();
        for (File f : allFiles) {
           String fileName = f.getName();
           if (!fileName.startsWith(".") && !fileName.equals(instanceFile.getName())) {   // ignore invisible files and instance xml file    
         files.add(f);
           }
        }
        */

        // add the submission file first...

        /*
        ct = ContentType.create("text/xml");
         //fb = new FileBody(instanceFile, ct);
         entity.addBinaryBody("xml_submission_file", instanceFile, ct, instanceFile.getPath());
         //entity.addPart("xml_submission_file", fb);
        */

        /*
        for (int j = 0; j < files.size(); j++) {
                  
                
            File f = files.get(j);
            String fileName = f.getName();
            int idx = fileName.lastIndexOf(".");
            String extension = "";
            if (idx != -1) {
           extension = fileName.substring(idx + 1);
            }
                
            // we will be processing every one of these, so
            // we only need to deal with the content type determination...
            if (extension.equals("xml")) {
          ct = ContentType.create("text/xml");
            } else if (extension.equals("jpg")) {
          ct = ContentType.create("image/jpeg");
            } else if (extension.equals("3gp")) {
          ct = ContentType.create("video/3gp");
            } else if (extension.equals("3ga")) {
          ct = ContentType.create("audio/3ga");
            } else if (extension.equals("mp4")) {
          ct = ContentType.create("video/mp4");
            } else if (extension.equals("m4a")) {
            ct = ContentType.create("audio/m4a");
            }else if (extension.equals("csv")) {
          ct = ContentType.create("text/csv");
            } else if (f.getName().endsWith(".amr")) {
          ct = ContentType.create("audio/amr");
            } else if (extension.equals("xls")) {
          ct = ContentType.create("application/vnd.ms-excel");
            }  else {
          ct = ContentType.create("application/octet-stream");
          parent.appendToStatus("   Info: unrecognised content type for extension " + extension);
                  
            }
                
            //fb = new FileBody(f, ct);
            //entity.addPart(f.getName(), fb);
            entity.addBinaryBody(f.getName(), f, ct, f.getName());
                 
           parent.appendToStatus("   Info: added file " + f.getName());
                
        }
        */

        //req.setEntity(entity.build());

        // prepare response and return uploaded
        HttpResponse response = null;
        try {

            // Create AuthCache instance
            AuthCache authCache = new BasicAuthCache();

            // Generate DIGEST scheme object, initialize it and add it to the local auth cache
            DigestScheme digestAuth = new DigestScheme();
            // Suppose we already know the realm name
            digestAuth.overrideParamter("realm", "smap");
            // Suppose we already know the expected nonce value
            digestAuth.overrideParamter("nonce", "whatever");
            authCache.put(targetHost, digestAuth);

            // Generate Basic scheme object
            BasicScheme basicAuth = new BasicScheme();
            authCache.put(targetHost, basicAuth);

            // Add AuthCache to the execution context
            HttpClientContext localContext = HttpClientContext.create();
            localContext.setAuthCache(authCache);

            parent.appendToStatus("   Info: submitting to: " + req.getURI().toString());
            response = httpclient.execute(targetHost, req, localContext);
            int responseCode = response.getStatusLine().getStatusCode();

            try {
                // have to read the stream in order to reuse the connection
                InputStream is = response.getEntity().getContent();
                // read to end of stream...
                final long count = 1024L;
                while (is.skip(count) == count)
                    ;
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }

            // verify that the response was a 201 or 202.
            // If it wasn't, the submission has failed.
            parent.appendToStatus("   Info: Response code: " + responseCode + " : "
                    + response.getStatusLine().getReasonPhrase());
            if (responseCode != HttpStatus.SC_CREATED && responseCode != HttpStatus.SC_ACCEPTED) {
                parent.appendToStatus("   Error: upload failed: ");
            } else {
                submit_status = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            parent.appendToStatus("   Error: Generic Exception. " + e.toString());
        }
    }

    try {
        httpclient.close();
    } catch (Exception e) {

    } finally {

    }

    if (tempFile != null) {
        tempFile.delete();
    }

    return submit_status;
}

From source file:com.imagesleuth.imagesleuthclient2.Poster.java

public String Post(final File imgFile) throws IOException, ImageReadException, InterruptedException {

    final ArrayList<String> idArray = new ArrayList<>();

    final CountDownLatch latch = new CountDownLatch(1);

    try (CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setDefaultHeaders(harray)
            .setDefaultCredentialsProvider(credsProvider).setDefaultRequestConfig(requestConfig).build()) {
        httpclient.start();/*from w ww  . j  a  va  2s.c om*/
        final byte[] imageAsBytes = IOUtils.toByteArray(new FileInputStream(imgFile));
        final ImageInfo info = Imaging.getImageInfo(imageAsBytes);
        final HttpPost request = new HttpPost(urlval);
        String boundary = UUID.randomUUID().toString();
        HttpEntity mpEntity = MultipartEntityBuilder.create().setBoundary("-------------" + boundary)
                .addBinaryBody("file", imageAsBytes, ContentType.create(info.getMimeType()), imgFile.getName())
                .build();
        ByteArrayOutputStream baoStream = new ByteArrayOutputStream();
        mpEntity.writeTo(baoStream);
        request.setHeader("Content-Type", "multipart/form-data;boundary=-------------" + boundary);
        //equest.setHeader("Content-Type", "multipart/form-data");                               
        NByteArrayEntity entity = new NByteArrayEntity(baoStream.toByteArray(),
                ContentType.MULTIPART_FORM_DATA);
        request.setEntity(entity);
        httpclient.execute(request, new FutureCallback<HttpResponse>() {

            @Override
            public void completed(final HttpResponse response) {
                int code = response.getStatusLine().getStatusCode();
                //System.out.println(" response code: " + code + " for image: " + imgFile.getName());
                if (response.getEntity() != null && code == 202) {
                    StringWriter writer = new StringWriter();
                    try {
                        IOUtils.copy(response.getEntity().getContent(), writer);
                        idArray.add(writer.toString());
                        writer.close();
                        //System.out.println(" response id: " + id + " for image "+ img.getName()); 
                        latch.countDown();
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                } else {
                    System.out.println(" response code: " + code + " for image: " + imgFile.getName()
                            + " reason " + response.getStatusLine().getReasonPhrase());
                }
            }

            @Override
            public void failed(final Exception ex) {
                System.out.println(request.getRequestLine() + imgFile.getName() + "->" + ex);
                latch.countDown();
            }

            @Override
            public void cancelled() {
                System.out.println(request.getRequestLine() + " cancelled");
                latch.countDown();
            }

        });
        latch.await();
    }
    if (idArray.isEmpty()) {
        return null;
    } else {
        return idArray.get(0);
    }
}

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.  ja v a  2s.c om
    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:gda.util.ElogEntry.java

/**
 * Post eLog Entry//from w ww .j  av  a2  s .  c o  m
 */
public void post() throws ELogEntryException {

    String entryType = "41";// entry type is always a log (41)

    String titleForPost = visit == null ? title : "Visit: " + visit + " - " + title;

    String content = buildContent();

    MultipartEntityBuilder request = MultipartEntityBuilder.create().addTextBody("txtTITLE", titleForPost)
            .addTextBody("txtCONTENT", content).addTextBody("txtLOGBOOKID", logID)
            .addTextBody("txtGROUPID", groupID).addTextBody("txtENTRYTYPEID", entryType)
            .addTextBody("txtUSERID", userID);

    HttpEntity entity = request.build();
    HttpPost httpPost = new HttpPost(targetPostURL);
    httpPost.setEntity(entity);

    CloseableHttpClient httpClient = null;
    CloseableHttpResponse response = null;

    try {
        httpClient = HttpClients.createDefault();
        response = httpClient.execute(httpPost);
        String responseString = EntityUtils.toString(response.getEntity());
        System.out.println(responseString);
        if (!responseString.contains("New Log Entry ID")) {
            throw new ELogEntryException("Upload failed, status=" + response.getStatusLine().getStatusCode()
                    + " response=" + responseString + " targetURL = " + targetPostURL + " titleForPost = "
                    + titleForPost + " logID = " + logID + " groupID = " + groupID + " entryType = " + entryType
                    + " userID = " + userID);
        }
    } catch (ELogEntryException e) {
        throw e;
    } catch (Exception e) {
        throw new ELogEntryException("Error in ELogger.  Database:" + targetPostURL, e);
    } finally {
        try {
            if (httpClient != null)
                httpClient.close();
            if (response != null)
                response.close();
        } catch (IOException e) {
            elogger.error("Could not close connections", e);
        }
    }

}

From source file:com.github.piotrkot.resources.CompilerResource.java

/**
 * Upload source for compiler./*from   www . j  a  v  a2s .  c o  m*/
 * @param user Logged in user.
 * @param stream File input stream.
 * @param details Form data details.
 * @return Compiler result view.
 */
@Path("/source")
@POST
@Timed
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_HTML)
public Response uploadSource(@Auth final User user, @FormDataParam("inputFile") final InputStream stream,
        @FormDataParam("inputFile") final FormDataContentDisposition details) {
    Response response = Response.serverError().build();
    try {
        final String request = Request.Post(String.format("%s/source", this.conf.getCompiler()))
                .setHeader(this.authorization(user))
                .body(MultipartEntityBuilder.create()
                        .addBinaryBody("file", stream, ContentType.DEFAULT_BINARY, details.getName()).build())
                .execute().returnContent().asString();
        response = Response.seeOther(URI.create(String.format("/compiler/result/%s", request))).build();
    } catch (final IOException ex) {
        log.error("Cannot connect to the server", ex);
    }
    return response;
}

From source file:com.huawei.ais.demo.TokenDemo.java

/**
 * Base64???Token???/*from  w w  w. ja v  a2  s.  c  o  m*/
 * @param token token?
 * @param formFile 
 * @throws IOException
 */
public static void requestOcrCustomsFormEnBase64(String token, String formFile) {

    // 1.?????
    String url = "https://ais.cn-north-1.myhuaweicloud.com/v1.0/ocr/action/ocr_form";
    Header[] headers = new Header[] { new BasicHeader("X-Auth-Token", token) };
    try {
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        FileBody fileBody = new FileBody(new File(formFile), ContentType.create("image/jpeg", "utf-8"));
        multipartEntityBuilder.addPart("file", fileBody);

        // 2.????, POST??
        HttpResponse response = HttpClientUtils.post(url, headers, multipartEntityBuilder.build());
        System.out.println(response);
        String content = IOUtils.toString(response.getEntity().getContent());
        System.out.println(content);
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:cc.sferalabs.libs.telegram.bot.api.TelegramBot.java

/**
 * Sends a request to the server./*www. j  a v a 2  s. com*/
 * 
 * @param <T>
 *            the class to cast the returned value to
 * @param request
 *            the request to be sent
 * @param timeout
 *            the read timeout value (in milliseconds) to be used for server
 *            response. A timeout of zero is interpreted as an infinite
 *            timeout
 * @return the JSON object representing the value of the field "result" of
 *         the response JSON object cast to the specified type parameter
 * @throws ResponseError
 *             if the server returned an error response, i.e. the value of
 *             the field "ok" of the response JSON object is {@code false}
 * @throws ParseException
 *             if an error occurs while parsing the server response
 * @throws IOException
 *             if an I/O exception occurs
 */
@SuppressWarnings("unchecked")
public <T> T sendRequest(Request request, int timeout) throws IOException, ParseException, ResponseError {
    HttpURLConnection connection = null;
    try {
        URL url = buildUrl(request);
        log.debug("Performing request: {}", url);
        connection = (HttpURLConnection) url.openConnection();
        connection.setReadTimeout(timeout);

        if (request instanceof SendFileRequest) {
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            Path filePath = ((SendFileRequest) request).getFilePath();
            builder.addBinaryBody(((SendFileRequest) request).getFileParamName(), filePath.toFile());
            HttpEntity multipart = builder.build();

            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", multipart.getContentType().getValue());
            connection.setRequestProperty("Content-Length", "" + multipart.getContentLength());

            try (OutputStream out = connection.getOutputStream()) {
                multipart.writeTo(out);
            }
        } else {
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Content-Length", "0");
        }

        boolean httpOk = connection.getResponseCode() == HttpURLConnection.HTTP_OK;
        try (InputStream in = httpOk ? connection.getInputStream() : connection.getErrorStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8))) {
            JSONObject resp = (JSONObject) parser.parse(br);
            log.debug("Response: {}", resp);

            boolean ok = (boolean) resp.get("ok");
            if (!ok) {
                String description = (String) resp.get("description");
                if (description == null) {
                    description = "ok=false";
                }
                throw new ResponseError(description);
            }
            return (T) resp.get("result");
        }
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:org.apache.heron.uploader.http.HttpUploader.java

private URI uploadPackageAndGetURI(final CloseableHttpClient httpclient)
        throws IOException, URISyntaxException {
    File file = new File(this.topologyPackageLocation);
    String uploaderUri = HttpUploaderContext.getHeronUploaderHttpUri(this.config);
    post = new HttpPost(uploaderUri);
    FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart(FILE, fileBody);/*from  www  . j  a  v a  2  s.co  m*/
    HttpEntity entity = builder.build();
    post.setEntity(entity);
    HttpResponse response = execute(httpclient);
    String responseString = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8.name());
    LOG.fine("Topology package download URI: " + responseString);

    return new URI(responseString);
}

From source file:com.diversityarrays.dalclient.httpimpl.DalHttpFactoryImpl.java

@Override
public DalRequest createForUpload(String url, List<Pair<String, String>> pairs, String rand_num,
        String namesInOrder, String signature, File fileForUpload) {

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    for (Pair<String, String> pair : pairs) {
        builder.addTextBody(pair.a, pair.b);
    }//from w  w  w . j  av  a  2 s  . c o m

    builder.addPart("uploadfile", new FileBody(fileForUpload)).addTextBody("rand_num", rand_num)
            .addTextBody("url", url);

    HttpEntity entity = builder.addTextBody("param_order", namesInOrder).addTextBody("signature", signature)
            .build();

    HttpPost post = new HttpPost(url);
    post.setEntity(entity);

    return new DalRequestImpl(post);
}