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.wso2.am.integration.tests.other.InvalidAuthTokenLargePayloadTestCase.java

/**
 * Upload a file to the given URL//from  ww w  . jav a 2 s  .  co m
 *
 * @param endpointUrl URL to be file upload
 * @param fileName    Name of the file to be upload
 * @throws IOException throws if connection issues occurred
 */
private HttpResponse uploadFile(String endpointUrl, File fileName, Map<String, String> headers)
        throws IOException {
    //open import API url connection and deploy the exported API
    URL url = new URL(endpointUrl);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");

    FileBody fileBody = new FileBody(fileName);
    MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT);
    multipartEntity.addPart("file", fileBody);

    connection.setRequestProperty("Content-Type", multipartEntity.getContentType().getValue());
    //setting headers
    if (headers != null && headers.size() > 0) {
        Iterator<String> itr = headers.keySet().iterator();
        while (itr.hasNext()) {
            String key = itr.next();
            if (key != null) {
                connection.setRequestProperty(key, headers.get(key));
            }
        }
        for (String key : headers.keySet()) {
            connection.setRequestProperty(key, headers.get(key));
        }
    }

    OutputStream out = connection.getOutputStream();
    try {
        multipartEntity.writeTo(out);
    } finally {
        out.close();
    }
    int status = connection.getResponseCode();
    BufferedReader read = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String temp;
    StringBuilder responseMsg = new StringBuilder();
    while ((temp = read.readLine()) != null) {
        responseMsg.append(temp);
    }
    HttpResponse response = new HttpResponse(responseMsg.toString(), status);
    return response;
}

From source file:com.ushahidi.android.app.net.MainHttpClient.java

/**
 * Upload files to server 0 - success, 1 - missing parameter, 2 - invalid
 * parameter, 3 - post failed, 5 - access denied, 6 - access limited, 7 - no
 * data, 8 - api disabled, 9 - no task found, 10 - json is wrong
 *//*from   w  w  w  .j a  va  2  s  .  co  m*/
public static int PostFileUpload(String URL, HashMap<String, String> params) throws IOException {
    Log.d(CLASS_TAG, "PostFileUpload(): upload file to server.");

    entity = new MultipartEntity();
    // Dipo Fix
    try {
        // wrap try around because this constructor can throw Error
        final HttpPost httpost = new HttpPost(URL);

        if (params != null) {

            entity.addPart("task", new StringBody(params.get("task")));
            entity.addPart("incident_title",
                    new StringBody(params.get("incident_title"), Charset.forName("UTF-8")));
            entity.addPart("incident_description",
                    new StringBody(params.get("incident_description"), Charset.forName("UTF-8")));
            entity.addPart("incident_date", new StringBody(params.get("incident_date")));
            entity.addPart("incident_hour", new StringBody(params.get("incident_hour")));
            entity.addPart("incident_minute", new StringBody(params.get("incident_minute")));
            entity.addPart("incident_ampm", new StringBody(params.get("incident_ampm")));
            entity.addPart("incident_category", new StringBody(params.get("incident_category")));
            entity.addPart("latitude", new StringBody(params.get("latitude")));
            entity.addPart("longitude", new StringBody(params.get("longitude")));
            entity.addPart("location_name",
                    new StringBody(params.get("location_name"), Charset.forName("UTF-8")));
            entity.addPart("person_first",
                    new StringBody(params.get("person_first"), Charset.forName("UTF-8")));
            entity.addPart("person_last", new StringBody(params.get("person_last"), Charset.forName("UTF-8")));
            entity.addPart("person_email",
                    new StringBody(params.get("person_email"), Charset.forName("UTF-8")));

            if (!TextUtils.isEmpty(params.get("filename"))) {
                File file = new File(params.get("filename"));
                if (file.exists()) {
                    entity.addPart("incident_photo[]", new FileBody(new File(params.get("filename"))));
                }
            }

            // NEED THIS NOW TO FIX ERROR 417
            httpost.getParams().setBooleanParameter("http.protocol.expect-continue", false);
            httpost.setEntity(entity);

            HttpResponse response = httpClient.execute(httpost);
            Preferences.httpRunning = false;

            HttpEntity respEntity = response.getEntity();
            if (respEntity != null) {
                InputStream serverInput = respEntity.getContent();
                return Util.extractPayloadJSON(GetText(serverInput));

            }
        }

    } catch (MalformedURLException ex) {
        Log.d(CLASS_TAG, "PostFileUpload(): MalformedURLException");
        ex.printStackTrace();
        return 11;
        // fall through and return false
    } catch (IllegalArgumentException ex) {
        Log.e(CLASS_TAG, ex.toString());
        //invalid URI
        return 12;
    } catch (IOException e) {
        Log.e(CLASS_TAG, e.toString());
        //timeout
        return 13;
    }
    return 10;
}

