Example usage for org.apache.http.entity.mime.content FileBody FileBody

List of usage examples for org.apache.http.entity.mime.content FileBody FileBody

Introduction

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

Prototype

public FileBody(final File file) 

Source Link

Usage

From source file:org.uberfire.provisioning.wildfly.runtime.provider.extras.Wildfly10RemoteClient.java

public int deploy(String user, String password, String host, int port, String filePath) {

    // the digest auth backend
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(host, port), new UsernamePasswordCredentials(user, password));

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

    HttpPost post = new HttpPost("http://" + host + ":" + port + "/management-upload");

    post.addHeader("X-Management-Client-Name", "HAL");

    // the file to be uploaded
    File file = new File(filePath);
    FileBody fileBody = new FileBody(file);

    // the DMR operation
    ModelNode operation = new ModelNode();
    operation.get("address").add("deployment", file.getName());
    operation.get("operation").set("add");
    operation.get("runtime-name").set(file.getName());
    operation.get("enabled").set(true);
    operation.get("content").add().get("input-stream-index").set(0); // point to the multipart index used

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    try {//from  w w  w.  j a  v  a  2 s .co m
        operation.writeBase64(bout);
    } catch (IOException ex) {
        getLogger(Wildfly10RemoteClient.class.getName()).log(SEVERE, null, ex);
    }

    // the multipart
    MultipartEntityBuilder builder = create();
    builder.setMode(BROWSER_COMPATIBLE);
    builder.addPart("uploadFormElement", fileBody);
    builder.addPart("operation",
            new ByteArrayBody(bout.toByteArray(), create("application/dmr-encoded"), "blob"));
    HttpEntity entity = builder.build();

    //entity.writeTo(System.out);
    post.setEntity(entity);

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

        out.println(">>> Deploying Response Entity: " + response.getEntity());
        out.println(">>> Deploying Response Satus: " + response.getStatusLine().getStatusCode());
        return response.getStatusLine().getStatusCode();
    } catch (IOException ex) {
        ex.printStackTrace();
        getLogger(Wildfly10RemoteClient.class.getName()).log(SEVERE, null, ex);
    }
    return -1;
}

From source file:org.ez.flickr.api.CommandArguments.java

public MultipartEntity getBody(Map<String, String> additionalParameters) {
    try {/*from  www  .  j  av  a 2 s. c  o  m*/
        MultipartEntity entity = new MultipartEntity();

        for (Parameter param : params) {
            if (!param.internal) {
                if (param.value instanceof File) {
                    entity.addPart(param.key, new FileBody((File) param.value));
                } else if (param.value instanceof String) {
                    entity.addPart(param.key, new StringBody((String) param.value, UTF8));
                }
            }
        }
        for (Map.Entry<String, String> entry : additionalParameters.entrySet()) {
            entity.addPart(entry.getKey(), new StringBody(entry.getValue(), UTF8));
        }

        return entity;

    } catch (UnsupportedEncodingException ex) {
        throw new UnsupportedOperationException(ex.getMessage(), ex);
    }
}

From source file:key.access.manager.HttpHandler.java

public boolean sendImage(String url, String employeeId, File imageFile) throws IOException {
    String userHome = System.getProperty("user.home");
    HttpClient httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    HttpPost httpPost = new HttpPost(url);
    FileBody fileBody = new FileBody(imageFile);
    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    reqEntity.addPart("fileToUpload", fileBody);
    reqEntity.addPart("employee_id", new StringBody(employeeId));

    httpPost.setEntity(reqEntity);/*from w ww. j  a  v  a  2  s  . c o  m*/

    // execute HTTP post request
    HttpResponse response = httpClient.execute(httpPost);
    HttpEntity resEntity = response.getEntity();

    if (resEntity != null) {
        String responseStr = EntityUtils.toString(resEntity).trim();
        System.out.println(responseStr);
        return true;
    } else {
        return false;
    }
}

From source file:com.kurento.test.recorder.RecorderIT.java

private void testRecord(String handler, int statusCode) throws IOException {
    // To follow redirect: .setRedirectStrategy(new LaxRedirectStrategy())
    HttpClient client = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost("http://localhost:" + getServerPort() + "/kmf-content-api-test/" + handler);
    MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
    multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    File file = new File("small");
    URL small = new URL(VideoURLs.map.get("small-webm"));
    FileUtils.copyURLToFile(small, file);
    FileBody fb = new FileBody(file);
    multipartEntity.addPart("file", fb);

    HttpEntity httpEntity = multipartEntity.build();
    post.setEntity(httpEntity);//  w w w .j ava  2s .  c o m

    EntityUtils.consume(httpEntity);
    HttpResponse response = client.execute(post);
    final int responseStatusCode = response.getStatusLine().getStatusCode();

    log.info("Response Status Code: {}", responseStatusCode);
    log.info("Deleting tmp file: {}", file.delete());

    Assert.assertEquals("HTTP response status code must be " + statusCode, statusCode, responseStatusCode);
}

From source file:de.xwic.appkit.core.file.impl.hbn.RemoteFileAccessClient.java

@Override
protected int storeFile(final File file) throws IOException {
    MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT);
    multipartEntity.addPart(PARAM_ACTION, new StringBody(ACTION_FILE_HANDLE));
    multipartEntity.addPart(PARAM_FH_ACTION, new StringBody(PARAM_FH_ACTION_UPLOAD));
    multipartEntity.addPart(PARAM_FH_STREAM, new FileBody(file));
    return URemoteAccessClient.multipartRequestInt(multipartEntity, config);
}

From source file:org.dataconservancy.ui.it.support.ValidatingMetadataFileRequest.java

