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

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

Introduction

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

Prototype

public HttpEntity build() 

Source Link

Usage

From source file:io.andyc.papercut.api.PrintApi.java

/**
 * Uploads the file and finalizes the printing
 *
 * @param printJob    {PrintJob} - the print job
 * @param prevElement {Element} - the previous Jsoup element containing the
 *                    upload file Html// w  ww .jav a  2  s.c  o  m
 *
 * @return {boolean} - whether or not the print job completed
 */
static boolean uploadFile(PrintJob printJob, Document prevElement)
        throws PrintingException, UnsupportedMimeTypeException {
    String uploadUrl = printJob.getSession().getDomain().replace("/app", "")
            + PrintApi.getUploadFileUrl(prevElement); // upload directory

    HttpPost post = new HttpPost(uploadUrl);
    CloseableHttpClient client = HttpClientBuilder.create().build();

    // configure multipart post request entity builder
    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    // build the file boundary
    String boundary = "-----------------------------" + new Date().getTime();
    entityBuilder.setBoundary(boundary);

    // set the file
    File file = new File(printJob.getFilePath());
    FileBody body = new FileBody(file,
            ContentType.create(ContentTypes.getApplicationType(printJob.getFilePath())), file.getName());
    entityBuilder.addPart("file[]", body);

    // build the post request
    HttpEntity multipart = entityBuilder.build();
    post.setEntity(multipart);

    // set cookie
    post.setHeader("Cookie", printJob.getSession().getSessionKey() + "=" + printJob.getSession().getSession());

    // send
    try {
        CloseableHttpResponse response = client.execute(post);
        return response.getStatusLine().getStatusCode() == 200;
    } catch (IOException e) {
        throw new PrintingException("Error uploading the file");
    }
}

From source file:eu.seaclouds.platform.dashboard.http.HttpPostRequestBuilder.java

public String build() throws IOException, URISyntaxException {
    if (!params.isEmpty() && entity == null) {
        if (!isMultipart) {
            this.entity = new UrlEncodedFormEntity(params);
        } else {/*from   www  .  j  ava 2  s . co m*/
            MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
            for (NameValuePair pair : params) {
                entityBuilder.addTextBody(pair.getName(), pair.getValue());
            }

            this.entity = entityBuilder.build();
        }
    }

    URI uri = new URIBuilder().setHost(host).setPath(path).setScheme(scheme).build();

    this.requestBase = new HttpPost(uri);

    for (NameValuePair header : super.headers) {
        requestBase.addHeader(header.getName(), header.getValue());
    }

    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
        if (this.entity != null) {
            this.requestBase.setEntity(this.entity);
        }
        return httpClient.execute(requestBase, responseHandler, context);
    }
}

From source file:org.metaeffekt.dcc.agent.UnitBasedEndpointUriBuilder.java

public HttpUriRequest buildHttpUriRequest(Commands command, Id<DeploymentId> deploymentId, Id<UnitId> unitId,
        Id<PackageId> packageId, Map<String, byte[]> executionProperties) {
    Validate.isTrue(executionProperties != null && !executionProperties.isEmpty());

    StringBuilder sb = new StringBuilder("/");
    sb.append(PATH_ROOT).append("/");
    sb.append(deploymentId).append("/");
    sb.append("packages").append("/").append(packageId).append("/");
    sb.append("units").append("/").append(unitId).append("/");
    sb.append(command);//from w  w w . jav a2 s .  c  om
    String path = sb.toString();

    URIBuilder uriBuilder = createUriBuilder();
    uriBuilder.setPath(path);
    URI uri;
    try {
        uri = uriBuilder.build();
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
    HttpPut put = new HttpPut(uri);

    final MultipartEntityBuilder multipartBuilder = MultipartEntityBuilder.create();
    for (Map.Entry<String, byte[]> entry : executionProperties.entrySet()) {
        multipartBuilder.addBinaryBody(entry.getKey(), entry.getValue());
    }

    put.setEntity(multipartBuilder.build());
    if (requestConfig != null) {
        put.setConfig(requestConfig);
    }
    return put;
}

From source file:com.jkoolcloud.tnt4j.streams.inputs.HttpStreamTest.java

@Test
public void httpFilePostTest() throws Exception {
    HttpClientBuilder builder = HttpClientBuilder.create();
    HttpClient client = builder.build();

    URI url = makeURI();//from w  w  w.j av a 2  s . c om
    HttpPost post = new HttpPost(url);

    File file = new File(samplesDir, "/http-file/log.txt");
    EntityBuilder entityBuilder = EntityBuilder.create();
    entityBuilder.setFile(file);
    entityBuilder.setContentType(ContentType.TEXT_PLAIN);

    MultipartEntityBuilder builder2 = MultipartEntityBuilder.create();
    builder2.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM, "file.ext"); // NON-NLS
    HttpEntity multipart = builder2.build();

    post.setEntity(multipart);

    final HttpResponse returned = client.execute(post);
    assertNotNull(returned);

}

From source file:com.cognifide.qa.bb.aem.content.ContentInstaller.java

/**
 * This method uploads, installs and replicates the package indicated by the name
 * provided as the method's parameter. For each of these actions activateAemPackage constructs
 * and sends a POST request to AEM instance. If any of the POST requests lead to NOK response,
 * activateAemPackage will throw an exception.
 * <br>//from  w ww. j  ava  2 s  .com
 * Method will look for content in the location indicated by the content.path property.
 * The content path defaults to "src/main/content".
 *
 * @param packageName Name of the package to be activated.
 * @throws IOException Thrown when AEM instance returns NOK response.
 */
