Search in sources :

Example 6 with FileItemFactory

use of org.apache.commons.fileupload.FileItemFactory in project openmrs-core by openmrs.

the class StartupErrorFilter method doPost.

/**
 * @see org.openmrs.web.filter.StartupFilter#doPost(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 */
@Override
protected void doPost(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException, ServletException {
    // if they are uploading modules
    if (getModel().errorAtStartup instanceof OpenmrsCoreModuleException) {
        RequestContext requestContext = new ServletRequestContext(httpRequest);
        if (!ServletFileUpload.isMultipartContent(requestContext)) {
            throw new ServletException("The request is not a valid multipart/form-data upload request");
        }
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            Context.openSession();
            List<FileItem> items = upload.parseRequest(requestContext);
            for (FileItem item : items) {
                InputStream uploadedStream = item.getInputStream();
                ModuleUtil.insertModuleFile(uploadedStream, item.getName());
            }
        } catch (FileUploadException ex) {
            throw new ServletException("Error while uploading file(s)", ex);
        } finally {
            Context.closeSession();
        }
        Map<String, Object> map = new HashMap<>();
        map.put("success", Boolean.TRUE);
        renderTemplate("coremoduleerror.vm", map, httpResponse);
    // TODO restart openmrs here instead of going to coremodulerror template
    }
}
Also used : HashMap(java.util.HashMap) InputStream(java.io.InputStream) ServletRequestContext(org.apache.commons.fileupload.servlet.ServletRequestContext) OpenmrsCoreModuleException(org.openmrs.module.OpenmrsCoreModuleException) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItemFactory(org.apache.commons.fileupload.FileItemFactory) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) ServletException(javax.servlet.ServletException) FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) ServletRequestContext(org.apache.commons.fileupload.servlet.ServletRequestContext) RequestContext(org.apache.commons.fileupload.RequestContext) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 7 with FileItemFactory

use of org.apache.commons.fileupload.FileItemFactory in project cerberus-source by cerberustesting.

