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, final String mimeType) 

Source Link

Usage

From source file:at.univie.sensorium.extinterfaces.HTTPSUploader.java

private String uploadFiles(List<File> files) {
    String result = "";
    try {//from  w w w . j a v  a  2  s  .c  om

        if (URLUtil.isValidUrl(posturl)) {
            HttpClient httpclient = getNewHttpClient();

            HttpPost httppost = new HttpPost(posturl);
            MultipartEntity mpEntity = new MultipartEntity();
            //            MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

            mpEntity.addPart("username", new StringBody(username));
            mpEntity.addPart("password", new StringBody(password));
            for (File file : files) {
                Log.d(SensorRegistry.TAG, "preparing " + file.getName() + " for upload");
                ContentBody cbFile = new FileBody(file, "application/json");
                mpEntity.addPart(file.toString(), cbFile);
            }
            httppost.addHeader("username", username);
            httppost.addHeader("password", password);
            httppost.setEntity(mpEntity);
            HttpResponse response = httpclient.execute(httppost);

            String reply;
            InputStream in = response.getEntity().getContent();

            StringBuilder sb = new StringBuilder();
            try {
                int chr;
                while ((chr = in.read()) != -1) {
                    sb.append((char) chr);
                }
                reply = sb.toString();
            } finally {
                in.close();
            }
            result = response.getStatusLine().toString();
            Log.d(SensorRegistry.TAG, "Http upload completed with response: " + result + " " + reply);

        } else {
            result = "URL invalid";
            Log.d(SensorRegistry.TAG, "Invalid http upload url, aborting.");
        }
    } catch (IllegalArgumentException e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        Log.d(SensorRegistry.TAG, sw.toString());
    } catch (FileNotFoundException e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        Log.d(SensorRegistry.TAG, sw.toString());
    } catch (ClientProtocolException e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        Log.d(SensorRegistry.TAG, sw.toString());
    } catch (IOException e) {
        result = "upload failed due to timeout";
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        Log.d(SensorRegistry.TAG, sw.toString());
    }
    return result;
}

From source file:com.ibm.watson.developer_cloud.document_conversion.v1.helpers.ConvertDocumentHelper.java

/**
 * Synchronously converts a new document without persistence
 * POST /v1/convert_document./* ww w .jav  a 2  s .c o m*/
 *
 * @param document The file to convert
 * @param mediaType Internet media type for the file
 * @param conversionTarget The conversion target to use
 * @return Converted document in the specified format
 * @see DocumentConversion#convertDocument(File, String, ConversionTarget)
 */
