List of usage examples for org.apache.http.entity.mime.content FileBody FileBody
public FileBody(final File file, final String mimeType)
From source file:net.java.sip.communicator.service.httputil.HttpUtils.java
/** * Posts a <tt>file</tt> to the <tt>address</tt>. * @param address the address to post the form to. * @param fileParamName the name of the param for the file. * @param file the file we will send.//from w w w .j ava 2 s .com * @param usernamePropertyName the property to use to retrieve/store * username value if protected site is hit, for username * ConfigurationService service is used. * @param passwordPropertyName the property to use to retrieve/store * password value if protected site is hit, for password * CredentialsStorageService service is used. * @return the result or null if send was not possible or * credentials ask if any was canceled. */ public static HTTPResponseResult postFile(String address, String fileParamName, File file, String usernamePropertyName, String passwordPropertyName) { DefaultHttpClient httpClient = null; try { HttpPost postMethod = new HttpPost(address); httpClient = getHttpClient(usernamePropertyName, passwordPropertyName, postMethod.getURI().getHost(), null); String mimeType = URLConnection.guessContentTypeFromName(file.getPath()); if (mimeType == null) mimeType = "application/octet-stream"; FileBody bin = new FileBody(file, mimeType); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart(fileParamName, bin); postMethod.setEntity(reqEntity); HttpEntity resEntity = executeMethod(httpClient, postMethod, null, null); if (resEntity == null) return null; return new HTTPResponseResult(resEntity, httpClient); } catch (Throwable e) { logger.error("Cannot post file to:" + address, e); } return null; }
From source file:org.wso2.am.integration.tests.publisher.APIM614AddDocumentationToAnAPIWithDocTypeSampleAndSDKThroughPublisherRestAPITestCase.java
@Test(groups = { "wso2.am" }, description = "Add Documentation To An API With Type Sample SDK And" + " Source File through the publisher rest API ", dependsOnMethods = "testAddDocumentToAnAPIHowToFile") public void testAddDocumentToAnAPISDKToFile() throws Exception { String fileNameAPIM622 = "APIM622.txt"; String docName = "APIM622PublisherTestHowTo-File-summary"; String docType = "samples"; String sourceType = "file"; String summary = "Testing"; String mimeType = "text/plain"; String docUrl = "http://"; String filePathAPIM622 = TestConfigurationProvider.getResourceLocation() + File.separator + "artifacts" + File.separator + "AM" + File.separator + "lifecycletest" + File.separator + fileNameAPIM622; String addDocUrl = publisherUrls.getWebAppURLHttp() + "publisher/site/blocks/documentation/ajax/docs.jag"; //Send Http Post request to add a new file HttpPost httppost = new HttpPost(addDocUrl); File file = new File(filePathAPIM622); FileBody fileBody = new FileBody(file, "text/plain"); //Create multipart entity to upload file as multipart file MultipartEntity multipartEntity = new MultipartEntity(); multipartEntity.addPart("docLocation", fileBody); multipartEntity.addPart("mode", new StringBody("")); multipartEntity.addPart("docName", new StringBody(docName)); multipartEntity.addPart("docUrl", new StringBody(docUrl)); multipartEntity.addPart("sourceType", new StringBody(sourceType)); multipartEntity.addPart("summary", new StringBody(summary)); multipartEntity.addPart("docType", new StringBody(docType)); multipartEntity.addPart("version", new StringBody(apiVersion)); multipartEntity.addPart("apiName", new StringBody(apiName)); multipartEntity.addPart("action", new StringBody("addDocumentation")); multipartEntity.addPart("provider", new StringBody(apiProvider)); multipartEntity.addPart("mimeType", new StringBody(mimeType)); multipartEntity.addPart("optionsRadios", new StringBody(docType)); multipartEntity.addPart("optionsRadios1", new StringBody(sourceType)); multipartEntity.addPart("optionsRadios1", new StringBody(sourceType)); httppost.setEntity(multipartEntity); //Upload created file and validate HttpResponse response = httpClient.execute(httppost); HttpEntity entity = response.getEntity(); JSONObject jsonObject1 = new JSONObject(EntityUtils.toString(entity)); assertFalse(jsonObject1.getBoolean("error"), "Error when adding files to the API "); }
From source file:com.reelfx.model.PostProcessor.java
public void run() { try {// ww w . j av a 2 s . com String ffmpeg = "ffmpeg" + (Applet.IS_WINDOWS ? ".exe" : ""); // ----- quickly merge audio and video after recording ----------------------- if (outputFile != null && encodingOpts.containsKey(MERGE_AUDIO_VIDEO) && !Applet.IS_MAC) { fireProcessUpdate(ENCODING_STARTED); // get information about the media file: //Map<String,Object> metadata = parseMediaFile(ScreenRecorder.OUTPUT_FILE.getAbsolutePath()); //printMetadata(metadata); List<String> ffmpegArgs = new ArrayList<String>(); ffmpegArgs.add(Applet.BIN_FOLDER.getAbsoluteFile() + File.separator + ffmpeg); ffmpegArgs.add("-y"); // overwrite any existing file // audio and video files if (AudioRecorder.OUTPUT_FILE.exists()) { // if opted for microphone // delay the audio if needed ( http://howto-pages.org/ffmpeg/#delay ) if (encodingOpts.containsKey(OFFSET_AUDIO)) ffmpegArgs.addAll(parseParameters("-itsoffset 00:00:0" + encodingOpts.get(OFFSET_AUDIO))); // assume offset is less than 10 seconds ffmpegArgs.addAll(parseParameters("-i " + AudioRecorder.OUTPUT_FILE.getAbsolutePath())); // delay the video if needed ( http://howto-pages.org/ffmpeg/#delay ) if (encodingOpts.containsKey(OFFSET_VIDEO)) ffmpegArgs.addAll(parseParameters("-itsoffset 00:00:0" + encodingOpts.get(OFFSET_VIDEO))); } ffmpegArgs.addAll(parseParameters("-i " + ScreenRecorder.OUTPUT_FILE)); // export settings ffmpegArgs.addAll(getFfmpegCopyParams()); // resize screen //ffmpegArgs.addAll(parseParameters("-s 1024x"+Math.round(1024.0/(double)Applet.SCREEN.width*(double)Applet.SCREEN.height))); ffmpegArgs.add(outputFile.getAbsolutePath()); logger.info("Executing this command: " + prettyCommand(ffmpegArgs)); ProcessBuilder pb = new ProcessBuilder(ffmpegArgs); ffmpegProcess = pb.start(); errorGobbler = new StreamGobbler(ffmpegProcess.getErrorStream(), false, "ffmpeg E"); inputGobbler = new StreamGobbler(ffmpegProcess.getInputStream(), false, "ffmpeg O"); logger.info("Starting listener threads..."); errorGobbler.start(); inputGobbler.start(); ffmpegProcess.waitFor(); logger.info("Done encoding..."); fireProcessUpdate(ENCODING_COMPLETE); } // end merging audio/video // ----- encode file to X264 ----------------------- else if (outputFile != null && encodingOpts.containsKey(ENCODE_TO_X264) && !Applet.IS_MAC && !DEFAULT_OUTPUT_FILE.exists()) { fireProcessUpdate(ENCODING_STARTED); File inputFile = Applet.IS_LINUX ? LinuxController.MERGED_OUTPUT_FILE : WindowsController.MERGED_OUTPUT_FILE; // get information about the media file: //metadata = parseMediaFile(inputFile.getAbsolutePath()); //printMetadata(metadata); List<String> ffmpegArgs = new ArrayList<String>(); ffmpegArgs.add(Applet.BIN_FOLDER.getAbsoluteFile() + File.separator + ffmpeg); ffmpegArgs.addAll(parseParameters("-y -i " + inputFile.getAbsolutePath())); ffmpegArgs.addAll(getFfmpegX264FastFirstPastBaselineParams()); ffmpegArgs.add(DEFAULT_OUTPUT_FILE.getAbsolutePath()); logger.info("Executing this command: " + prettyCommand(ffmpegArgs)); ProcessBuilder pb = new ProcessBuilder(ffmpegArgs); ffmpegProcess = pb.start(); errorGobbler = new StreamGobbler(ffmpegProcess.getErrorStream(), false, "ffmpeg E"); inputGobbler = new StreamGobbler(ffmpegProcess.getInputStream(), false, "ffmpeg O"); logger.info("Starting listener threads..."); //errorGobbler.addActionListener("frame", this); errorGobbler.start(); inputGobbler.start(); ffmpegProcess.waitFor(); logger.info("Done encoding..."); fireProcessUpdate(ENCODING_COMPLETE); } // do we need to copy the X264 encoded file somewhere? if (outputFile != null && encodingOpts.containsKey(ENCODE_TO_X264) && !Applet.IS_MAC && !outputFile.getAbsolutePath().equals(DEFAULT_OUTPUT_FILE.getAbsolutePath())) { FileUtils.copyFile(DEFAULT_OUTPUT_FILE, outputFile); fireProcessUpdate(ENCODING_COMPLETE); } // ----- just copy the file if it's a Mac ----------------------- if (outputFile != null && Applet.IS_MAC) { FileUtils.copyFile(ScreenRecorder.OUTPUT_FILE, outputFile); fireProcessUpdate(ENCODING_COMPLETE); } try { // ----- post data of screen capture to Insight ----------------------- if (postRecording) { // base code: http://stackoverflow.com/questions/1067655/how-to-upload-a-file-using-java-httpclient-library-working-with-php-strange-pro fireProcessUpdate(POST_STARTED); HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); CountingMultipartEntity entity = new CountingMultipartEntity(); ContentBody body = new FileBody(outputFile, "video/quicktime"); entity.addPart("capture_file", body); HttpPost post = new HttpPost(postUrl); post.setEntity(entity); logger.info("Posting file to server... " + post.getRequestLine()); HttpResponse response = client.execute(post); HttpEntity responseEntity = response.getEntity(); logger.info("Response Status Code: " + response.getStatusLine()); if (responseEntity != null) { logger.info(EntityUtils.toString(responseEntity)); // to see the response body } // redirection to show page (meaning everything was correct); NOTE: Insight redirects you to the login form when you're not logged in (or no api_key) //if(response.getStatusLine().getStatusCode() == 302) { //Header header = response.getFirstHeader("Location"); //logger.info("Redirecting to "+header.getValue()); //Applet.redirectWebPage(header.getValue()); //Applet.APPLET.showDocument(new URL(header.getValue()),"_self"); if (response.getStatusLine().getStatusCode() == 200) { fireProcessUpdate(POST_COMPLETE); } else { fireProcessUpdate(POST_FAILED); } if (responseEntity != null) { responseEntity.consumeContent(); } client.getConnectionManager().shutdown(); } // ----- post data of screen capture to Insight ----------------------- else if (postData) { fireProcessUpdate(POST_STARTED); HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpPost post = new HttpPost(postUrl); logger.info("Sending data to Insight... " + post.getRequestLine()); HttpResponse response = client.execute(post); HttpEntity responseEntity = response.getEntity(); logger.info("Response Status Code: " + response.getStatusLine()); if (responseEntity != null) { logger.info(EntityUtils.toString(responseEntity)); // to see the response body } if (response.getStatusLine().getStatusCode() == 200) { fireProcessUpdate(POST_COMPLETE); } else { fireProcessUpdate(POST_FAILED); } if (responseEntity != null) { responseEntity.consumeContent(); } client.getConnectionManager().shutdown(); } // TODO monitor the progress of the transcoding? // TODO allow canceling of the transcoding? } catch (Exception e) { logger.error("Error occurred while posting the file.", e); fireProcessUpdate(POST_FAILED); } finally { outputFile = null; encodingOpts = new HashMap<Integer, String>(); // reset encoding options metadata = null; } } catch (Exception e) { logger.error("Error occurred while encoding the file.", e); fireProcessUpdate(ENCODING_FAILED); } }
From source file:com.cianmcgovern.android.ShopAndShare.Share.java
/** * Uploads the text file specified by filename * /*from www .j a va 2 s .c o m*/ * @param instance * The results instance to use * @param location * The location as specified by the user * @param store * The store as specified by the user * @return Response message from server * @throws ClientProtocolException * @throws IOException */ private String upload(Results instance, String location, String store) throws ClientProtocolException, IOException { Log.v(Constants.LOG_TAG, "Inside upload"); HttpClient httpClient = new DefaultHttpClient(); httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); String filename = Results.getInstance().toFile(); HttpPost httpPost = new HttpPost(Constants.FULL_URL); File file = new File(filename); MultipartEntity entity = new MultipartEntity(); ContentBody cb = new FileBody(file, "plain/text"); entity.addPart("inputfile", cb); ContentBody cbLocation = new StringBody(location); entity.addPart("location", cbLocation); ContentBody cbStore = new StringBody(store); entity.addPart("store", cbStore); httpPost.setEntity(entity); Log.v(Constants.LOG_TAG, "Sending post"); HttpResponse response = httpClient.execute(httpPost); HttpEntity resEntity = response.getEntity(); String message = EntityUtils.toString(resEntity); Log.v(Constants.LOG_TAG, "Response from upload is: " + message); resEntity.consumeContent(); httpClient.getConnectionManager().shutdown(); file.delete(); return message; }
From source file:com.ad.mediasharing.ADUploadMediaTask.java
private FileBody getMediaType(File f) { FileBody fb = null;/* ww w. jav a 2 s . c om*/ if (f != null) { if (f.getName().endsWith(".gif")) { fb = new FileBody(f, "image/gif"); } else if (f.getName().endsWith(".jpg")) { fb = new FileBody(f, "image/jpeg"); } else if (f.getName().endsWith(".png")) { fb = new FileBody(f, "image/png"); } else if (f.getName().endsWith(".3gpp")) { fb = new FileBody(f, "audio/3gpp"); } else if (f.getName().endsWith(".3gp")) { fb = new FileBody(f, "video/3gpp"); } else if (f.getName().endsWith(".mp4")) { fb = new FileBody(f, "video/mp4"); } else { if (ADMediaSharingConstants.DEBUG) Log.d(TAG, "unsupported file type, not adding file: " + f.getName()); } } return fb; }
From source file:com.pc.dailymile.DailyMileClient.java
public Long addNoteWithImage(String note, File imageFile) throws Exception { HttpPost request = new HttpPost(DailyMileUtil.ENTRIES_URL); HttpResponse response = null;//from w ww .j a v a2 s . c o m try { MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); mpEntity.addPart("media[data]", new FileBody(imageFile, "image/jpeg")); mpEntity.addPart("media[type]", new StringBody("image")); mpEntity.addPart("message", new StringBody(note)); mpEntity.addPart("[share_on_services][facebook]", new StringBody("false")); mpEntity.addPart("[share_on_services][twitter]", new StringBody("false")); mpEntity.addPart("oauth_token", new StringBody(oauthToken)); request.setEntity(mpEntity); // send the request response = httpClient.execute(request); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 401) { throw new RuntimeException( "unable to execute POST - url: " + DailyMileUtil.ENTRIES_URL + " body: " + note); } if (statusCode == 201) { Header loc = response.getFirstHeader("Location"); if (loc != null) { String locS = loc.getValue(); if (!StringUtils.isBlank(locS) && locS.matches(".*/[0-9]+$")) { try { return NumberUtils.createLong(locS.substring(locS.lastIndexOf("/") + 1)); } catch (NumberFormatException e) { return null; } } } } return null; } finally { try { if (response != null) { HttpEntity entity = response.getEntity(); if (entity != null) { entity.consumeContent(); } } //EntityUtils.consume(response.getEntity()); } catch (IOException e) { // ignore } } }
From source file:eu.geopaparazzi.library.network.NetworkUtilities.java
/** * Sends a {@link MultipartEntity} post with text and image files. * //from www. j av a2 s.c o m * @param url the url to which to POST to. * @param user the user or <code>null</code>. * @param pwd the password or <code>null</code>. * @param stringsMap the {@link HashMap} containing the key and string pairs to send. * @param filesMap the {@link HashMap} containing the key and image file paths * (jpg, png supported) pairs to send. * @throws UnsupportedEncodingException * @throws IOException * @throws ClientProtocolException */ public static void sentMultiPartPost(String url, String user, String pwd, HashMap<String, String> stringsMap, HashMap<String, File> filesMap) throws UnsupportedEncodingException, IOException, ClientProtocolException { HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpPost httppost = new HttpPost(url); if (user != null && pwd != null) { String ret = getB64Auth(user, pwd); httppost.setHeader("Authorization", ret); } MultipartEntity mpEntity = new MultipartEntity(); Set<Entry<String, String>> stringsEntrySet = stringsMap.entrySet(); for (Entry<String, String> stringEntry : stringsEntrySet) { ContentBody cbProperties = new StringBody(stringEntry.getValue()); mpEntity.addPart(stringEntry.getKey(), cbProperties); } Set<Entry<String, File>> filesEntrySet = filesMap.entrySet(); for (Entry<String, File> filesEntry : filesEntrySet) { String propName = filesEntry.getKey(); File file = filesEntry.getValue(); if (file.exists()) { String ext = file.getName().toLowerCase().endsWith("jpg") ? "jpeg" : "png"; ContentBody cbFile = new FileBody(file, "image/" + ext); mpEntity.addPart(propName, cbFile); } } httppost.setEntity(mpEntity); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { resEntity.consumeContent(); } httpclient.getConnectionManager().shutdown(); }
From source file:org.wso2.am.integration.tests.publisher.APIM614AddDocumentationToAnAPIWithDocTypeSampleAndSDKThroughPublisherRestAPITestCase.java
@Test(groups = { "wso2.am" }, description = "Add Documentation To An API With Type public forum And" + " Source File through the publisher rest API ", dependsOnMethods = "testAddDocumentToAnAPISDKToFile") public void testAddDocumentToAnAPIPublicToFile() throws Exception { String fileNameAPIM624 = "APIM624.txt"; String docName = "APIM624PublisherTestHowTo-File-summary"; String docType = "public forum"; String sourceType = "file"; String summary = "Testing"; String mimeType = "text/plain"; String docUrl = "http://"; String filePathAPIM624 = TestConfigurationProvider.getResourceLocation() + File.separator + "artifacts" + File.separator + "AM" + File.separator + "lifecycletest" + File.separator + fileNameAPIM624; String addDocUrl = publisherUrls.getWebAppURLHttp() + "publisher/site/blocks/documentation/ajax/docs.jag"; //Send Http Post request to add a new file HttpPost httppost = new HttpPost(addDocUrl); File file = new File(filePathAPIM624); FileBody fileBody = new FileBody(file, "text/plain"); //Create multipart entity to upload file as multipart file MultipartEntity multipartEntity = new MultipartEntity(); multipartEntity.addPart("docLocation", fileBody); multipartEntity.addPart("mode", new StringBody("")); multipartEntity.addPart("docName", new StringBody(docName)); multipartEntity.addPart("docUrl", new StringBody(docUrl)); multipartEntity.addPart("sourceType", new StringBody(sourceType)); multipartEntity.addPart("summary", new StringBody(summary)); multipartEntity.addPart("docType", new StringBody(docType)); multipartEntity.addPart("version", new StringBody(apiVersion)); multipartEntity.addPart("apiName", new StringBody(apiName)); multipartEntity.addPart("action", new StringBody("addDocumentation")); multipartEntity.addPart("provider", new StringBody(apiProvider)); multipartEntity.addPart("mimeType", new StringBody(mimeType)); multipartEntity.addPart("optionsRadios", new StringBody(docType)); multipartEntity.addPart("optionsRadios1", new StringBody(sourceType)); multipartEntity.addPart("optionsRadios1", new StringBody(sourceType)); httppost.setEntity(multipartEntity); //Upload created file and validate HttpResponse response = httpClient.execute(httppost); HttpEntity entity = response.getEntity(); JSONObject jsonObject1 = new JSONObject(EntityUtils.toString(entity)); assertFalse(jsonObject1.getBoolean("error"), "Error when adding files to the API "); }
From source file:org.wso2.mdm.qsg.utils.HTTPInvoker.java
public static HTTPResponse uploadFile(String url, String fileName, String fileContentType) { HttpPost post = null;/*from www . ja va2 s . c om*/ HttpResponse response = null; HTTPResponse httpResponse = new HTTPResponse(); CloseableHttpClient httpclient = null; try { httpclient = (CloseableHttpClient) createHttpClient(); post = new HttpPost(url); File file = new File(fileName); MultipartEntity mpEntity = new MultipartEntity(); ContentBody cbFile = new FileBody(file, fileContentType); mpEntity.addPart("file", cbFile); post.setEntity(mpEntity); post.setHeader(Constants.Header.AUTH, OAUTH_BEARER + oAuthToken); //post.setHeader(Constants.Header.CONTENT_TYPE, "multipart/form-data"); post.setHeader("Accept", Constants.ContentType.APPLICATION_JSON); response = httpclient.execute(post); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } BufferedReader rd = null; try { rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); } catch (IOException e) { e.printStackTrace(); } StringBuffer result = new StringBuffer(); String line = ""; try { while ((line = rd.readLine()) != null) { result.append(line); } } catch (IOException e) { e.printStackTrace(); } httpResponse.setResponseCode(response.getStatusLine().getStatusCode()); httpResponse.setResponse(result.toString()); try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } return httpResponse; }
From source file:org.bungeni.ext.integration.bungeniportal.BungeniServiceAccess.java
public HashMap<String, ContentBody> attachmentEditSubmitPostQuery(HashMap<String, ContentBody> formFields, String title, String description, String fFileName) { try {//from w ww .j a v a 2 s. c o m formFields.put("form.title", new StringBody(title)); formFields.put("form.data.up_action", new StringBody("update")); formFields.put("form_data_file", new FileBody(new File(new URI(fFileName)), getMimeType(fFileName))); formFields.put("form.description", new StringBody(description)); formFields.put("form.language-empty-marker", new StringBody("1")); formFields.put("form.type-empty-marker", new StringBody("1")); return formFields; } catch (URISyntaxException ex) { log.error("Error getting URI to file ", ex); return formFields; } catch (UnsupportedEncodingException ex) { log.error("Encoding exception for field ", ex); return formFields; } }