use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project OpenClinica by OpenClinica.
the class OpenRosaSubmissionController method doSubmission.
/**
* @api {post} /pages/api/v1/editform/:studyOid/submission Submit form data
* @apiName doSubmission
* @apiPermission admin
* @apiVersion 3.8.0
* @apiParam {String} studyOid Study Oid.
* @apiParam {String} ecid Key that will be used to look up subject context information while processing submission.
* @apiGroup Form
* @apiDescription Submits the data from a completed form.
*/
@RequestMapping(value = "/{studyOID}/submission", method = RequestMethod.POST)
public ResponseEntity<String> doSubmission(HttpServletRequest request, HttpServletResponse response, @PathVariable("studyOID") String studyOID, @RequestParam(FORM_CONTEXT) String ecid) {
logger.info("Processing xform submission.");
HashMap<String, String> subjectContext = null;
Locale locale = LocaleResolver.getLocale(request);
DataBinder dataBinder = new DataBinder(null);
Errors errors = dataBinder.getBindingResult();
Study study = studyDao.findByOcOID(studyOID);
String requestBody = null;
HashMap<String, String> map = new HashMap();
ArrayList<HashMap> listOfUploadFilePaths = new ArrayList();
try {
// Verify Study is allowed to submit
if (!mayProceed(studyOID)) {
logger.info("Submissions to the study not allowed. Aborting submission.");
return new ResponseEntity<String>(org.springframework.http.HttpStatus.NOT_ACCEPTABLE);
}
if (ServletFileUpload.isMultipartContent(request)) {
String dir = getAttachedFilePath(studyOID);
FileProperties fileProperties = new FileProperties();
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(fileProperties.getFileSizeMax());
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items) {
if (item.getContentType() != null && !item.getFieldName().equals("xml_submission_file")) {
if (!new File(dir).exists())
new File(dir).mkdirs();
File file = processUploadedFile(item, dir);
map.put(item.getFieldName(), file.getPath());
} else if (item.getFieldName().equals("xml_submission_file")) {
requestBody = item.getString("UTF-8");
}
}
listOfUploadFilePaths.add(map);
} else {
requestBody = IOUtils.toString(request.getInputStream(), "UTF-8");
}
// Load user context from ecid
PFormCache cache = PFormCache.getInstance(context);
subjectContext = cache.getSubjectContext(ecid);
// Execute save as Hibernate transaction to avoid partial imports
openRosaSubmissionService.processRequest(study, subjectContext, requestBody, errors, locale, listOfUploadFilePaths);
} catch (Exception e) {
logger.error("Exception while processing xform submission.");
logger.error(e.getMessage());
logger.error(ExceptionUtils.getStackTrace(e));
if (!errors.hasErrors()) {
// Send a failure response
logger.info("Submission caused internal error. Sending error response.");
return new ResponseEntity<String>(org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR);
}
}
if (!errors.hasErrors()) {
// Log submission with Participate
notifier.notify(studyOID, subjectContext);
logger.info("Completed xform submission. Sending successful response");
String responseMessage = "<OpenRosaResponse xmlns=\"http://openrosa.org/http/response\">" + "<message>success</message>" + "</OpenRosaResponse>";
return new ResponseEntity<String>(responseMessage, org.springframework.http.HttpStatus.CREATED);
} else {
logger.info("Submission contained errors. Sending error response");
return new ResponseEntity<String>(org.springframework.http.HttpStatus.NOT_ACCEPTABLE);
}
}
use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project tutorials by eugenp.
the class UploadController method handleUpload.
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String handleUpload(HttpServletRequest request) {
System.out.println(System.getProperty("java.io.tmpdir"));
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);
factory.setFileCleaningTracker(null);
// Configure a repository (to ensure a secure temp location is used)
ServletFileUpload upload = new ServletFileUpload(factory);
try {
// Parse the request
List<FileItem> items = upload.parseRequest(request);
// Process the uploaded items
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = iter.next();
if (!item.isFormField()) {
try (InputStream uploadedStream = item.getInputStream();
OutputStream out = new FileOutputStream("file.mov")) {
IOUtils.copy(uploadedStream, out);
out.close();
}
}
}
// Parse the request with Streaming API
upload = new ServletFileUpload();
FileItemIterator iterStream = upload.getItemIterator(request);
while (iterStream.hasNext()) {
FileItemStream item = iterStream.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
if (!item.isFormField()) {
// Process the InputStream
} else {
// process form fields
String formFieldValue = Streams.asString(stream);
}
}
return "success!";
} catch (IOException | FileUploadException ex) {
return "failed: " + ex.getMessage();
}
}
use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project wechat by dllwh.
the class UploadUtils method initFields.
/**
* @Title:initFields
* @Description:处理上传内容
* @param request
* @return:void 返回类型
*/
@SuppressWarnings("unchecked")
private static Map<String, Object> initFields(HttpServletRequest request) {
// 存储表单字段和非表单字段
Map<String, Object> resultMap = new HashMap<String, Object>();
// 第一步:判断request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
// 第二步:解析request
if (isMultipart) {
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// 阀值,超过这个值才会写到临时目录,否则在内存中
factory.setSizeThreshold(1024 * 1024 * 10);
factory.setRepository(new File(tempPath));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
// 最大上传限制
upload.setSizeMax(maxSize);
/* FileItem */
List<FileItem> items = null;
// Parse the request
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}
// 第3步:处理uploaded items
if (items != null && items.size() > 0) {
Iterator<FileItem> iter = items.iterator();
// 文件域对象
List<FileItem> list = new ArrayList<FileItem>();
// 表单字段
Map<String, String> fields = new HashMap<String, String>();
while (iter.hasNext()) {
FileItem item = iter.next();
// 处理所有表单元素和文件域表单元素
if (item.isFormField()) {
// 表单元素
String name = item.getFieldName();
String value = item.getString();
fields.put(name, value);
} else {
// 文件域表单元素
list.add(item);
}
}
resultMap.put(FORM_FIELDS, fields);
resultMap.put(FILE_FIELDS, list);
}
}
return resultMap;
}
use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project cerberus-source by cerberustesting.
the class SaveManualExecutionPicture method doPost.
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// using commons-fileupload http://commons.apache.org/proper/commons-fileupload/using.html
ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
// Collection<Part> parts = req.getParts(); //for sevlet 3.0, in glassfish 2.x does not work
TestCaseStepActionExecution tcsae = new TestCaseStepActionExecution();
FileItem uploadedFile = null;
// if is multipart we need to handle the upload data
IParameterService parameterService = appContext.getBean(IParameterService.class);
IRecorderService recorderService = appContext.getBean(IRecorderService.class);
DiskFileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
Integer imgPathMaxSize = parameterService.getParameterIntegerByKey("cerberus_screenshot_max_size", "", UPLOAD_PICTURE_MAXSIZE);
// Set overall request size constraint
// max size for the file
upload.setFileSizeMax(imgPathMaxSize);
try {
// Parse the request
List<FileItem> items = upload.parseRequest(req);
// Process the uploaded items
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = iter.next();
if (item.isFormField()) {
tcsae = processFormField(tcsae, item);
} else {
// uploadFileName = processUploadedFile(item);
uploadedFile = item;
}
}
// this handles an action each time
} catch (FileSizeLimitExceededException ex) {
LOG.warn("File size exceed the limit: " + ex.toString());
} catch (FileUploadException ex) {
LOG.warn("Exception occurred while uploading file: " + ex.toString());
}
if (uploadedFile != null) {
if (uploadedFile.getContentType().startsWith("image/")) {
// TODO:FN verify if this is the best approach or if we should
// check if the mime types for images can be configured in the web.xml and then obtain the valid mime types from the servletContext
// getServletContext().getMimeType(fileName);
recorderService.recordUploadedFile(tcsae.getId(), tcsae, uploadedFile);
} else {
LOG.warn("Problem with the file you're trying to upload. It is not an image." + "Name: " + uploadedFile.getName() + "; Content-type: " + uploadedFile.getContentType());
}
}
// old version : TODO to be deleted after testing
// Collection<Part> parts = req.getParts();
// String runId = req.getParameter("runId");
// String test = req.getParameter("picTest");
// String testCase = req.getParameter("picTestCase");
// String step = req.getParameter("pictStep");
// String action = req.getParameter("pictAction");
// String control = req.getParameter("pictControl") == null ? "" : req.getParameter("pictControl");
// String returnCode = req.getParameter("returnCode");
//
// ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
// IParameterService parameterService = appContext.getBean(IParameterService.class);
// // ITestCaseStepExecutionService testCaseStepExecutionService = appContext.getBean(ITestCaseStepExecutionService.class);
// // ITestCaseStepActionExecutionService testCaseStepActionExecutionService = appContext.getBean(ITestCaseStepActionExecutionService.class);
//
// try {
// String imgPath = parameterService.findParameterByKey("cerberus_exeautomedia_path", "").getValue();
//
// File dir = new File(imgPath + runId);
// dir.mkdirs();
//
// int seq = 1;
// long runID = ParameterParserUtil.parseLongParam(runId, 0);
// //TestCaseStepActionExecution testCaseStepActionExecution = new TestCaseStepActionExecution();
// for (Part p : parts) {
// if (p.getName().equalsIgnoreCase("files[]")) {
// if (seq == 1) {
// // TestCaseStepExecution tcse = new TestCaseStepExecution();
// // tcse.setId(runID);
// // tcse.setTest(test);
// // tcse.setTestCase(testCase);
// // tcse.setStep(1);
// // testCaseStepExecutionService.insertTestCaseStepExecution(tcse);
// }
//
// InputStream inputStream = p.getInputStream();
// String controlName = control.equals("") ? "" : "Ct"+control;
// String name = test + "-" + testCase + "-St"+step+"Sq" + action + controlName + ".jpg";
// OutputStream outputStream = new FileOutputStream(new File(this.buildScreenshotPath(imgPath, runId, name)));
//
// int read;
// byte[] bytes = new byte[1024];
// while ((read = inputStream.read(bytes)) != -1) {
// outputStream.write(bytes, 0, read);
// }
// outputStream.close();
//
// Date now = new Date();
//
// //create action
// // testCaseStepActionExecution.setId(runID);
// // testCaseStepActionExecution.setTest(test);
// // testCaseStepActionExecution.setTestCase(testCase);
// // testCaseStepActionExecution.setStep(1);
// // testCaseStepActionExecution.setSequence(seq);
// // testCaseStepActionExecution.setReturnCode(returnCode);
// // testCaseStepActionExecution.setReturnMessage("");
// // testCaseStepActionExecution.setAction("screenshot");
// // testCaseStepActionExecution.setObject("");
// // testCaseStepActionExecution.setProperty("");
// // testCaseStepActionExecution.setStart(now.getTime());
// // testCaseStepActionExecution.setEnd(now.getTime());
// // testCaseStepActionExecution.setStartLong(now.getTime());
// // testCaseStepActionExecution.setEndLong(now.getTime());
// // testCaseStepActionExecutionService.insertTestCaseStepActionExecution(testCaseStepActionExecution);
// //
// // seq++;
// }
// }
//
// } catch (CerberusException e) {
// MyLogger.log(SaveManualExecutionPicture.class.getName(), Level.ERROR, e.toString());
// }
}
use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project cerberus-source by cerberustesting.
the class CreateUpdateTestCaseExecutionFile method processRequest.
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
* @throws org.cerberus.exception.CerberusException
* @throws org.json.JSONException
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, CerberusException, JSONException {
JSONObject jsonResponse = new JSONObject();
Answer ans = new Answer();
Gson gson = new Gson();
MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
ans.setResultMessage(msg);
PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
response.setContentType("application/json");
String charset = request.getCharacterEncoding();
Map<String, String> fileData = new HashMap<String, String>();
FileItem file = null;
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> fields = upload.parseRequest(request);
Iterator<FileItem> it = fields.iterator();
if (!it.hasNext()) {
return;
}
while (it.hasNext()) {
FileItem fileItem = it.next();
boolean isFormField = fileItem.isFormField();
if (isFormField) {
fileData.put(fileItem.getFieldName(), fileItem.getString("UTF-8"));
} else {
file = fileItem;
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
/**
* Parsing and securing all required parameters
*/
// Parameter that needs to be secured --> We SECURE+DECODE them
String description = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(fileData.get("desc"), null, charset);
String extension = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(fileData.get("type"), "", charset);
String fileName = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(fileData.get("fileName"), null, charset);
Integer fileID = ParameterParserUtil.parseIntegerParam(fileData.get("fileID"), 0);
Integer idex = ParameterParserUtil.parseIntegerParam(fileData.get("idex"), 0);
boolean action = fileData.get("action") != null ? true : false;
ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
IRecorderService recorderService = appContext.getBean(IRecorderService.class);
TestCaseStepActionExecution testCaseStepActionExecution = null;
TestCaseStepActionControlExecution testCaseStepActionControlExecution = null;
JSONArray obj = null;
if (action) {
obj = new JSONArray(fileData.get("action"));
testCaseStepActionExecution = updateTestCaseStepActionExecutionFromJsonArray(obj, appContext);
} else {
obj = new JSONArray(fileData.get("control"));
testCaseStepActionControlExecution = updateTestCaseStepActionControlExecutionFromJsonArray(obj, appContext);
}
if (description.isEmpty()) {
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
msg.setDescription(msg.getDescription().replace("%ITEM%", "manual testcase execution file").replace("%OPERATION%", "Create/Update").replace("%REASON%", "desc is missing!"));
ans.setResultMessage(msg);
} else {
ans = recorderService.recordManuallyFile(testCaseStepActionExecution, testCaseStepActionControlExecution, extension, description, file, idex, fileName, fileID);
}
if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
/**
* Object created. Adding Log entry.
*/
ILogEventService logEventService = appContext.getBean(LogEventService.class);
logEventService.createForPrivateCalls("/CreateUpdateTestCaseExecutionFile", "CREATE", "Create execution file", request);
}
/**
* Formating and returning the json result.
*/
jsonResponse.put("messageType", ans.getResultMessage().getMessage().getCodeString());
jsonResponse.put("message", ans.getResultMessage().getDescription());
response.getWriter().print(jsonResponse);
response.getWriter().flush();
}
Aggregations