Search in sources :

Example 76 with DiskFileItemFactory

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);
    }
}
Also used : Locale(java.util.Locale) Study(org.akaza.openclinica.domain.datamap.Study) FileProperties(org.akaza.openclinica.bean.rule.FileProperties) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) IOException(java.io.IOException) OpenClinicaSystemException(org.akaza.openclinica.exception.OpenClinicaSystemException) Errors(org.springframework.validation.Errors) FileItem(org.apache.commons.fileupload.FileItem) ResponseEntity(org.springframework.http.ResponseEntity) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) DataBinder(org.springframework.validation.DataBinder) File(java.io.File) PFormCache(org.akaza.openclinica.web.pform.PFormCache) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 77 with DiskFileItemFactory

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();
    }
}
Also used : InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileItemStream(org.apache.commons.fileupload.FileItemStream) FileOutputStream(java.io.FileOutputStream) File(java.io.File) FileItemIterator(org.apache.commons.fileupload.FileItemIterator) FileUploadException(org.apache.commons.fileupload.FileUploadException) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 78 with DiskFileItemFactory

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;
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) File(java.io.File) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 79 with DiskFileItemFactory

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());
// }
}
Also used : FileItem(org.apache.commons.fileupload.FileItem) ApplicationContext(org.springframework.context.ApplicationContext) IRecorderService(org.cerberus.engine.execution.IRecorderService) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileSizeLimitExceededException(org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException) TestCaseStepActionExecution(org.cerberus.crud.entity.TestCaseStepActionExecution) IParameterService(org.cerberus.crud.service.IParameterService) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 80 with DiskFileItemFactory

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();
}
Also used : PolicyFactory(org.owasp.html.PolicyFactory) HashMap(java.util.HashMap) MessageEvent(org.cerberus.engine.entity.MessageEvent) JSONArray(org.json.JSONArray) Gson(com.google.gson.Gson) TestCaseStepActionExecution(org.cerberus.crud.entity.TestCaseStepActionExecution) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItemFactory(org.apache.commons.fileupload.FileItemFactory) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) Answer(org.cerberus.util.answer.Answer) FileItem(org.apache.commons.fileupload.FileItem) ApplicationContext(org.springframework.context.ApplicationContext) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) IRecorderService(org.cerberus.engine.execution.IRecorderService) JSONObject(org.json.JSONObject) TestCaseStepActionControlExecution(org.cerberus.crud.entity.TestCaseStepActionControlExecution) ILogEventService(org.cerberus.crud.service.ILogEventService) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Aggregations

DiskFileItemFactory (org.apache.commons.fileupload.disk.DiskFileItemFactory)91 ServletFileUpload (org.apache.commons.fileupload.servlet.ServletFileUpload)85 FileItem (org.apache.commons.fileupload.FileItem)73 FileUploadException (org.apache.commons.fileupload.FileUploadException)50 File (java.io.File)44 IOException (java.io.IOException)32 HashMap (java.util.HashMap)24 FileItemFactory (org.apache.commons.fileupload.FileItemFactory)24 List (java.util.List)22 ArrayList (java.util.ArrayList)21 InputStream (java.io.InputStream)19 ServletException (javax.servlet.ServletException)15 HttpServletRequest (javax.servlet.http.HttpServletRequest)10 ServletRequestContext (org.apache.commons.fileupload.servlet.ServletRequestContext)9 Locale (java.util.Locale)8 JSONObject (org.json.JSONObject)8 ApplicationContext (org.springframework.context.ApplicationContext)8 UnsupportedEncodingException (java.io.UnsupportedEncodingException)7 Iterator (java.util.Iterator)7 Map (java.util.Map)7