the class UpdateTestDataLib 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
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    JSONObject jsonResponse = new JSONObject();
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    Answer ans = new Answer();
    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);
    String charset = request.getCharacterEncoding();
    IFactoryTestDataLibData tdldFactory = appContext.getBean(IFactoryTestDataLibData.class);
    ITestDataLibDataService tdldService = appContext.getBean(ITestDataLibDataService.class);
    IParameterService parameterService = appContext.getBean(IParameterService.class);
    response.setContentType("application/json");
    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(), ParameterParserUtil.parseStringParamAndDecode(fileItem.getString("UTF-8"), "", charset));
            } else {
                file = fileItem;
            }
        }
    } catch (FileUploadException e) {
        e.printStackTrace();
    }
    /**
     * Parsing and securing all required parameters.
     */
    // Parameter that are already controled by GUI (no need to decode) --> We SECURE them
    String type = policy.sanitize(fileData.get("type"));
    String system = policy.sanitize(fileData.get("system"));
    String environment = policy.sanitize(fileData.get("environment"));
    String country = policy.sanitize(fileData.get("country"));
    String database = policy.sanitize(fileData.get("database"));
    String databaseUrl = policy.sanitize(fileData.get("databaseUrl"));
    String databaseCsv = policy.sanitize(fileData.get("databaseCsv"));
    // Parameter that needs to be secured --> We SECURE+DECODE them
    // this is mandatory
    String name = fileData.get("name");
    String group = fileData.get("group");
    String description = fileData.get("libdescription");
    String service = fileData.get("service");
    // Parameter that we cannot secure as we need the html --> We DECODE them
    String script = fileData.get("script");
    String servicePath = fileData.get("servicepath");
    String method = fileData.get("method");
    String envelope = fileData.get("envelope");
    String csvUrl = fileData.get("csvUrl");
    String separator = fileData.get("separator");
    String activateAutoSubdata = fileData.get("subdataCheck");
    Integer testdatalibid = 0;
    boolean testdatalibid_error = true;
    try {
        if (fileData.get("testdatalibid") != null && !fileData.get("testdatalibid").isEmpty()) {
            testdatalibid = Integer.valueOf(fileData.get("testdatalibid"));
            testdatalibid_error = false;
        }
    } catch (NumberFormatException ex) {
        testdatalibid_error = true;
        LOG.warn(ex);
    }
    try {
        // Prepare the final answer.
        MessageEvent msg1 = new MessageEvent(MessageEventEnum.GENERIC_OK);
        Answer finalAnswer = new Answer(msg1);
        /**
         * Checking all constrains before calling the services.
         */
        if (StringUtil.isNullOrEmpty(name)) {
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
            msg.setDescription(msg.getDescription().replace("%ITEM%", "Test data library").replace("%OPERATION%", "Update").replace("%REASON%", "Test data library name is missing."));
            finalAnswer.setResultMessage(msg);
        } else if (testdatalibid_error) {
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
            msg.setDescription(msg.getDescription().replace("%ITEM%", "Test data library").replace("%OPERATION%", "Update").replace("%REASON%", "Could not manage to convert testdatalibid to an integer value or testdatalibid is missing."));
            finalAnswer.setResultMessage(msg);
        } else {
            /**
             * All data seems cleans so we can call the services.
             */
            // specific attributes
            ITestDataLibService libService = appContext.getBean(ITestDataLibService.class);
            AnswerItem resp = libService.readByKey(testdatalibid);
            if (!(resp.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && resp.getItem() != null)) {
                /**
                 * Object could not be found. We stop here and report the
                 * error.
                 */
                finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) resp);
            } else {
                /**
                 * The service was able to perform the query and confirm the
                 * object exist, then we can update it.
                 */
                TestDataLib lib = (TestDataLib) resp.getItem();
                String fileName = lib.getCsvUrl();
                if (file != null) {
                    ans = libService.uploadFile(lib.getTestDataLibID(), file);
                    if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                        fileName = file.getName();
                    }
                }
                lib.setName(name);
                lib.setType(type);
                lib.setGroup(group);
                lib.setDescription(description);
                lib.setSystem(system);
                lib.setEnvironment(environment);
                lib.setCountry(country);
                lib.setDatabase(database);
                lib.setScript(script);
                lib.setDatabaseUrl(databaseUrl);
                lib.setServicePath(servicePath);
                lib.setService(service);
                lib.setMethod(method);
                lib.setEnvelope(envelope);
                lib.setDatabaseCsv(databaseCsv);
                if (file == null) {
                    lib.setCsvUrl(csvUrl);
                } else {
                    lib.setCsvUrl(File.separator + lib.getTestDataLibID() + File.separator + fileName);
                }
                lib.setSeparator(separator);
                lib.setLastModifier(request.getRemoteUser());
                ans = libService.update(lib);
                finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
                if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                    /**
                     * Update operation finished with success, then the
                     * logging entry must be added.
                     */
                    ILogEventService logEventService = appContext.getBean(LogEventService.class);
                    logEventService.createForPrivateCalls("/UpdateTestDataLib", "UPDATE", "Update TestDataLib - id: " + testdatalibid + " name: " + name + " system: " + system + " environment: " + environment + " country: " + country, request);
                }
                List<TestDataLibData> tdldList = new ArrayList();
                // Getting list of SubData from JSON Call
                if (fileData.get("subDataList") != null) {
                    JSONArray objSubDataArray = new JSONArray(fileData.get("subDataList"));
                    tdldList = getSubDataFromParameter(request, appContext, testdatalibid, objSubDataArray);
                }
                // When File has just been uploaded to servlet and flag to load the subdata value has been checked, we will parse it in order to automatically feed the subdata.
                if (file != null && activateAutoSubdata.equals("1")) {
                    String str = "";
                    try (BufferedReader reader = new BufferedReader(new FileReader(parameterService.getParameterStringByKey("cerberus_testdatalibcsv_path", "", null) + lib.getCsvUrl()))) {
                        // First line of the file is split by separator.
                        str = reader.readLine();
                        String[] subData = (!lib.getSeparator().isEmpty()) ? str.split(lib.getSeparator()) : str.split(",");
                        // We take the subdata from the servlet input.
                        TestDataLibData firstLine = tdldList.get(0);
                        tdldList = new ArrayList();
                        firstLine.setColumnPosition("1");
                        tdldList.add(firstLine);
                        int i = 1;
                        for (String item : subData) {
                            String subdataName = "SUBDATA" + i;
                            TestDataLibData tdld = tdldFactory.create(null, testdatalibid, subdataName, item, null, null, Integer.toString(i), null);
                            tdldList.add(tdld);
                            i++;
                        }
                    // Update the Database with the new list.
                    } finally {
                        try {
                            file.getInputStream().close();
                        } catch (Throwable ignore) {
                        }
                    }
                }
                ans = tdldService.compareListAndUpdateInsertDeleteElements(testdatalibid, tdldList);
                finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
            }
        }
        jsonResponse.put("messageType", finalAnswer.getResultMessage().getMessage().getCodeString());
        jsonResponse.put("message", finalAnswer.getResultMessage().getDescription());
        response.getWriter().print(jsonResponse);
        response.getWriter().flush();
    } catch (JSONException ex) {
        LOG.warn(ex);
        // returns a default error message with the json format that is able to be parsed by the client-side
        response.getWriter().print(AnswerUtil.createGenericErrorAnswer());
    }
}
Also used : PolicyFactory(org.owasp.html.PolicyFactory) HashMap(java.util.HashMap) MessageEvent(org.cerberus.engine.entity.MessageEvent) IFactoryTestDataLibData(org.cerberus.crud.factory.IFactoryTestDataLibData) ILogEventService(org.cerberus.crud.service.ILogEventService) LogEventService(org.cerberus.crud.service.impl.LogEventService) ArrayList(java.util.ArrayList) IParameterService(org.cerberus.crud.service.IParameterService) ITestDataLibDataService(org.cerberus.crud.service.ITestDataLibDataService) ApplicationContext(org.springframework.context.ApplicationContext) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) ILogEventService(org.cerberus.crud.service.ILogEventService) ArrayList(java.util.ArrayList) List(java.util.List) FileReader(java.io.FileReader) TestDataLib(org.cerberus.crud.entity.TestDataLib) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) AnswerItem(org.cerberus.util.answer.AnswerItem) 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) JSONObject(org.json.JSONObject) BufferedReader(java.io.BufferedReader) ITestDataLibService(org.cerberus.crud.service.ITestDataLibService) FileUploadException(org.apache.commons.fileupload.FileUploadException) IFactoryTestDataLibData(org.cerberus.crud.factory.IFactoryTestDataLibData) TestDataLibData(org.cerberus.crud.entity.TestDataLibData)

