List of usage examples for org.apache.http.entity.mime.content FileBody FileBody
public FileBody(final File file)
From source file:com.brightcove.com.uploader.helper.MediaAPIHelper.java
/** * Executes a file upload write api call against the given URI. * This is useful for create_video and add_image * @param json the json representation of the call you are making * @param file the file you are uploading * @param uri the api servlet you want to execute against * @return json response from api/* www .j a v a 2 s. com*/ * @throws BadEnvironmentException * @throws MediaAPIError */ public JsonNode executeWrite(JsonNode json, File file, URI uri) throws BadEnvironmentException, MediaAPIError { mLog.debug("using " + uri.getHost() + " on port " + uri.getPort() + " for api write"); HttpPost method = new HttpPost(uri); MultipartEntity entityIn = new MultipartEntity(); FileBody fileBody = null; if (file != null) { fileBody = new FileBody(file); } try { entityIn.addPart("JSON-RPC", new StringBody(json.toString(), Charset.forName("UTF-8"))); } catch (UnsupportedEncodingException e) { throw new BadEnvironmentException("UTF-8 no longer supported"); } if (file != null) { entityIn.addPart(file.getName(), fileBody); } method.setEntity(entityIn); return executeCall(method); }
From source file:com.brightcove.zartan.common.helper.MediaAPIHelper.java
/** * Executes a file upload write api call against the given URI. This is useful for create_video * and add_image/* w ww .j av a2 s. co m*/ * * @param json the json representation of the call you are making * @param file the file you are uploading * @param uri the api servlet you want to execute against * @return json response from api * @throws BadEnvironmentException * @throws MediaAPIException */ public JsonNode executeWrite(JsonNode json, File file, URI uri) throws BadEnvironmentException, MediaAPIException { mLog.debug("using " + uri.getHost() + " on port " + uri.getPort() + " for api write"); HttpPost method = new HttpPost(uri); MultipartEntity entityIn = new MultipartEntity(); FileBody fileBody = null; if (file != null) { fileBody = new FileBody(file); } try { entityIn.addPart("JSON-RPC", new StringBody(json.toString(), Charset.forName("UTF-8"))); } catch (UnsupportedEncodingException e) { throw new BadEnvironmentException("UTF-8 no longer supported"); } if (file != null) { entityIn.addPart(file.getName(), fileBody); } method.setEntity(entityIn); return executeCall(method); }
From source file:org.apache.syncope.installer.utilities.HttpUtils.java
public String postWithDigestAuth(final String url, final String file) { String responseBodyAsString = ""; try (CloseableHttpResponse response = httpClient.execute(targetHost, httpPost(url, MultipartEntityBuilder.create().addPart("bin", new FileBody(new File(file))).build()), setAuth(targetHost, new DigestScheme()))) { responseBodyAsString = IOUtils.toString(response.getEntity().getContent(), Charset.forName("UTF-8")); handler.logOutput("Http status: " + response.getStatusLine().getStatusCode(), true); InstallLog.getInstance().info("Http status: " + response.getStatusLine().getStatusCode()); } catch (IOException e) { final String messageError = "Error calling " + url + ": " + e.getMessage(); handler.emitError(messageError, messageError); InstallLog.getInstance().error(messageError); }//from w w w .j a v a 2 s . c om return responseBodyAsString; }
From source file:com.piusvelte.sonet.core.PhotoUploadService.java
private void start(Intent intent) { if (intent != null) { String action = intent.getAction(); if (Sonet.ACTION_UPLOAD.equals(action)) { if (intent.hasExtra(Accounts.TOKEN) && intent.hasExtra(Statuses.MESSAGE) && intent.hasExtra(Widgets.INSTANT_UPLOAD)) { String place = null; if (intent.hasExtra(Splace)) place = intent.getStringExtra(Splace); String tags = null; if (intent.hasExtra(Stags)) tags = intent.getStringExtra(Stags); // upload a photo Notification notification = new Notification(R.drawable.notification, "uploading photo", System.currentTimeMillis()); notification.setLatestEventInfo(getBaseContext(), "photo upload", "uploading", PendingIntent.getActivity(PhotoUploadService.this, 0, (Sonet.getPackageIntent(PhotoUploadService.this, About.class)), 0)); ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(NOTIFY_ID, notification);/* w ww.j a v a2s . co m*/ (new AsyncTask<String, Void, String>() { @Override protected String doInBackground(String... params) { String response = null; if (params.length > 2) { Log.d(TAG, "upload file: " + params[2]); HttpPost httpPost = new HttpPost(String.format(FACEBOOK_PHOTOS, FACEBOOK_BASE_URL, Saccess_token, mSonetCrypto.Decrypt(params[0]))); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); File file = new File(params[2]); ContentBody fileBody = new FileBody(file); entity.addPart(Ssource, fileBody); HttpClient httpClient = SonetHttpClient .getThreadSafeClient(getApplicationContext()); try { entity.addPart(Smessage, new StringBody(params[1])); if (params[3] != null) entity.addPart(Splace, new StringBody(params[3])); if (params[4] != null) entity.addPart(Stags, new StringBody(params[4])); httpPost.setEntity(entity); response = SonetHttpClient.httpResponse(httpClient, httpPost); } catch (UnsupportedEncodingException e) { Log.e(TAG, e.toString()); } } return response; } @Override protected void onPostExecute(String response) { // notify photo success String message = getString(response != null ? R.string.success : R.string.failure); Notification notification = new Notification(R.drawable.notification, "photo upload " + message, System.currentTimeMillis()); notification.setLatestEventInfo(getBaseContext(), "photo upload", message, PendingIntent.getActivity(PhotoUploadService.this, 0, (Sonet.getPackageIntent(PhotoUploadService.this, About.class)), 0)); ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(NOTIFY_ID, notification); stopSelfResult(mStartId); } }).execute(intent.getStringExtra(Accounts.TOKEN), intent.getStringExtra(Statuses.MESSAGE), intent.getStringExtra(Widgets.INSTANT_UPLOAD), place, tags); } } } }
From source file:com.behance.sdk.asynctasks.BehanceSDKCreateProjectDraftAsyncTask.java
protected BehanceSDKAsyncTaskResultWrapper<String> doInBackground( BehanceSDKCreateProjectDraftTaskParams... paramVarArgs) { BehanceSDKAsyncTaskResultWrapper localBehanceSDKAsyncTaskResultWrapper = new BehanceSDKAsyncTaskResultWrapper(); Object localObject2 = paramVarArgs[0]; for (;;) {/*www . j ava 2 s .c om*/ try { paramVarArgs = new HashMap(1); paramVarArgs.put("clientId", ((BehanceSDKCreateProjectDraftTaskParams) localObject2).getClientId()); Object localObject1 = BehanceSDKUrlUtil.getUrlFromTemplate( "{server_root_url}/v2/project/editor?{key_client_id_param}={clientId}", paramVarArgs); Object localObject3 = BehanceSDKUserManager.getInstance().checkExpiryAndGetAccessToken(); paramVarArgs = (BehanceSDKCreateProjectDraftTaskParams[]) localObject1; if (localObject3 != null) { paramVarArgs = BehanceSDKUrlUtil.appendQueryStringParam((String) localObject1, "access_token", localObject3); } localObject1 = ((BehanceSDKCreateProjectDraftTaskParams) localObject2) .getBehanceSDKProjectDraftOptions(); localObject2 = new HttpPost(paramVarArgs); if (localObject1 != null) { localObject3 = MultipartEntityBuilder.create(); ContentType localContentType = ContentType.create("text/plain", "UTF-8"); paramVarArgs = ((BehanceSDKProjectDraftOptions) localObject1).getProjectTitle(); if (!TextUtils.isEmpty(paramVarArgs)) { ((MultipartEntityBuilder) localObject3).addTextBody("title", paramVarArgs, localContentType); } paramVarArgs = ((BehanceSDKProjectDraftOptions) localObject1).getProjectDescription(); if (!TextUtils.isEmpty(paramVarArgs)) { ((MultipartEntityBuilder) localObject3).addTextBody("description", paramVarArgs, localContentType); } paramVarArgs = ((BehanceSDKProjectDraftOptions) localObject1).getProjectTags(); if (!TextUtils.isEmpty(paramVarArgs)) { ((MultipartEntityBuilder) localObject3).addTextBody("tags", paramVarArgs, localContentType); } paramVarArgs = ((BehanceSDKProjectDraftOptions) localObject1).getCreativeFields(); if (!TextUtils.isEmpty(paramVarArgs)) { ((MultipartEntityBuilder) localObject3).addTextBody("fields", paramVarArgs, localContentType); } if (((BehanceSDKProjectDraftOptions) localObject1).isProjectContainsAdultContent()) { paramVarArgs = "1"; ((MultipartEntityBuilder) localObject3).addTextBody("mature_content", paramVarArgs, localContentType); paramVarArgs = ((BehanceSDKProjectDraftOptions) localObject1).getProjectCopyrightSettings(); if (paramVarArgs != null) { ((MultipartEntityBuilder) localObject3).addTextBody("license", paramVarArgs.getValue(), localContentType); } paramVarArgs = ((BehanceSDKProjectDraftOptions) localObject1).getCoverImage(); if (paramVarArgs != null) { ((MultipartEntityBuilder) localObject3).addPart("image", new FileBody(paramVarArgs)); } ((HttpPost) localObject2).setEntity(((MultipartEntityBuilder) localObject3).build()); } } else { paramVarArgs = BehanceSDKHTTPUtils.doHTTPPost((HttpPost) localObject2); if (paramVarArgs.getStatusCode() != 201) { localBehanceSDKAsyncTaskResultWrapper.setExceptionOccurred(true); localBehanceSDKAsyncTaskResultWrapper .setException(new BehanceSDKException(paramVarArgs.getReasonPhrase())); return localBehanceSDKAsyncTaskResultWrapper; } localBehanceSDKAsyncTaskResultWrapper.setExceptionOccurred(false); localBehanceSDKAsyncTaskResultWrapper.setResult( ((JSONObject) new JSONObject(paramVarArgs.getResponseString()).get("project")) .optString("id")); return localBehanceSDKAsyncTaskResultWrapper; } } catch (Throwable paramVarArgs) { localBehanceSDKAsyncTaskResultWrapper.setExceptionOccurred(true); localBehanceSDKAsyncTaskResultWrapper.setException(new BehanceSDKException(paramVarArgs)); return localBehanceSDKAsyncTaskResultWrapper; } paramVarArgs = "0"; } }
From source file:com.shafiq.myfeedle.core.PhotoUploadService.java
private void start(Intent intent) { if (intent != null) { String action = intent.getAction(); if (Myfeedle.ACTION_UPLOAD.equals(action)) { if (intent.hasExtra(Accounts.TOKEN) && intent.hasExtra(Statuses.MESSAGE) && intent.hasExtra(Widgets.INSTANT_UPLOAD)) { String place = null; if (intent.hasExtra(Splace)) place = intent.getStringExtra(Splace); String tags = null; if (intent.hasExtra(Stags)) tags = intent.getStringExtra(Stags); // upload a photo Notification notification = new Notification(R.drawable.notification, "uploading photo", System.currentTimeMillis()); notification.setLatestEventInfo(getBaseContext(), "photo upload", "uploading", PendingIntent.getActivity(PhotoUploadService.this, 0, (Myfeedle.getPackageIntent(PhotoUploadService.this, About.class)), 0)); ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(NOTIFY_ID, notification);//from w ww .j av a 2s . c om (new AsyncTask<String, Void, String>() { @Override protected String doInBackground(String... params) { String response = null; if (params.length > 2) { Log.d(TAG, "upload file: " + params[2]); HttpPost httpPost = new HttpPost(String.format(FACEBOOK_PHOTOS, FACEBOOK_BASE_URL, Saccess_token, mMyfeedleCrypto.Decrypt(params[0]))); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); File file = new File(params[2]); ContentBody fileBody = new FileBody(file); entity.addPart(Ssource, fileBody); HttpClient httpClient = MyfeedleHttpClient .getThreadSafeClient(getApplicationContext()); try { entity.addPart(Smessage, new StringBody(params[1])); if (params[3] != null) entity.addPart(Splace, new StringBody(params[3])); if (params[4] != null) entity.addPart(Stags, new StringBody(params[4])); httpPost.setEntity(entity); response = MyfeedleHttpClient.httpResponse(httpClient, httpPost); } catch (UnsupportedEncodingException e) { Log.e(TAG, e.toString()); } } return response; } @Override protected void onPostExecute(String response) { // notify photo success String message = getString(response != null ? R.string.success : R.string.failure); Notification notification = new Notification(R.drawable.notification, "photo upload " + message, System.currentTimeMillis()); notification.setLatestEventInfo(getBaseContext(), "photo upload", message, PendingIntent.getActivity(PhotoUploadService.this, 0, (Myfeedle.getPackageIntent(PhotoUploadService.this, About.class)), 0)); ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(NOTIFY_ID, notification); stopSelfResult(mStartId); } }).execute(intent.getStringExtra(Accounts.TOKEN), intent.getStringExtra(Statuses.MESSAGE), intent.getStringExtra(Widgets.INSTANT_UPLOAD), place, tags); } } } }
From source file:org.wso2.security.tools.zap.ext.zapwso2jiraplugin.JiraRestClient.java
public static void invokePutMethodWithFile(String auth, String url, String path) { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httppost = new HttpPost(url); httppost.setHeader(IssueCreatorConstants.ATLASSIAN_TOKEN, "nocheck"); httppost.setHeader(IssueCreatorConstants.ATLASSIAN_AUTHORIZATION, "Basic " + auth); File fileToUpload = new File(path); FileBody fileBody = new FileBody(fileToUpload); HttpEntity entity = MultipartEntityBuilder.create().addPart("file", fileBody).build(); httppost.setEntity(entity);/*from ww w . j a v a 2s .com*/ CloseableHttpResponse response = null; try { response = httpclient.execute(httppost); } catch (Exception e) { log.error("File upload failed when involing the update method with file "); } finally { try { httpclient.close(); } catch (IOException e) { log.error("Exception occured when closing the connection"); } } }
From source file:org.cvasilak.jboss.mobile.app.service.UploadToJBossServerService.java
@Override protected void onHandleIntent(Intent intent) { // initialize // extract details Server server = intent.getParcelableExtra("server"); String directory = intent.getStringExtra("directory"); String filename = intent.getStringExtra("filename"); // get the json parser from the application JsonParser jsonParser = new JsonParser(); // start the ball rolling... final NotificationManager mgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); final NotificationCompat.Builder builder = new NotificationCompat.Builder(this); builder.setTicker(String.format(getString(R.string.notif_ticker), filename)) .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_stat_notif_large)) .setSmallIcon(R.drawable.ic_stat_notif_small) .setContentTitle(String.format(getString(R.string.notif_title), filename)) .setContentText(getString(R.string.notif_content_init)) // to avoid NPE on android 2.x where content intent is required // set an empty content intent .setContentIntent(PendingIntent.getActivity(this, 0, new Intent(), 0)).setOngoing(true); // notify user that upload is starting mgr.notify(NOTIFICATION_ID, builder.build()); // reset ticker for any subsequent notifications builder.setTicker(null);//from w ww. j a v a 2s. c om AbstractHttpClient client = CustomHTTPClient.getHttpClient(); // enable digest authentication if (server.getUsername() != null && !server.getUsername().equals("")) { Credentials credentials = new UsernamePasswordCredentials(server.getUsername(), server.getPassword()); client.getCredentialsProvider().setCredentials( new AuthScope(server.getHostname(), server.getPort(), AuthScope.ANY_REALM), credentials); } final File file = new File(directory, filename); final long length = file.length(); try { CustomMultiPartEntity multipart = new CustomMultiPartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, new CustomMultiPartEntity.ProgressListener() { @Override public void transferred(long num) { // calculate percentage //System.out.println("transferred: " + num); int progress = (int) ((num * 100) / length); builder.setContentText(String.format(getString(R.string.notif_content), progress)); mgr.notify(NOTIFICATION_ID, builder.build()); } }); multipart.addPart(file.getName(), new FileBody(file)); HttpPost httpRequest = new HttpPost(server.getHostPort() + "/management/add-content"); httpRequest.setEntity(multipart); HttpResponse serverResponse = client.execute(httpRequest); BasicResponseHandler handler = new BasicResponseHandler(); JsonObject reply = jsonParser.parse(handler.handleResponse(serverResponse)).getAsJsonObject(); if (!reply.has("outcome")) { throw new RuntimeException(getString(R.string.invalid_response)); } else { // remove the 'upload in-progress' notification mgr.cancel(NOTIFICATION_ID); String outcome = reply.get("outcome").getAsString(); if (outcome.equals("success")) { String BYTES_VALUE = reply.get("result").getAsJsonObject().get("BYTES_VALUE").getAsString(); Intent resultIntent = new Intent(this, UploadCompletedActivity.class); // populate it resultIntent.putExtra("server", server); resultIntent.putExtra("BYTES_VALUE", BYTES_VALUE); resultIntent.putExtra("filename", filename); resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); // the notification id for the 'completed upload' notification // each completed upload will have a different id int notifCompletedID = (int) System.currentTimeMillis(); builder.setContentTitle(getString(R.string.notif_title_uploaded)) .setContentText(String.format(getString(R.string.notif_content_uploaded), filename)) .setContentIntent( // we set the (2nd param request code to completedID) // see http://tinyurl.com/kkcedju PendingIntent.getActivity(this, notifCompletedID, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT)) .setAutoCancel(true).setOngoing(false); mgr.notify(notifCompletedID, builder.build()); } else { JsonElement elem = reply.get("failure-description"); if (elem.isJsonPrimitive()) { throw new RuntimeException(elem.getAsString()); } else if (elem.isJsonObject()) throw new RuntimeException( elem.getAsJsonObject().get("domain-failure-description").getAsString()); } } } catch (Exception e) { builder.setContentText(e.getMessage()).setAutoCancel(true).setOngoing(false); mgr.notify(NOTIFICATION_ID, builder.build()); } }
From source file:eu.liveGov.libraries.livegovtoolkit.Utils.RestClient.java
public void Execute(RequestMethod method, int soTime, int connTime) throws Exception { switch (method) { case GET: {/*from w w w . ja v a 2 s . c o m*/ // add parameters String combinedParams = ""; if (!params.isEmpty()) { combinedParams += "?"; for (NameValuePair p : params) { String paramString; paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(), "UTF-8"); if (combinedParams.length() > 1) { combinedParams += "&" + paramString; } else { combinedParams += paramString; } } } HttpGet request = new HttpGet(url + combinedParams); // add headers for (NameValuePair h : headers) { request.addHeader(h.getName(), h.getValue()); } executeRequest(request, url, soTime, connTime); break; } case POST: { HttpPost request = new HttpPost(url); // add headers for (NameValuePair h : headers) { request.addHeader(h.getName(), h.getValue()); } if (!_json.isEmpty()) { request.addHeader("Content-type", "application/json"); request.setEntity(new StringEntity(_json, "UTF8")); } else if (!params.isEmpty()) { request.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); } executeRequest(request, url, soTime, connTime); break; } case POSTLOG: { HttpPost request = new HttpPost(url); // add headers for (NameValuePair h : headers) { request.addHeader(h.getName(), h.getValue()); } MultipartEntity reqEntity = new MultipartEntity(); if (!_json.isEmpty()) { reqEntity.addPart("LogfileRequest", new StringBody(_json, "application/json", Charset.forName("UTF-8"))); } else if (!params.isEmpty()) { // ignore the params for now. } if (_file != null) { reqEntity.addPart("logfile", new FileBody(_file)); } request.setEntity(reqEntity); executeRequest(request, url, soTime, connTime); break; } } }
From source file:name.richardson.james.maven.plugins.uploader.UploadMojo.java
public void execute() throws MojoExecutionException { this.getLog().info("Uploading project to BukkitDev"); final String gameVersion = this.getGameVersion(); final URIBuilder builder = new URIBuilder(); final MultipartEntity entity = new MultipartEntity(); HttpPost request;/*from ww w .j ava 2 s . c o m*/ // create the request builder.setScheme("http"); builder.setHost("dev.bukkit.org"); builder.setPath("/" + this.projectType + "/" + this.slug.toLowerCase() + "/upload-file.json"); try { entity.addPart("file_type", new StringBody(this.getFileType())); entity.addPart("name", new StringBody(this.project.getArtifact().getVersion())); entity.addPart("game_versions", new StringBody(gameVersion)); entity.addPart("change_log", new StringBody(this.changeLog)); entity.addPart("known_caveats", new StringBody(this.knownCaveats)); entity.addPart("change_markup_type", new StringBody(this.markupType)); entity.addPart("caveats_markup_type", new StringBody(this.markupType)); entity.addPart("file", new FileBody(this.getArtifactFile(this.project.getArtifact()))); } catch (final UnsupportedEncodingException e) { throw new MojoExecutionException(e.getMessage()); } // create the actual request try { request = new HttpPost(builder.build()); request.setHeader("User-Agent", "MavenCurseForgeUploader/1.0"); request.setHeader("X-API-Key", this.key); request.setEntity(entity); } catch (final URISyntaxException exception) { throw new MojoExecutionException(exception.getMessage()); } this.getLog().debug(request.toString()); // send the request and handle any replies try { final HttpClient client = new DefaultHttpClient(); final HttpResponse response = client.execute(request); switch (response.getStatusLine().getStatusCode()) { case 201: this.getLog().info("File uploaded successfully."); break; case 403: this.getLog().error( "You have not specifed your API key correctly or do not have permission to upload to that project."); break; case 404: this.getLog().error("Project was not found. Either it is specified wrong or been renamed."); break; case 422: this.getLog().error("There was an error in uploading the plugin"); this.getLog().debug(request.toString()); this.getLog().debug(EntityUtils.toString(response.getEntity())); break; default: this.getLog().warn("Unexpected response code: " + response.getStatusLine().getStatusCode()); break; } } catch (final ClientProtocolException exception) { throw new MojoExecutionException(exception.getMessage()); } catch (final IOException exception) { throw new MojoExecutionException(exception.getMessage()); } }