From source file:com.devbliss.doctest.LogicDocTest.java

protected ApiResponse makePostUploadRequest(URI uri, File fileToUpload, String paramName,
        Map<String, String> additionalHeaders) throws Exception {
    FileBody fileBodyToUpload = new FileBody(fileToUpload);
    String mimeType = new MimetypesFileTypeMap().getContentType(fileToUpload);

    Context context = apiTest.post(uri, null, new PostUploadWithoutRedirectImpl(paramName, fileBodyToUpload),
            additionalHeaders);/*from  w w w .  j  a  v a2 s. c  o m*/

    docTestMachine.sayUploadRequest(context.apiRequest, fileBodyToUpload.getFilename(),
            fileHelper.readFile(fileToUpload), fileToUpload.length(), mimeType, headersToShow, cookiesToShow);

    docTestMachine.sayResponse(context.apiResponse, headersToShow);

    return context.apiResponse;
}

From source file:org.xmetdb.rest.protocol.attachments.CallableAttachmentImporter.java

protected HttpEntity createPOSTEntity(DBAttachment attachment) throws Exception {
    Charset utf8 = Charset.forName("UTF-8");

    if ("text/uri-list".equals(attachment.getFormat())) {
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new BasicNameValuePair("title", attachment.getTitle()));
        formparams.add(new BasicNameValuePair("dataset_uri", attachment.getDescription()));
        formparams.add(new BasicNameValuePair("folder",
                attachment_type.substrate.equals(attachment.getType()) ? "substrate" : "product"));
        return new UrlEncodedFormEntity(formparams, "UTF-8");
    } else {/*from w  w w  .  j av a2s .c o m*/
        if (attachment.getResourceURL() == null)
            throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Attachment resource URL is null! ");
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, utf8);
        entity.addPart("title", new StringBody(attachment.getTitle(), utf8));
        entity.addPart("seeAlso", new StringBody(attachment.getDescription(), utf8));
        entity.addPart("license", new StringBody("XMETDB", utf8));
        entity.addPart("file", new FileBody(new File(attachment.getResourceURL().toURI())));
        return entity;
    }
    //match, seeAlso, license
}

From source file:net.fluidnexus.FluidNexusAndroid.services.NexusServiceThread.java

/**
 * Start the listeners for zeroconf services
 *//*from www  .  j  a  v  a2  s .  c  om*/
public void doStateNone() {
    if (wifiManager.getWifiState() == wifiManager.WIFI_STATE_ENABLED) {
        Cursor c = messagesProviderHelper.publicMessages();

        while (c.isAfterLast() == false) {
            String message_hash = c.getString(c.getColumnIndex(MessagesProviderHelper.KEY_MESSAGE_HASH));
            boolean result = checkHash(message_hash);

            if (!result) {
                try {
                    JSONObject message = new JSONObject();
                    message.put("message_title",
                            c.getString(c.getColumnIndex(MessagesProviderHelper.KEY_TITLE)));
                    message.put("message_content",
                            c.getString(c.getColumnIndex(MessagesProviderHelper.KEY_CONTENT)));
                    message.put("message_hash",
                            c.getString(c.getColumnIndex(MessagesProviderHelper.KEY_MESSAGE_HASH)));
                    message.put("message_type", c.getInt(c.getColumnIndex(MessagesProviderHelper.KEY_TYPE)));
                    message.put("message_time", c.getFloat(c.getColumnIndex(MessagesProviderHelper.KEY_TIME)));
                    message.put("message_received_time",
                            c.getFloat(c.getColumnIndex(MessagesProviderHelper.KEY_RECEIVED_TIME)));
                    message.put("message_priority",
                            c.getInt(c.getColumnIndex(MessagesProviderHelper.KEY_PRIORITY)));

                    String attachment_path = c
                            .getString(c.getColumnIndex(MessagesProviderHelper.KEY_ATTACHMENT_PATH));

                    //String serializedMessage = message.toString();

                    // First, get our nonce
                    consumer = new CommonsHttpOAuthConsumer(key, secret);
                    consumer.setTokenWithSecret(token, token_secret);
                    HttpPost nonce_request = new HttpPost(NEXUS_NONCE_URL);
                    consumer.sign(nonce_request);
                    HttpClient client = new DefaultHttpClient();
                    String response = client.execute(nonce_request, new BasicResponseHandler());
                    JSONObject object = new JSONObject(response);
                    String nonce = object.getString("nonce");

                    // Then, take our nonce and key and put them in the message
                    message.put("message_nonce", nonce);
                    message.put("message_key", key);

                    // Setup our multipart entity
                    MultipartEntity entity = new MultipartEntity();

                    // Deal with file attachment
                    if (!attachment_path.equals("")) {
                        File file = new File(attachment_path);
                        ContentBody cbFile = new FileBody(file);
                        entity.addPart("message_attachment", cbFile);

                        // add the original filename to the message
                        message.put("message_attachment_original_filename", c.getString(
                                c.getColumnIndex(MessagesProviderHelper.KEY_ATTACHMENT_ORIGINAL_FILENAME)));
                    }

                    String serializedMessage = message.toString();
                    ContentBody messageBody = new StringBody(serializedMessage);
                    entity.addPart("message", messageBody);

                    HttpPost message_request = new HttpPost(NEXUS_MESSAGE_URL);
                    message_request.setEntity(entity);

                    client = new DefaultHttpClient();
                    client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

                    response = client.execute(message_request, new BasicResponseHandler());
                    object = new JSONObject(response);
                    boolean message_result = object.getBoolean("result");

                    if (message_result) {
                        ContentValues values = new ContentValues();
                        values.put(MessagesProviderHelper.KEY_MESSAGE_HASH, message_hash);
                        values.put(MessagesProviderHelper.KEY_UPLOADED, 1);
                        int res = messagesProviderHelper
                                .setPublic(c.getLong(c.getColumnIndex(MessagesProviderHelper.KEY_ID)), values);
                        if (res == 0) {
                            log.debug("Message with hash " + message_hash
                                    + " not found; this should never happen!");
                        }
                    }

                } catch (OAuthMessageSignerException e) {
                    log.debug("OAuthMessageSignerException: " + e);
                } catch (OAuthExpectationFailedException e) {
                    log.debug("OAuthExpectationFailedException: " + e);
                } catch (OAuthCommunicationException e) {
                    log.debug("OAuthCommunicationException: " + e);
                } catch (JSONException e) {
                    log.debug("JSON Error: " + e);
                } catch (IOException e) {
                    log.debug("IOException: " + e);
                }
            }
            c.moveToNext();
        }

        c.close();

    }

    setServiceState(STATE_SERVICE_WAIT);
}