Example 8 with FileItemFactory

use of org.apache.commons.fileupload.FileItemFactory in project cerberus-source by cerberustesting.

the class UpdateApplicationObject 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
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, CerberusException, JSONException {
    JSONObject jsonResponse = new JSONObject();
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    Answer ans = new Answer();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    ans.setResultMessage(msg);
    String charset = request.getCharacterEncoding();
    response.setContentType("application/json");
    // Calling Servlet Transversal Util.
    ServletUtil.servletStart(request);
    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 are already controled by GUI (no need to decode) --> We SECURE them
    // Parameter that needs to be secured --> We SECURE+DECODE them
    String application = ParameterParserUtil.parseStringParamAndDecode(fileData.get("application"), null, charset);
    String object = ParameterParserUtil.parseStringParamAndDecode(fileData.get("object"), null, charset);
    String value = ParameterParserUtil.parseStringParam(fileData.get("value"), null);
    String usrmodif = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getRemoteUser(), "", charset);
    String datemodif = new Timestamp(new java.util.Date().getTime()).toString();
    // Parameter that we cannot secure as we need the html --> We DECODE them
    // Getting list of application from JSON Call
    // Prepare the final answer.
    MessageEvent msg1 = new MessageEvent(MessageEventEnum.GENERIC_OK);
    Answer finalAnswer = new Answer(msg1);
    /**
     * Checking all constrains before calling the services.
     */
    if (StringUtil.isNullOrEmpty(application)) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "ApplicationObject").replace("%OPERATION%", "Update").replace("%REASON%", "Application name (applicationobject) is missing."));
        ans.setResultMessage(msg);
    } else if (StringUtil.isNullOrEmpty(object)) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "ApplicationObject").replace("%OPERATION%", "Update").replace("%REASON%", "Object name (applicationobject) is missing."));
        ans.setResultMessage(msg);
    } else {
        /**
         * All data seems cleans so we can call the services.
         */
        IApplicationObjectService applicationObjectService = appContext.getBean(IApplicationObjectService.class);
        AnswerItem resp = applicationObjectService.readByKey(application, object);
        if (!(resp.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && resp.getItem() != null)) {
            /**
             * Object could not be found. We stop here and report the error.
             */
            finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) resp);
        } else {
            /**
             * The service was able to perform the query and confirm the
             * object exist, then we can update it.
             */
            ApplicationObject applicationData = (ApplicationObject) resp.getItem();
            String fileName = applicationData.getScreenShotFileName();
            if (file != null) {
                ans = applicationObjectService.uploadFile(applicationData.getID(), file);
                if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                    fileName = file.getName();
                }
            }
            applicationData.setValue(value);
            applicationData.setScreenShotFileName(fileName);
            applicationData.setUsrModif(usrmodif);
            applicationData.setDateModif(datemodif);
            ans = applicationObjectService.update(applicationData.getApplication(), applicationData.getObject(), applicationData);
            finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
            if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                /**
                 * Update was successful. Adding Log entry.
                 */
                ILogEventService logEventService = appContext.getBean(LogEventService.class);
                logEventService.createForPrivateCalls("/UpdateApplication", "UPDATE", "Updated Application : ['" + application + "']", request);
            }
            finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
        }
    }
    /**
     * Formating and returning the json result.
     */
    jsonResponse.put("messageType", finalAnswer.getResultMessage().getMessage().getCodeString());
    jsonResponse.put("message", finalAnswer.getResultMessage().getDescription());
    response.getWriter().print(jsonResponse);
    response.getWriter().flush();
}
Also used : MessageEvent(org.cerberus.engine.entity.MessageEvent) ApplicationObject(org.cerberus.crud.entity.ApplicationObject) ILogEventService(org.cerberus.crud.service.ILogEventService) LogEventService(org.cerberus.crud.service.impl.LogEventService) IApplicationObjectService(org.cerberus.crud.service.IApplicationObjectService) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) Timestamp(java.sql.Timestamp) AnswerItem(org.cerberus.util.answer.AnswerItem) 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) JSONObject(org.json.JSONObject) java.util(java.util) ILogEventService(org.cerberus.crud.service.ILogEventService) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 9 with FileItemFactory