public InputStream convertDocument(final File document, String mediaType,
        final ConversionTarget conversionTarget) {
    if (mediaType == null || mediaType.isEmpty())
        throw new IllegalArgumentException("media type cannot be null or empty");
    if (!ConversionUtils.isValidMediaType(mediaType))
        throw new IllegalArgumentException("file with the given media type is not supported");
    if (document == null || !document.exists())
        throw new IllegalArgumentException("document can not be null and must exist");
    if (conversionTarget == null)
        throw new IllegalArgumentException("conversion target can not be null");

    try {
        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("file", new FileBody(document, mediaType));
        JsonObject configRequestJson = new JsonObject();
        configRequestJson.addProperty("conversion_target", conversionTarget.toString());
        String json = configRequestJson.toString();
        reqEntity.addPart("config", new StringBody(json, MediaType.APPLICATION_JSON, Charset.forName("UTF-8")));

        HttpRequestBase request = Request.Post(ConfigConstants.CONVERT_DOCUMENT_PATH).withEntity(reqEntity)
                .build();

        HttpResponse response = docConversionService.execute(request);
        InputStream is = ResponseUtil.getInputStream(response);
        return is;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:ee.ioc.phon.netspeechapi.AudioUploader.java

public MultipartEntity createMultipartEntity(File file, String mimeType, int sampleRate) {
    return createMultipartEntity(new FileBody(file, mimeType), mimeType, sampleRate);
}

From source file:com.ibm.streamsx.topology.internal.streaminganalytics.RestUtils.java

/**
 * Submit an application bundle to execute as a job.
 *///from   www  .ja v a 2  s  .c  o  m
public static JsonObject postJob(CloseableHttpClient httpClient, JsonObject service, File bundle,
        JsonObject jobConfigOverlay) throws ClientProtocolException, IOException {

    final String serviceName = jstring(service, "name");
    final JsonObject credentials = service.getAsJsonObject("credentials");

    String url = getJobSubmitURL(credentials, bundle);

    HttpPost postJobWithConfig = new HttpPost(url);
    postJobWithConfig.addHeader("accept", ContentType.APPLICATION_JSON.getMimeType());
    postJobWithConfig.addHeader(AUTH.WWW_AUTH_RESP, getAPIKey(credentials));
    FileBody bundleBody = new FileBody(bundle, ContentType.APPLICATION_OCTET_STREAM);
    StringBody configBody = new StringBody(jobConfigOverlay.toString(), ContentType.APPLICATION_JSON);

    HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("sab", bundleBody)
            .addPart(DeployKeys.JOB_CONFIG_OVERLAYS, configBody).build();

    postJobWithConfig.setEntity(reqEntity);

    JsonObject jsonResponse = getGsonResponse(httpClient, postJobWithConfig);

    RemoteContext.REMOTE_LOGGER.info("Streaming Analytics service (" + serviceName + "): submit job response:"
            + jsonResponse.toString());

    return jsonResponse;
}

From source file:eu.nubomedia.nubomedia_kurento_health_communicator_android.kc_and_communicator.services.CommandService.java

private static HttpResp<Void> sendCommandWithMedia(final Context ctx, CommandObject cmd)
        throws KurentoCommandException, TransportException, InvalidDataException, NotFoundException {
    String contentPath = cmd.getMedia();

    File content = new File(contentPath);
    String mimeType;// www . j  a  va 2  s.  co m
    if (content.exists() && content.isFile()) {
        if (contentPath.contains(ConstantKeys.EXTENSION_JPG)) {
            mimeType = ConstantKeys.TYPE_IMAGE;
        } else {
            mimeType = ConstantKeys.TYPE_VIDEO;
        }
    } else {
        String error = contentPath + " does not exists or is not a file";
        log.error(error);
        throw new KurentoCommandException(error);
    }

    CustomMultiPartEntity mpEntity;
    final String json = cmd.getJson();
    String charset = HTTP.UTF_8;
    long contentSize = 0;
    try {
        contentSize = content.length();
        /* Aprox. total size */
        final long totalSize = content.length() + json.getBytes("UTF-16BE").length;
        mpEntity = new CustomMultiPartEntity(new CustomMultiPartEntity.ProgressListener() {

            private int i;

            @Override
            public void transferred(long num) {
                int totalpercent = Math.min(100, (int) ((num * 100) / totalSize));

                if (totalpercent > (1 + PERCENT_INC * i) || totalpercent >= 100) {
                    Intent intent = new Intent();
                    intent.setAction(ConstantKeys.BROADCAST_PROGRESSBAR);
                    intent.putExtra(ConstantKeys.JSON, json);
                    intent.putExtra(ConstantKeys.TOTAL, totalpercent);
                    ctx.sendBroadcast(intent);
                    i++;
                }
            }
        });

        mpEntity.addPart(COMMAND_PART_NAME,
                new StringBody(json, HttpManager.CONTENT_TYPE_APPLICATION_JSON, Charset.forName(charset)));

        FormBodyPart fbp = new FormBodyPart(CONTENT_PART_NAME, new FileBody(content, mimeType));
        fbp.addField(HTTP.CONTENT_LEN, String.valueOf(contentSize));
        mpEntity.addPart(fbp);

    } catch (UnsupportedEncodingException e) {
        String msg = "Cannot use " + charset + "as entity";
        log.error(msg, e);
        throw new TransportException(msg);
    }

    return HttpManager.sendPostVoid(ctx, ctx.getString(R.string.url_command), mpEntity);
}

From source file:packjacket.StaticUtils.java

/**
 * Uploads a file to the PackJacket webserver
 * @param f the fiel to upload/*from w w w. ja va2s.c  om*/
 * @return the id of the log file, or 0 if it crashed
 */
public static long uploadLog(File f) {
    long id = 0;
    try {
        //Sets up the HTTP interaction
        HttpClient httpclient = new DefaultHttpClient();
        httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        HttpPost httppost = new HttpPost("http://packjacket.sourceforge.net/log/up.php");

        //Adds file to a POST
        MultipartEntity mpEntity = new MultipartEntity();
        ContentBody cbFile = new FileBody(f, "image/jpeg");
        mpEntity.addPart("uploadedfile", cbFile);

        //Uplaods file
        httppost.setEntity(mpEntity);
        RunnerClass.logger.info("executing request " + httppost.getRequestLine());
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();

        //Receives the status message
        RunnerClass.logger.info("Status: " + response.getStatusLine());
        if (resEntity != null) {
            //Get the id that the server reports
            String s = EntityUtils.toString(resEntity);
            RunnerClass.logger.info("Result: " + s);
            id = Long.parseLong(s.replaceFirst("222 ", "").replace("\n", ""));
        }
        if (resEntity != null)
            resEntity.consumeContent();

        //Close connection
        httpclient.getConnectionManager().shutdown();
    } catch (Exception ex) {
        RunnerClass.logger.info("Internet not available");
    }
    return id;
}

From source file:org.trpr.platform.batch.impl.job.ha.service.SyncServiceImpl.java

/**
 * Interface Method Implementation//from ww  w  .j a v a 2 s  .  com
 * @see SyncService#pushJobToHost(String, String)
 */
public boolean pushJobToHost(String jobName, String serverName) {
    serverName = SyncServiceImpl.PROTOCOL + serverName + SynchronizationController.PUSH_URL;

    HttpPost postRequest = new HttpPost(serverName);
    try {
        MultipartEntity multiPartEntity = new MultipartEntity();
        multiPartEntity.addPart("jobName", new StringBody(jobName));

        FileBody fileBody = new FileBody(this.jobConfigService.getJobConfig(jobName).getFile(),
                "application/octect-stream");
        multiPartEntity.addPart("jobConfig", fileBody);

        if (this.jobConfigService.getJobDependencyList(jobName) != null) {
            for (String dependency : this.jobConfigService.getJobDependencyList(jobName)) {
                File depFile = new File(
                        this.jobConfigService.getJobStoreURI(jobName).getPath() + "/lib/" + dependency);
                FileBody depFileBody = new FileBody(depFile);
                multiPartEntity.addPart("depFiles[]", depFileBody);
            }
        }
        postRequest.setEntity(multiPartEntity);
    } catch (UnsupportedEncodingException ex) {
        LOGGER.error("Error while forming multiPart request", ex);
    } catch (IOException e) {
        LOGGER.error("Error while forming multiPart request", e);
    }
    String retValue = org.trpr.platform.batch.impl.job.ha.service.FileUpload.executeRequest(postRequest);
    LOGGER.info("Server returns: " + retValue.trim());
    if (retValue.trim().equalsIgnoreCase(SyncServiceImpl.SUCCESS_STRING)) {
        return true;
    }
    return false;
}

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);//from w ww  .j  a v a  2  s .  c om
    post.setEntity(entity);

    return client.execute(post);
}