From source file:de.tu_dortmund.ub.data.dswarm.Ingest.java

/**
 * upload a file and update an existing resource with it
 *
 * @param resourceUUID/* www.ja va  2 s .com*/
 * @param filename
 * @param name
 * @param description
 * @return responseJson
 * @throws Exception
 */
private String uploadFileAndUpdateResource(final String resourceUUID, final String filename, final String name,
        final String description, final String serviceName, final String engineDswarmAPI) throws Exception {

    if (null == resourceUUID)
        throw new Exception("ID of the resource to update was null.");

    final String resourceWatchFolder = config.getProperty(TPUStatics.RESOURCE_WATCHFOLDER_IDENTIFIER);
    final String completeFileName = resourceWatchFolder + File.separatorChar + filename;

    try (final CloseableHttpClient httpclient = HttpClients.createDefault()) {

        final HttpPut httpPut = new HttpPut(
                engineDswarmAPI + DswarmBackendStatics.RESOURCES_ENDPOINT + APIStatics.SLASH + resourceUUID);

        final File file1 = new File(completeFileName);
        final FileBody fileBody = new FileBody(file1);
        final StringBody stringBodyForName = new StringBody(name, ContentType.TEXT_PLAIN);
        final StringBody stringBodyForDescription = new StringBody(description, ContentType.TEXT_PLAIN);

        final HttpEntity reqEntity = MultipartEntityBuilder.create()
                .addPart(DswarmBackendStatics.NAME_IDENTIFIER, stringBodyForName)
                .addPart(DswarmBackendStatics.DESCRIPTION_IDENTIFIER, stringBodyForDescription)
                .addPart(FILE_IDENTIFIER, fileBody).build();

        httpPut.setEntity(reqEntity);

        LOG.info(String.format("[%s] request : %s", serviceName, httpPut.getRequestLine()));

        try (final CloseableHttpResponse httpResponse = httpclient.execute(httpPut)) {

            final int statusCode = httpResponse.getStatusLine().getStatusCode();

            final String message = String.format("[%s] %d : %s", serviceName, statusCode,
                    httpResponse.getStatusLine().getReasonPhrase());

            final String response = TPUUtil.getResponseMessage(httpResponse);

            switch (statusCode) {

            case 200: {

                LOG.info(message);

                LOG.debug(String.format("[%s] responseJson : %s", serviceName, response));

                return response;
            }
            default: {

                LOG.error(message);

                throw new Exception("something went wrong at data model export: " + message + " " + response);
            }
            }
        }
    }
}

From source file:org.syncany.plugins.php.PhpTransferManager.java