public void activateAemPackage(String packageName) throws IOException {
    HttpPost upload = builder.createUploadRequest();
    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    entityBuilder.addBinaryBody("package", new File(CONTENT_PATH, packageName), ContentType.DEFAULT_BINARY,
            packageName);
    entityBuilder.addTextBody("force", "true");
    upload.setEntity(entityBuilder.build());
    JsonObject result = sender.sendCrxRequest(upload);
    String path = result.get("path").getAsString();

    HttpPost install = builder.createInstallRequest(path);
    sender.sendCrxRequest(install);

    HttpPost replicate = builder.createReplicateRequest(path);

    sender.sendCrxRequest(replicate);
}

From source file:org.alfresco.cacheserver.MultipartTest.java

@Test
public void test1() throws Exception {
    byte[] b = "Hello world".getBytes();
    InputStream in = new ByteArrayInputStream(b);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE).addBinaryBody("p_stream", in)
            .addTextBody("p_size", String.valueOf(b.length)).addTextBody("p_idx", String.valueOf(10));
    HttpEntity entity = builder.build();

    entity.writeTo(System.out);//from   w  w w  .  ja va 2s  .  c om
    //      BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
    //      while ((inputLine = br.readLine()) != null) {
    //         System.out.println(inputLine);
    //      }
    //      br.close();

    //      HttpPost httpPost = new HttpPost("http://localhost:2389/TESTME_WITH_NETCAT");
    //      httpPost.setEntity(entity);
}

From source file:com.android.tools.idea.diagnostics.crash.GoogleCrash.java

@Override
@NotNull/*from w w  w .jav a2 s. c o m*/
public CompletableFuture<String> submit(@NotNull CrashReport report, boolean userReported) {
    if (!userReported) { // all non user reported crash events are rate limited on the client side
        if (!myRateLimiter.tryAcquire()) {
            CompletableFuture<String> f = new CompletableFuture<>();
            f.completeExceptionally(new RuntimeException("Exceeded Quota of crashes that can be reported"));
            return f;
        }
    }

    Map<String, String> parameters = getDefaultParameters();
    if (report.version != null) {
        parameters.put(KEY_VERSION, report.version);
    }
    parameters.put(KEY_PRODUCT_ID, report.productId);

    MultipartEntityBuilder builder = newMultipartEntityBuilderWithKv(parameters);
    report.serialize(builder);
    return submit(builder.build());
}

From source file:org.eclipse.vorto.repository.RestModelRepository.java

@Override
public UploadResult upload(String name, byte[] model) {
    Objects.requireNonNull(model, "Model should not be null.");
    Objects.requireNonNull(name, "Name should not be null.");
    try {//  www.ja  v  a 2s.c  o  m
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addBinaryBody(FILE_PARAMETER_NAME, model, ContentType.APPLICATION_OCTET_STREAM, name);
        HttpEntity fileToUpload = builder.build();

        UploadResultView uploadResult = httpClient.executePost("secure", fileToUpload, uploadResponseConverter);

        return uploadResultConverter.apply(uploadResult);
    } catch (Exception e) {
        throw new CheckInModelException("Error in uploading file to remote repository", e);
    }
}

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);/*  ww  w.j a  va 2s.  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:jog.my.memory.gcm.ServerUtilities.java

/**
 * Uploads a file to the server./*from   www  .  jav a 2  s.com*/
 * @param context - Context of the app where the file is
 * @param serverUrl - URL of the server
 * @param uri - URI of the file
 * @return - response of posting the file to server
 */
public static String postFile(Context context, String serverUrl, Uri uri) { //TODO: Get the location sent up in here too!

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(serverUrl + "/upload");
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    //        //Create the FileBody
    //        final File file = new File(uri.getPath());
    //        FileBody fb = new FileBody(file);

    // deal with the file
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    Bitmap bitmap = BitmapFactory.decodeFile(getRealPathFromURI(uri, context));
    bitmap.compress(Bitmap.CompressFormat.JPEG, 75, byteArrayOutputStream);
    byte[] byteData = byteArrayOutputStream.toByteArray();
    //String strData = Base64.encodeToString(data, Base64.DEFAULT); // I have no idea why Im doing this
    ByteArrayBody byteArrayBody = new ByteArrayBody(byteData, "image"); // second parameter is the name of the image (//TODO HOW DO I MAKE IT USE THE IMAGE FILENAME?)

    builder.addPart("myFile", byteArrayBody);
    builder.addTextBody("foo", "test text");

    HttpEntity entity = builder.build();
    post.setEntity(entity);

    try {
        HttpResponse response = client.execute(post);
        Log.d(TAG, "The response code was: " + response.getStatusLine().getStatusCode());
    } catch (Exception e) {
        Log.d(TAG, "The image was not successfully uploaded.");
    }

    return null;

    //        HttpClient httpclient = new DefaultHttpClient();
    //        HttpPost httppost = new HttpPost(serverUrl+"/postFile.do");
    //
    //        InputStream stream = null;
    //        try {
    //            stream = context.getContentResolver().openInputStream(uri);
    //
    //            InputStreamEntity reqEntity = new InputStreamEntity(stream, -1);
    //
    //            httppost.setEntity(reqEntity);
    //
    //            HttpResponse response = httpclient.execute(httppost);
    //            Log.d(TAG,"The response code was: "+response.getStatusLine().getStatusCode());
    //            if (response.getStatusLine().getStatusCode() == 200) {
    //                // file uploaded successfully!
    //            } else {
    //                throw new RuntimeException("server couldn't handle request");
    //            }
    //            return response.toString();
    //        } catch (Exception e) {
    //            e.printStackTrace();
    //
    //            // handle error
    //        } finally {
    //            try {
    //                stream.close();
    //            }catch(IOException ioe){
    //                ioe.printStackTrace();
    //            }
    //        }
    //        return null;
}