List of usage examples for org.apache.http.entity.mime MultipartEntity addPart
public void addPart(final String name, final ContentBody contentBody)
From source file:gov.nist.appvet.tool.AsynchronousService.java
public void sendReport(String appid, String toolrisk, String reportPath) { HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, 30000); HttpConnectionParams.setSoTimeout(httpParameters, 1200000); HttpClient httpclient = new DefaultHttpClient(httpParameters); httpclient = SSLWrapper.wrapClient(httpclient); try {/*w w w .jav a 2s . c o m*/ // To send reports back to AppVet, the following parameters must // be sent: // * command: SUBMIT_REPORT // * username: AppVet username // * password: AppVet password // * appid: The app ID // * toolid: The ID of this tool // * toolrisk: The risk assessment (PASS,FAIL,WARNING,ERROR) // * file: The report file. MultipartEntity entity = new MultipartEntity(); entity.addPart("command", new StringBody("SUBMIT_REPORT", Charset.forName("UTF-8"))); entity.addPart("username", new StringBody(Properties.appVetUsername, Charset.forName("UTF-8"))); entity.addPart("password", new StringBody(Properties.appVetPassword, Charset.forName("UTF-8"))); entity.addPart("appid", new StringBody(appid, Charset.forName("UTF-8"))); entity.addPart("toolid", new StringBody(Properties.toolId, Charset.forName("UTF-8"))); entity.addPart("toolrisk", new StringBody(toolrisk, Charset.forName("UTF-8"))); File report = new File(reportPath); FileBody fileBody = new FileBody(report); entity.addPart("file", fileBody); HttpPost httpPost = new HttpPost(Properties.appVetURL); httpPost.setEntity(entity); log.debug("Sending report to AppVet"); // Send the app to the tool final HttpResponse response = httpclient.execute(httpPost); httpPost = null; log.debug("Received: " + response.getStatusLine()); } catch (Exception e) { e.printStackTrace(); } }
From source file:at.ac.tuwien.big.testsuite.impl.validator.XhtmlValidator.java
@Override public ValidationResult validate(File fileToValidate, String exerciseId) throws Exception { HttpPost request = new HttpPost(W3C_XHTML_VALIDATOR_URL); List<ValidationResultEntry> validationResultEntries = new ArrayList<>(); try {/*from w w w .j ava2 s . c om*/ MultipartEntity multipartEntity = new MultipartEntity(); multipartEntity.addPart("uploaded_file", new FileBody(fileToValidate, "text/html")); multipartEntity.addPart("charset", new StringBody("(detect automatically)")); multipartEntity.addPart("doctype", new StringBody("Inline")); multipartEntity.addPart("group", new StringBody("0")); request.setEntity(multipartEntity); Document doc = httpClient.execute(request, new DomResponseHandler(httpClient, request)); String doctype = DomUtils.textByXpath(doc.getDocumentElement(), "//form[@id='form']/table//tr[4]/td[1]"); if (!"XHTML 1.1".equals(doctype.trim()) && !doctype.contains("XHTML+ARIA 1.0")) { validationResultEntries.add(new DefaultValidationResultEntry("Doctype Validation", "The given document is not XHTML 1.1 compatible, instead the guessed doctype is '" + doctype + "'", ValidationResultEntryType.ERROR)); } Document fileToValidateDocument = null; Element warningsContainer = DomUtils.byId(doc.getDocumentElement(), "warnings"); if (warningsContainer != null) { for (Element warningChildElement : DomUtils.asList(warningsContainer.getChildNodes())) { if (IGNORED_MESSAGES.contains(warningChildElement.getAttribute("id"))) { continue; } ValidationResultEntryType type = getEntryType(warningChildElement.getAttribute("class")); String title = getTitle( DomUtils.firstByClass(warningChildElement.getElementsByTagName("span"), "msg")); StringBuilder descriptionSb = new StringBuilder(); for (Element descriptionElement : DomUtils.listByXpath(warningChildElement, ".//p[position()>1]")) { descriptionSb.append(descriptionElement.getTextContent()); } validationResultEntries .add(new DefaultValidationResultEntry(title, descriptionSb.toString(), type)); } } Element errorsContainer = DomUtils.byId(doc.getDocumentElement(), "error_loop"); if (errorsContainer != null) { for (Element errorChildElement : DomUtils.asList(errorsContainer.getChildNodes())) { ValidationResultEntryType type = getEntryType(errorChildElement.getAttribute("class")); StringBuilder titleSb = new StringBuilder(); NodeList errorEms = errorChildElement.getElementsByTagName("em"); if (errorEms.getLength() > 0) { titleSb.append(getTitle((Element) errorEms.item(0))); titleSb.append(": "); } titleSb.append( getTitle(DomUtils.firstByClass(errorChildElement.getElementsByTagName("span"), "msg"))); StringBuilder descriptionSb = new StringBuilder(); for (Element descriptionElement : DomUtils.listByXpath(errorChildElement, ".//div/p")) { descriptionSb.append(descriptionElement.getTextContent()); } String title = titleSb.toString(); if (TestsuiteConstants.EX_ID_LAB3.equals(exerciseId)) { // This is more a hack than anything else but we have to ignore the errors that were produced by JSF specific artifacts. // We basically extract the line and column number from the reported errors and look for the 2 elements that match these // numbers and check if they really are the input elements produced by forms that cant be wrapped by block containers. // More specifically we check for inputs with type hidden, one is for the ViewState of JSF and the other is for recognition // of the form that was submitted. Matcher matcher = LINE_AND_COLUMN_NUMBER_PATTERN.matcher(title); if (title.contains("document type does not allow element \"input\" here") && matcher.matches()) { if (fileToValidateDocument == null) { fileToValidateDocument = DomUtils.createDocument(fileToValidate); } boolean excludeEntry = false; int expectedLineNumber = Integer.parseInt(matcher.group(1)); int expectedColumnNumber = Integer.parseInt(matcher.group(2)); try (BufferedReader reader = new BufferedReader( new InputStreamReader(new FileInputStream(fileToValidate)))) { String line; while ((line = reader.readLine()) != null) { if (--expectedLineNumber == 0) { Matcher lineMatcher = HIDDEN_FORM_INPUT_PATTERN.matcher(line); if (lineMatcher.matches()) { MatchResult matchResult = lineMatcher.toMatchResult(); if (matchResult.start(1) <= expectedColumnNumber && matchResult.end(1) >= expectedColumnNumber) { excludeEntry = true; break; } } lineMatcher = HIDDEN_VIEW_STATE_INPUT_PATTERN.matcher(line); if (lineMatcher.matches()) { MatchResult matchResult = lineMatcher.toMatchResult(); if (matchResult.start(1) <= expectedColumnNumber && matchResult.end(1) >= expectedColumnNumber) { excludeEntry = true; break; } } System.out.println("Could not match potential wrong error."); break; } } } if (excludeEntry) { continue; } } } validationResultEntries .add(new DefaultValidationResultEntry(title, descriptionSb.toString(), type)); } } } finally { request.releaseConnection(); } return new DefaultValidationResult("XHTML Validation", fileToValidate.getName(), new DefaultValidationResultType("XHTML"), validationResultEntries); }
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);/*from ww w . j a v a 2 s. 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, 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.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);// w w w. jav a 2 s.c o 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, 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:com.glodon.paas.document.api.FileRestAPITest.java
@Test public void uploadFileForMultiPart() throws IOException { File parentFile = getFile(simpleCall(createPost("/file/1?folder")), null); java.io.File file = new ClassPathResource("file/testupload.file").getFile(); String uploadUrl = "/file/" + file.getName() + "?upload&position=0&type=path"; HttpPost post = createPost(uploadUrl); FileBody fileBody = new FileBody(file); StringBody sbId = new StringBody(parentFile.getId()); StringBody sbSize = new StringBody(String.valueOf(file.length())); StringBody sbName = new StringBody(file.getName()); StringBody sbPosition = new StringBody("0"); MultipartEntity entity = new MultipartEntity(); entity.addPart("fileId", sbId); entity.addPart("size", sbSize); entity.addPart("fileName", sbName); entity.addPart("position", sbPosition); entity.addPart("file", fileBody); post.setEntity(entity);/* www .j a v a 2 s . c o m*/ File uploadFile = getFile(simpleCall(post), null); assertEquals(file.getName(), uploadFile.getFullName()); assertTrue(file.length() == uploadFile.getSize()); assertEquals(parentFile.getId(), uploadFile.getParentId()); }
From source file:com.puppetlabs.geppetto.forge.client.ForgeHttpClient.java
@Override public <V> V postUpload(String uri, Map<String, String> stringParts, InputStream in, String mimeType, String fileName, final long fileSize, Class<V> type) throws IOException { HttpPost request = new HttpPost(createV2Uri(uri)); configureRequest(request);/* ww w.j av a 2 s .c o m*/ MultipartEntity entity = new MultipartEntity(); for (Map.Entry<String, String> entry : stringParts.entrySet()) entity.addPart(entry.getKey(), StringBody.create(entry.getValue(), "text/plain", UTF_8)); entity.addPart("file", new InputStreamBody(in, mimeType, fileName) { @Override public long getContentLength() { return fileSize; } }); request.setEntity(entity); return executeRequest(request, type); }
From source file:de.raptor2101.GalDroid.WebGallery.Gallery3.Gallery3Imp.java
public String getSecurityToken(String user, String password) throws SecurityException { try {//from ww w . j a v a2s. c om HttpPost httpRequest = new HttpPost(LinkRest_LoadSecurityToken); httpRequest.addHeader("X-Gallery-Request-Method", "post"); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); mpEntity.addPart("user", new StringBody(user)); mpEntity.addPart("password", new StringBody(password)); httpRequest.setEntity(mpEntity); HttpResponse response; response = mHttpClient.execute(httpRequest); InputStream inputStream = response.getEntity().getContent(); InputStreamReader streamReader = new InputStreamReader(inputStream); BufferedReader reader = new BufferedReader(streamReader); String content = reader.readLine(); inputStream.close(); if (content.length() == 0 || content.startsWith("[]")) { throw new SecurityException("Couldn't verify user-credentials"); } return content.trim().replace("\"", ""); } catch (Exception e) { throw new SecurityException("Couldn't verify user-credentials", e); } }
From source file:com.glodon.paas.document.api.FileRestAPITest.java
@Test public void uploadFolderForMultiPart() throws IOException { File parentFile = getFile(simpleCall(createPost("/file/1?folder")), null); java.io.File file = new ClassPathResource("file/testupload.file").getFile(); String uploadUrl = "/file/" + file.getName() + "?upload&position=0&type=path"; HttpPost post = createPost(uploadUrl); FileBody fileBody = new FileBody(file); StringBody sbId = new StringBody(parentFile.getId()); StringBody sbSize = new StringBody(String.valueOf(file.length())); StringBody sbName = new StringBody("aa/" + file.getName()); StringBody sbPosition = new StringBody("0"); MultipartEntity entity = new MultipartEntity(); entity.addPart("fileId", sbId); entity.addPart("size", sbSize); entity.addPart("fileName", sbName); entity.addPart("position", sbPosition); entity.addPart("file", fileBody); post.setEntity(entity);// w w w . ja v a2 s .c o m File uploadFile = getFile(simpleCall(post), null); assertEquals(file.getName(), uploadFile.getFullName()); assertFalse(uploadFile.isFolder()); File aaFolder = getFile(simpleCall(createGet("/file/1/aa?meta")), "meta"); assertEquals(aaFolder.getId(), uploadFile.getParentId()); }
From source file:com.liferay.ide.server.remote.ServerManagerConnection.java
public Object installApplication(String absolutePath, String appName, IProgressMonitor submon) throws APIException { try {// www . ja v a 2s . co m FileBody fileBody = new FileBody(new File(absolutePath)); MultipartEntity entity = new MultipartEntity(); entity.addPart("deployWar", fileBody); HttpPost httpPost = new HttpPost(); httpPost.setEntity(entity); Object response = httpJSONAPI(httpPost, _getDeployURI(appName)); if (response instanceof JSONObject) { JSONObject jsonObject = (JSONObject) response; if (_isSuccess(jsonObject)) { System.out.println("installApplication: Sucess.\n\n"); } else { if (_isError(jsonObject)) { return jsonObject.getString("error"); } else { return "installApplication error " + _getDeployURI(appName); } } } httpPost.releaseConnection(); } catch (Exception e) { e.printStackTrace(); return e.getMessage(); } return null; }
From source file:com.liferay.ide.server.remote.ServerManagerConnection.java
public Object updateApplication(String appName, String absolutePath, IProgressMonitor monitor) throws APIException { try {// w w w. j a va2 s. c o m File file = new File(absolutePath); FileBody fileBody = new FileBody(file); MultipartEntity entity = new MultipartEntity(); entity.addPart(file.getName(), fileBody); HttpPut httpPut = new HttpPut(); httpPut.setEntity(entity); Object response = httpJSONAPI(httpPut, _getUpdateURI(appName)); if (response instanceof JSONObject) { JSONObject jsonObject = (JSONObject) response; if (_isSuccess(jsonObject)) { System.out.println("updateApplication: success.\n\n"); } else { if (_isError(jsonObject)) { return jsonObject.getString("error"); } else { return "updateApplication error " + _getDeployURI(appName); } } } httpPut.releaseConnection(); } catch (Exception e) { e.printStackTrace(); return e.getMessage(); } return null; }