@Override
public void upload(File localFile, RemoteFile remoteFile) throws StorageException {
    logger.info("Uploading: " + localFile.getName() + " to " + remoteFile.getName());
    try {//w ww.  ja v  a  2s . c  o m
        final String remote_name = remoteFile.getName();
        final File f = localFile;
        int r = operate("upload", new IPost() {
            List<NameValuePair> _nvps;

            public void mutateNVPS(List<NameValuePair> nvps) throws Exception {
                _nvps = nvps;
                nvps.add(new BasicNameValuePair("filename", remote_name));
            }

            public int mutatePost(HttpPost p) throws Exception {
                MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
                builder.addPart("file", new FileBody(f));
                Iterator<NameValuePair> it = _nvps.iterator();
                while (it.hasNext()) {
                    NameValuePair nvp = it.next();
                    builder.addTextBody(nvp.getName(), nvp.getValue());
                }
                p.setEntity(builder.build());
                return -1;
            }

            @Override
            public int consumeResponse(InputStream s) throws Exception {
                String response = getAnswer(s);
                if (response.equals("true")) {
                    return 1;
                } else {
                    throw new Exception(response);
                }
            }

        });
        if (r != 1) {
            throw new Exception("Unexpected error, result code = " + r);
        }

    } catch (Exception e) {
        throw new StorageException("Cannot upload file " + remoteFile, e);
    }
}

From source file:com.code42.demo.RestInvoker.java

/**
 * Execuites CODE42 api/File to upload a single file into the root directory of the specified planUid
 * If the file is succesfully uploaded the response code of 204 is returned.
 * /* ww w  .j  a  v a 2 s.c o m*/
 * @param planUid 
 * @param sessionId
 * @param file
 * @return HTTP Response code as int
 * @throws Exception
 */

public int postFileAPI(String planUid, String sessionId, File file) throws Exception {

    int respCode;
    HttpClientBuilder hcs;
    CloseableHttpClient httpClient;
    hcs = HttpClients.custom().setDefaultCredentialsProvider(credsProvider);
    if (ssl) {
        hcs.setSSLSocketFactory(sslsf);
    }
    httpClient = hcs.build();
    StringBody planId = new StringBody(planUid, ContentType.TEXT_PLAIN);
    StringBody sId = new StringBody(sessionId, ContentType.TEXT_PLAIN);

    try {
        HttpPost httpPost = new HttpPost(ePoint + "/api/File");
        FileBody fb = new FileBody(file);
        HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("file", fb).addPart("planUid", planId)
                .addPart("sessionId", sId).build();
        httpPost.setEntity(reqEntity);
        CloseableHttpResponse resp = httpClient.execute(httpPost);
        try {
            m_log.info("executing " + httpPost.getRequestLine());
            m_log.info(resp.getStatusLine());
            respCode = resp.getStatusLine().getStatusCode();
        } finally {
            resp.close();
        }

    } finally {
        httpClient.close();
    }

    return respCode;
}

From source file:com.google.cloud.solutions.smashpix.MainActivity.java

  /**
 * Uploads the image to Google Cloud Storage.
 */// w w w. ja  v  a  2s  .  c  o  m
public Boolean uploadToCloudStorage(ServicesStorageSignedUrlResponse signedUrlParams,
  File localImageStoragePath){
  if (!signedUrlParams.isEmpty() && localImageStoragePath.exists())  {
    FileBody binary = new FileBody(localImageStoragePath);
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(signedUrlParams.getFormAction());
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    try {
      entity.addPart("bucket", new StringBody(signedUrlParams.getBucket()));
      entity.addPart("key", new StringBody(signedUrlParams.getFilename()));
      entity.addPart("policy", new StringBody(signedUrlParams.getPolicy()));
      entity.addPart("signature", new StringBody(signedUrlParams.getSignature()));
      entity.addPart("x-goog-meta-owner", new StringBody(accountName));
      entity.addPart("GoogleAccessId", new StringBody(signedUrlParams.getGoogleAccessId()));
      entity.addPart("file", binary);
    } catch (UnsupportedEncodingException e) {
      Log.e(Constants.APP_NAME, e.getMessage());
      return false;
    }

    httpPost.setEntity(entity);
    HttpResponse httpResponse;
    try {
      httpResponse = httpClient.execute(httpPost);
      if (httpResponse.getStatusLine().getStatusCode() == 204) {
        Log.i(Constants.APP_NAME, "Image Uploaded");
        return true;
      }
    } catch (ClientProtocolException e) {
        Log.e(Constants.APP_NAME, e.getMessage());
    } catch (IOException e) {
        Log.e(Constants.APP_NAME, e.getMessage());
    }
  }
  Log.e(Constants.APP_NAME, "Image Upload Failed");
  return false;
}