use of org.apache.commons.fileupload.FileItemFactory in project cerberus-source by cerberustesting.

the class ImportTestCaseFromJson 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
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String test = "";
    String testcase = "";
    JSONObject jo = null;
    FileItem item = null;
    if (ServletFileUpload.isMultipartContent(request)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            List items = upload.parseRequest(request);
            Iterator iterator = items.iterator();
            while (iterator.hasNext()) {
                item = (FileItem) iterator.next();
                if (item.isFormField()) {
                    String name = item.getFieldName();
                    if (name.equals("test")) {
                        test = item.getString("UTF-8");
                    }
                    if (name.equals("testcase")) {
                        testcase = item.getString("UTF-8");
                    }
                } else {
                    InputStream inputStream = item.getInputStream();
                    BufferedReader streamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                    StringBuilder responseStrBuilder = new StringBuilder();
                    String inputStr;
                    while ((inputStr = streamReader.readLine()) != null) {
                        responseStrBuilder.append(inputStr);
                    }
                    inputStream.close();
                    streamReader.close();
                    jo = new JSONObject(responseStrBuilder.toString());
                }
            }
            ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
            ITestCaseService tcService = appContext.getBean(ITestCaseService.class);
            TestCase tcInfo = new TestCase();
            tcInfo.setTest(test);
            tcInfo.setTestCase(testcase);
            tcInfo.setOrigine(jo.getString("origin") == null ? "" : jo.getString("origin"));
            tcInfo.setImplementer(jo.getString("implementer") == null ? "123TOTO" : "1234TOTO");
            tcInfo.setBehaviorOrValueExpected(jo.getString("description") == null ? "1293TOTO" : "12394TOTO");
            tcService.updateTestCaseInformation(tcInfo);
            response.sendRedirect("TestCase.jsp");
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (JSONException ex) {
            LOG.warn(ex);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) JSONException(org.json.JSONException) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItemFactory(org.apache.commons.fileupload.FileItemFactory) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) JSONException(org.json.JSONException) FileUploadException(org.apache.commons.fileupload.FileUploadException) FileItem(org.apache.commons.fileupload.FileItem) ApplicationContext(org.springframework.context.ApplicationContext) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) JSONObject(org.json.JSONObject) TestCase(org.cerberus.crud.entity.TestCase) Iterator(java.util.Iterator) BufferedReader(java.io.BufferedReader) ITestCaseService(org.cerberus.crud.service.ITestCaseService) List(java.util.List) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 10 with FileItemFactory

