List of usage examples for org.apache.http.entity.mime.content FileBody FileBody
public FileBody(final File file, final String mimeType)
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 av a2s . 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:org.hk.jt.client.core.Request.java
private HttpResponse execPost() throws URISyntaxException, InvalidKeyException, UnsupportedEncodingException, NoSuchAlgorithmException, IOException { DefaultHttpClient client = new DefaultHttpClient(); HttpClientParams.setCookiePolicy(client.getParams(), CookiePolicy.BROWSER_COMPATIBILITY); HttpPost httpPost = new HttpPost(); httpPost.setURI(new URI(requestIf.getUrl())); httpPost.setHeader("Authorization", createAuthorizationValue()); if (postParameter != null && !postParameter.isEmpty()) { final List<NameValuePair> params = new ArrayList<NameValuePair>(); for (String key : postParameter.keySet()) { params.add(new BasicNameValuePair(key, postParameter.get(key))); }// ww w. j a v a 2 s.c o m httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); } if (requestIf.getFiles() != null) { final MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); List<NameValuePair> fileList = requestIf.getFiles(); if (fileList != null && !fileList.isEmpty()) { for (NameValuePair val : fileList) { File file = new File(val.getValue()); entity.addPart(val.getName(), new FileBody(file, CONTENTTYPE_BINARY)); } } httpPost.setEntity(entity); } httpPost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false); return client.execute(httpPost); }
From source file:com.impetus.ankush.agent.action.impl.UploadHandler.java
/** * Method that builds the multi-part form data request. * /*from ww w . j a v a2s . com*/ * @param urlString * the urlString to which the file needs to be uploaded * @param file * the actual file instance that needs to be uploaded * @param fileName * name of the file, just to show how to add the usual form * parameters * @param fileDescription * some description for the file, just to show how to add the * usual form parameters * @return server response as <code>String</code> */ public String executeMultiPartRequest(String urlString, File file, String fileName, String fileDescription) { HttpPost postRequest = new HttpPost(urlString); try { MultipartEntity multiPartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); // The usual form parameters can be added this way multiPartEntity.addPart("fileDescription", new StringBody(fileDescription != null ? fileDescription : "")); multiPartEntity.addPart("fileName", new StringBody(fileName != null ? fileName : file.getName())); /* * Need to construct a FileBody with the file that needs to be * attached and specify the mime type of the file. Add the fileBody * to the request as an another part. This part will be considered * as file part and the rest of them as usual form-data parts */ FileBody fileBody = new FileBody(file, "application/octect-stream"); multiPartEntity.addPart("file", fileBody); postRequest.setEntity(multiPartEntity); } catch (Exception ex) { LOGGER.error(ex.getMessage(), ex); return null; } return executeRequest(postRequest); }
From source file:com.mobisys.android.ibp.ObservationRequestQueue.java
private void uploadImage(final boolean single, final Bundle b, final Context context, final ArrayList<String> imageStringPath, ArrayList<String> imageType, final ObservationInstance sp) { MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); if (b != null) Log.d("ObservationRequestQueue", "Params: " + b.toString()); int countUri = 0; for (int i = 0; i < imageStringPath.size(); i++) { if (!imageStringPath.get(i).contains("http://")) { FileBody bab;/* w ww .j ava2 s .c om*/ if (imageType.get(i) != null) bab = new FileBody(new File(imageStringPath.get(i)), imageType.get(i)); // image path and image type else bab = new FileBody(new File(imageStringPath.get(i)), "image/jpeg"); // image p reqEntity.addPart("resources", bab); ++countUri; } } // if imagestring path has no Image url's. if (countUri != 0) { try { reqEntity.addPart(Request.RESOURCE_TYPE, new StringBody("species.participation.Observation")); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } WebService.sendMultiPartRequest(context, Request.METHOD_POST, Request.PATH_UPLOAD_RESOURCE, new ResponseHandler() { @Override public void onSuccess(String response) { sp.setStatus(StatusType.PROCESSING); ObservationInstanceTable.updateRowFromTable(context, sp); parseUploadResourceDetail(response, single, b, context, sp, imageStringPath); } @Override public void onFailure(Throwable e, String content) { Log.d("NetWorkState", content); if (e instanceof UnknownHostException || e instanceof ConnectException) { mIsRunning = false; return; } sp.setStatus(StatusType.FAILURE); sp.setMessage(content); ObservationInstanceTable.updateRowFromTable(context, sp); //ObservationParamsTable.deleteRowFromTable(context, sp); if (!single) { ObservationInstance sp_new = ObservationInstanceTable.getFirstRecord(context); observationMethods(single, sp_new, context); } } }, reqEntity); } else { // if all are url's for (int i = 0; i < imageStringPath.size(); i++) { b.putString("file_" + (i + 1), imageStringPath.get(i) .replace("http://" + HttpUtils.stageOrProdBaseURL() + "/biodiv/observations/", "")); b.putString("type_" + (i + 1), Constants.IMAGE); b.putString("license_" + (i + 1), "CC_BY"); } submitObservationRequestFinally(single, b, context, sp); } }
From source file:at.ac.tuwien.big.testsuite.impl.validator.WaiValidator.java
@Override public ValidationResult validate(File fileToValidate, String exerciseId) throws Exception { CookieStore cookieStore = new BasicCookieStore(); HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); HttpPost request = new HttpPost("http://localhost:8080/" + contextPath + "/checker/index.php"); List<ValidationResultEntry> validationResultEntries = new ArrayList<>(); try {//from ww w . j ava 2 s .c o m MultipartEntity multipartEntity = new MultipartEntity(); multipartEntity.addPart("uri", new StringBody("")); multipartEntity.addPart("MAX_FILE_SIZE", new StringBody("52428800")); multipartEntity.addPart("uploadfile", new FileBody(fileToValidate, "text/html")); multipartEntity.addPart("validate_file", new StringBody("Check It")); multipartEntity.addPart("pastehtml", new StringBody("")); multipartEntity.addPart("radio_gid[]", new StringBody("8")); multipartEntity.addPart("checkbox_gid[]", new StringBody("8")); multipartEntity.addPart("rpt_format", new StringBody("1")); request.setEntity(multipartEntity); Document doc = httpClient.execute(request, new DomResponseHandler(httpClient, request), httpContext); Element errorsContainer = DomUtils.byId(doc.getDocumentElement(), "AC_errors"); String title = ""; StringBuilder descriptionSb = new StringBuilder(); boolean descriptionStarted = false; for (Element e : DomUtils.asList(errorsContainer.getChildNodes())) { if ("h3".equals(e.getTagName())) { if (descriptionStarted) { validationResultEntries.add(new DefaultValidationResultEntry(title, descriptionSb.toString(), ValidationResultEntryType.ERROR)); } title = e.getTextContent(); descriptionSb.setLength(0); descriptionStarted = false; } else if ("div".equals(e.getTagName()) && e.getAttribute("class").contains("gd_one_check")) { if (descriptionStarted) { descriptionSb.append('\n'); } if (extractDescription(e, descriptionSb)) { descriptionStarted = true; } } } if (descriptionStarted) { validationResultEntries.add(new DefaultValidationResultEntry(title, descriptionSb.toString(), ValidationResultEntryType.ERROR)); } } finally { request.releaseConnection(); } return new DefaultValidationResult("WAI Validation", fileToValidate.getName(), new DefaultValidationResultType("WAI"), validationResultEntries); }
From source file:functionaltests.RestSchedulerJobTaskTest.java
@Test public void testUrlMatrixParamsShouldReplaceJobVariables() throws Exception { File jobFile = new File(RestSchedulerJobTaskTest.class.getResource("config/job_matrix_params.xml").toURI()); String schedulerUrl = getResourceUrl("submit;var=matrix_param_val"); HttpPost httpPost = new HttpPost(schedulerUrl); setSessionHeader(httpPost); MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().addPart("file", new FileBody(jobFile, ContentType.APPLICATION_XML)); httpPost.setEntity(multipartEntityBuilder.build()); HttpResponse response = executeUriRequest(httpPost); assertHttpStatusOK(response);/*w w w .j a v a 2 s. co m*/ JSONObject jsonObj = toJsonObject(response); final String jobId = jsonObj.get("id").toString(); assertNotNull(jobId); waitJobState(jobId, JobStatus.FINISHED, TimeUnit.MINUTES.toMillis(1)); }
From source file:iqq.im.service.ApacheHttpService.java
@Override public Future<QQHttpResponse> executeHttpRequest(QQHttpRequest request, QQHttpListener listener) throws QQException { try {// w ww .j av a2 s.c o m URI uri = URI.create(request.getUrl()); if (request.getMethod().equals("POST")) { HttpPost httppost = new HttpPost(uri); HttpHost httphost = URIUtils.extractHost(uri); if (httphost == null) { LOG.error("host is null, url: " + uri.toString()); httphost = new HttpHost(uri.getHost()); } if (request.getReadTimeout() > 0) { HttpConnectionParams.setSoTimeout(httppost.getParams(), request.getReadTimeout()); } if (request.getConnectTimeout() > 0) { HttpConnectionParams.setConnectionTimeout(httppost.getParams(), request.getConnectTimeout()); } if (request.getFileMap().size() > 0) { MultipartEntity entity = new MultipartEntity(); String charset = request.getCharset(); Map<String, String> postMap = request.getPostMap(); for (String key : postMap.keySet()) { String value = postMap.get(key); value = value == null ? "" : value; entity.addPart(key, new StringBody(value, Charset.forName(charset))); } Map<String, File> fileMap = request.getFileMap(); for (String key : fileMap.keySet()) { File value = fileMap.get(key); entity.addPart(new FormBodyPart(key, new FileBody(value, getMimeType(value)))); } httppost.setEntity(entity); } else if (request.getPostMap().size() > 0) { List<NameValuePair> list = new ArrayList<NameValuePair>(); Map<String, String> postMap = request.getPostMap(); for (String key : postMap.keySet()) { String value = postMap.get(key); value = value == null ? "" : value; list.add(new BasicNameValuePair(key, value)); } httppost.setEntity(new UrlEncodedFormEntity(list, request.getCharset())); } Map<String, String> headerMap = request.getHeaderMap(); for (String key : headerMap.keySet()) { httppost.addHeader(key, headerMap.get(key)); } QQHttpPostRequestProducer producer = new QQHttpPostRequestProducer(httphost, httppost, listener); QQHttpResponseConsumer consumer = new QQHttpResponseConsumer(request, listener, cookieJar); QQHttpResponseCallback callback = new QQHttpResponseCallback(listener); Future<QQHttpResponse> future = asyncHttpClient.execute(producer, consumer, callback); return new ProxyFuture(future, consumer, producer); } else if (request.getMethod().equals("GET")) { HttpGet httpget = new HttpGet(uri); HttpHost httphost = URIUtils.extractHost(uri); if (httphost == null) { LOG.error("host is null, url: " + uri.toString()); httphost = new HttpHost(uri.getHost()); } Map<String, String> headerMap = request.getHeaderMap(); for (String key : headerMap.keySet()) { httpget.addHeader(key, headerMap.get(key)); } if (request.getReadTimeout() > 0) { HttpConnectionParams.setSoTimeout(httpget.getParams(), request.getReadTimeout()); } if (request.getConnectTimeout() > 0) { HttpConnectionParams.setConnectionTimeout(httpget.getParams(), request.getConnectTimeout()); } return asyncHttpClient.execute(new QQHttpGetRequestProducer(httphost, httpget), new QQHttpResponseConsumer(request, listener, cookieJar), new QQHttpResponseCallback(listener)); } else { throw new QQException(QQErrorCode.IO_ERROR, "not support http method:" + request.getMethod()); } } catch (IOException e) { throw new QQException(QQErrorCode.IO_ERROR); } }
From source file:org.openbmap.soapclient.AsyncUploader.java
/** * Sends an authenticated http post request to upload file * @param file File to upload (full path) * @return true on response code 200, false otherwise *//*from www . j a v a 2 s . c om*/ private UploadResult httpPostRequest(final String file) { // TODO check network state // @see http://developer.android.com/training/basics/network-ops/connecting.html // Adjust HttpClient parameters final HttpParams httpParameters = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. // The default value is zero, that means the timeout is not used. // HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECTION_TIMEOUT); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. //HttpConnectionParams.setSoTimeout(httpParameters, SOCKET_TIMEOUT); final DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters); final HttpPost httppost = new HttpPost(mServer); try { final MultipartEntity entity = new MultipartEntity(); entity.addPart(FILE_FIELD, new FileBody(new File(file), "text/xml")); if ((mUser != null) && (mPassword != null)) { final String authorizationString = "Basic " + Base64.encodeToString((mUser + ":" + mPassword).getBytes(), Base64.NO_WRAP); httppost.setHeader("Authorization", authorizationString); } if (mToken != null) { entity.addPart(API_FIELD, new StringBody(mToken)); } httppost.setEntity(entity); final HttpResponse response = httpclient.execute(httppost); final int reply = response.getStatusLine().getStatusCode(); if (reply == 200) { // everything is ok if we receive HTTP 200 mSize = entity.getContentLength(); Log.i(TAG, "Uploaded " + file + ": Server reply " + reply); return UploadResult.OK; } else if (reply == 401) { Log.e(TAG, "Wrong username or password"); return UploadResult.WRONG_PASSWORD; } else { Log.w(TAG, "Error while uploading" + file + ": Server reply " + reply); return UploadResult.ERROR; } // TODO: redirects (301, 302) are NOT handled here // thus if something changes on the server side we're dead here } catch (final ClientProtocolException e) { Log.e(TAG, e.getMessage()); } catch (final IOException e) { Log.e(TAG, "I/O exception on file " + file); } return UploadResult.UNDEFINED; }
From source file:com.tek271.reverseProxy.servlet.ProxyFilter.java
private static MultipartEntity getMultipartEntity(HttpServletRequest request) { MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); Enumeration<String> en = request.getParameterNames(); while (en.hasMoreElements()) { String name = en.nextElement(); String value = request.getParameter(name); try {/*from w ww. j av a 2 s. com*/ if (name.equals("file")) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(10000000);// 10 Mo List items = upload.parseRequest(request); Iterator itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); File file = new File(item.getName()); FileOutputStream fos = new FileOutputStream(file); fos.write(item.get()); fos.flush(); fos.close(); entity.addPart(name, new FileBody(file, "application/zip")); } } else { entity.addPart(name, new StringBody(value.toString(), "text/plain", Charset.forName("UTF-8"))); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (FileUploadException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (FileNotFoundException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } return entity; }
From source file:code.google.restclient.client.HitterClient.java
private MultipartEntity getMultipartEntity(ViewRequest req) throws RCException { MultipartEntity reqEntity = new MultipartEntity(); Map<String, String> params = req.getParams(); String paramValue = null;//w w w . j a va2s. co m StringBody stringBody = null; try { for (String paramName : params.keySet()) { paramValue = params.get(paramName); stringBody = new StringBody(paramValue, Charset.forName(RCConstants.DEFAULT_CHARSET)); reqEntity.addPart(paramName, stringBody); } String fileParamName = req.getFileParamName(); File selectedFile = new File(req.getFilePath()); if (selectedFile.exists() && !RCUtil.isEmpty(fileParamName)) { String mimeType = MimeTypeUtil.getMimeType(req.getFilePath()); FileBody fileBody = new FileBody(selectedFile, mimeType); reqEntity.addPart(fileParamName, fileBody); } } catch (UnsupportedEncodingException e) { throw new RCException( "getMultipartEntity(): Could not prepare multipart entity due to unsupported encoding", e); } return reqEntity; }