public HttpPost asHttpPost() {
    if (fileToTest == null) {
        throw new IllegalStateException("File not set: call setFileToTest(File) first");
    }/*  www.j a v  a2 s . com*/

    String validatingMetadataFileUrl = urlConfig.getAdminValidatingMetadataFilePathPostUrl().toString();
    HttpPost post = new HttpPost(validatingMetadataFileUrl);
    MultipartEntity entity = new MultipartEntity();
    try {
        entity.addPart(STRIPES_EVENT, new StringBody("Validate", Charset.forName("UTF-8")));
        entity.addPart("metadataFormatId", new StringBody(formatId, Charset.forName("UTF-8")));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    FileBody fileBody = new FileBody(fileToTest);
    entity.addPart("sampleMetadataFile", fileBody);
    post.setEntity(entity);

    return post;
}

From source file:hu.sztaki.lpds.dcibridge.util.io.HttpHandler.java

public void write(String pURL, List<File> pValue) throws IOException {
    open(pURL);//  www .jav  a  2 s . c o  m
    MultipartEntity reqEntity = new MultipartEntity();
    for (File t : pValue) {
        FileBody bin = new FileBody(t);
        reqEntity.addPart(t.getName(), bin);
    }
    httpPost.setEntity(reqEntity);
    HttpResponse response = httpclient.execute(httpPost);
}

From source file:com.fly1tkg.streamfileupload.FileUploadFacade.java

public void post(final String url, final String fileKey, final File file, final String contentType,
        final Map<String, String> params, final FileUploadCallback callback) {

    if (null == callback) {
        throw new RuntimeException("FileUploadCallback should not be null.");
    }//from www.ja va  2s  . c o  m

    ExecutorService executorService = Executors.newCachedThreadPool();
    executorService.execute(new Runnable() {
        public void run() {
            try {
                HttpPost httpPost = new HttpPost(url);

                FileBody fileBody;
                if (null == contentType) {
                    fileBody = new FileBody(file);
                } else {
                    fileBody = new FileBody(file, contentType);
                }

                MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                if (null == fileKey) {
                    entity.addPart(DEFAULT_FILE_KEY, fileBody);
                } else {
                    entity.addPart(fileKey, fileBody);
                }

                if (null != params) {
                    for (Map.Entry<String, String> e : params.entrySet()) {
                        entity.addPart(e.getKey(), new StringBody(e.getValue()));
                    }
                }

                httpPost.setEntity(entity);

                upload(httpPost, callback);
            } catch (UnsupportedEncodingException e) {
                callback.onFailure(-1, null, e);
            }
        }
    });
}

From source file:com.ibm.watson.developer_cloud.visual_recognition.v1.VisualRecognition.java

/**
 * Classifies the images against the label groups and labels. The response
 * includes a score for a label if the score meets the minimum threshold of
 * 0.5. If no score meets the threshold for an image, no labels are
 * returned.//from  w w  w. ja v a  2s .co m
 * 
 * @param image
 *            the file image
 * @param labelSet
 *            the labels to classify against
 * @return the visual recognition images
 */
public RecognizedImage recognize(final File image, final LabelSet labelSet) {
    if (image == null)
        throw new IllegalArgumentException("image can not be null");
    try {

        Request request = Request.Post("/v1/tag/recognize");

        MultipartEntity reqEntity = new MultipartEntity();

        // Set the image_file
        FileBody bin = new FileBody(image);
        reqEntity.addPart(IMG_FILE, bin);

        if (labelSet != null) {
            StringBody labels = new StringBody(GsonSingleton.getGson().toJson(labelSet),
                    Charset.forName("UTF-8"));

            // Set the labels_to_check
            reqEntity.addPart(LABELS_TO_CHECK, labels);
        }
        request.withEntity(reqEntity);

        HttpResponse response = execute(request.build());
        String resultJson = ResponseUtil.getString(response);
        VisualRecognitionImages recognizedImages = GsonSingleton.getGson().fromJson(resultJson,
                VisualRecognitionImages.class);
        return recognizedImages.getImages().get(0);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.wso2.carbon.appmanager.integration.ui.Util.Bean.DocumentRequest.java

@Override
public void init() {
    addParameter("mode", new StringBody(mode, ContentType.TEXT_PLAIN));
    addParameter("docUrl", new StringBody(docUrl, ContentType.TEXT_PLAIN));
    addParameter("sourceType", new StringBody(sourceType, ContentType.TEXT_PLAIN));
    addParameter("summary", new StringBody(summary, ContentType.TEXT_PLAIN));
    addParameter("docType", new StringBody(docType, ContentType.TEXT_PLAIN));
    addParameter("docName", new StringBody(docName, ContentType.TEXT_PLAIN));
    addParameter("version", new StringBody(version, ContentType.TEXT_PLAIN));
    addParameter("apiName", new StringBody(apiName, ContentType.TEXT_PLAIN));
    addParameter("action", new StringBody(action, ContentType.TEXT_PLAIN));
    addParameter("provider", new StringBody(provider, ContentType.TEXT_PLAIN));
    addParameter("optionsRadios", new StringBody(optionsRadios, ContentType.TEXT_PLAIN));
    addParameter("optionsRadios1", new StringBody(optionsRadios1, ContentType.TEXT_PLAIN));
    if ("other".equalsIgnoreCase(docType)) {
        addParameter("newType", new StringBody(newType, ContentType.TEXT_PLAIN));
    }//ww w. ja v a 2 s.com
    if ("file".equalsIgnoreCase(sourceType)) {
        FileBody bin = new FileBody(new File(docLocation));
        addParameter("docLocation", bin);
    }
}