use of org.apache.commons.fileupload.FileItemFactory in project coastal-hazards by USGS-CIDA.

the class FormUploadHandler method saveFileFromRequest.

public static File saveFileFromRequest(HttpServletRequest request, String filenameParameter, File destinationFile) throws FileUploadException, IOException {
    if (StringUtils.isBlank(filenameParameter)) {
        throw new IllegalArgumentException();
    }
    if (ServletFileUpload.isMultipartContent(request)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        FileItemIterator iter;
        iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            if (filenameParameter.toLowerCase().equals(name.toLowerCase())) {
                FileHelper.saveFileFromInputStream(item.openStream(), destinationFile);
                break;
            }
        }
    } else {
        FileHelper.saveFileFromInputStream(request.getInputStream(), destinationFile);
    }
    return destinationFile;
}
Also used : ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileItemStream(org.apache.commons.fileupload.FileItemStream) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItemIterator(org.apache.commons.fileupload.FileItemIterator) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItemFactory(org.apache.commons.fileupload.FileItemFactory)

Aggregations

FileItemFactory (org.apache.commons.fileupload.FileItemFactory)27 ServletFileUpload (org.apache.commons.fileupload.servlet.ServletFileUpload)27 DiskFileItemFactory (org.apache.commons.fileupload.disk.DiskFileItemFactory)24 FileItem (org.apache.commons.fileupload.FileItem)23 FileUploadException (org.apache.commons.fileupload.FileUploadException)16 HashMap (java.util.HashMap)9 IOException (java.io.IOException)7 ArrayList (java.util.ArrayList)6 List (java.util.List)6 JSONObject (org.json.JSONObject)6 ApplicationContext (org.springframework.context.ApplicationContext)6 File (java.io.File)5 InputStream (java.io.InputStream)5 ServletException (javax.servlet.ServletException)5 ILogEventService (org.cerberus.crud.service.ILogEventService)5 MessageEvent (org.cerberus.engine.entity.MessageEvent)5 Answer (org.cerberus.util.answer.Answer)5 Iterator (java.util.Iterator)4 AnswerItem (org.cerberus.util.answer.AnswerItem)4 BufferedReader (java.io.BufferedReader)3