From source file:functionaltests.RestSchedulerJobTaskTest.java

@Test
public void testSubmit() throws Exception {
    String schedulerUrl = getResourceUrl("submit");
    HttpPost httpPost = new HttpPost(schedulerUrl);
    setSessionHeader(httpPost);/*  w ww.j a  v a2 s  .  c  om*/
    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);
    JSONObject jsonObj = toJsonObject(response);
    assertNotNull(jsonObj.get("id").toString());
}

From source file:nl.phanos.liteliveresultsclient.LoginHandler.java

public void submitResults(ArrayList<ParFile> files) throws Exception {
    String url = "https://www.atletiek.nu/feeder.php?page=resultateninvoer&do=uploadresultaat&event_id=" + nuid
            + "";
    System.out.println(url);//from  w w w  .  jav a 2 s  .com
    for (int i = 0; i < files.size(); i++) {
        HttpPost post = new HttpPost(url);

        post.setHeader("User-Agent", USER_AGENT);
        post.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        post.setHeader("Accept-Language", "en-US,en;q=0.5");
        post.setHeader("Cookie", getCookies());
        MultipartEntity mpEntity = new MultipartEntity();
        System.out.println("files:" + files.size());

        File file = files.get(i).resultFile;
        ContentBody cbFile = new FileBody(file, "text/plain");
        mpEntity.addPart("files", cbFile);
        System.out.println("added file to upload");

        post.setEntity(mpEntity);

        HttpResponse response = client.execute(post);
        int responseCode = response.getStatusLine().getStatusCode();

        System.out.println("Response Code submit: " + responseCode);
        HttpEntity responseEntity = response.getEntity();
        String responseString = "";
        if (responseEntity != null) {
            responseString = EntityUtils.toString(responseEntity);
        }
        JSONObject obj = null;
        try {
            obj = new JSONObject(responseString);
            System.out.println("succes:" + responseString);
        } catch (Exception e) {
            System.out.println("error:" + responseString);
        }
        if (obj != null) {
            for (Object FileObj : (JSONArray) obj.get("files")) {
                JSONObject JSONFile = (JSONObject) FileObj;
                files.get(i).uploadDate = Calendar.getInstance().getTimeInMillis();
                files.get(i).UploadedAtleten = "" + (Integer) JSONFile.get("totaalverwerkt");
                AtletiekNuPanel.panel.addText("Uploaded " + JSONFile.get("name") + " met "
                        + JSONFile.get("totaalverwerkt") + " atleten");
            }
        }
        // set cookies
        setCookies(response.getFirstHeader("Set-Cookie") == null ? ""
                : response.getFirstHeader("Set-Cookie").toString());
        post.releaseConnection();
    }
    //getZip(nuid);
}