Search in sources :

Example 66 with FileUploadException

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

the class CreateTestDataLib 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 {
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    IFactoryTestDataLibData tdldFactory = appContext.getBean(IFactoryTestDataLibData.class);
    ITestDataLibDataService tdldService = appContext.getBean(ITestDataLibDataService.class);
    IParameterService parameterService = appContext.getBean(IParameterService.class);
    JSONObject jsonResponse = new JSONObject();
    Answer ans = new Answer();
    AnswerItem ansItem = new AnswerItem();
    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();
    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();
    }
    try {
        /**
         * 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 test = fileData.get("subdataCheck");
        /**
         * Checking all constrains before calling the services.
         */
        // Prepare the final answer.
        MessageEvent msg1 = new MessageEvent(MessageEventEnum.GENERIC_OK);
        Answer finalAnswer = new Answer(msg1);
        if (StringUtil.isNullOrEmpty(name)) {
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
            msg.setDescription(msg.getDescription().replace("%ITEM%", "Test Data Library").replace("%OPERATION%", "Create").replace("%REASON%", "Test data library name is missing! "));
            finalAnswer.setResultMessage(msg);
        } else {
            /**
             * All data seems cleans so we can call the services.
             */
            ITestDataLibService libService = appContext.getBean(ITestDataLibService.class);
            IFactoryTestDataLib factoryLibService = appContext.getBean(IFactoryTestDataLib.class);
            TestDataLib lib = factoryLibService.create(0, name, system, environment, country, group, type, database, script, databaseUrl, service, servicePath, method, envelope, databaseCsv, csvUrl, separator, description, request.getRemoteUser(), null, "", null, null, null, null, null);
            // Creates the entries and the subdata list
            ansItem = libService.create(lib);
            finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ansItem);
            /**
             * Object created. Adding Log entry.
             */
            if (ansItem.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                ILogEventService logEventService = appContext.getBean(LogEventService.class);
                logEventService.createForPrivateCalls("/CreateTestDataLib", "CREATE", "Create TestDataLib  : " + request.getParameter("name"), request);
            }
            List<TestDataLibData> tdldList = new ArrayList();
            TestDataLib dataLibWithUploadedFile = (TestDataLib) ansItem.getItem();
            if (file != null) {
                ans = libService.uploadFile(dataLibWithUploadedFile.getTestDataLibID(), file);
                if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                    dataLibWithUploadedFile.setCsvUrl(File.separator + dataLibWithUploadedFile.getTestDataLibID() + File.separator + file.getName());
                    libService.update(dataLibWithUploadedFile);
                }
            }
            // Getting list of SubData from JSON Call
            if (fileData.get("subDataList") != null) {
                JSONArray objSubDataArray = new JSONArray(fileData.get("subDataList"));
                tdldList = getSubDataFromParameter(request, appContext, dataLibWithUploadedFile.getTestDataLibID(), objSubDataArray);
            }
            if (file != null && test.equals("1")) {
                String firstLine = "";
                String secondLine = "";
                try (BufferedReader reader = new BufferedReader(new FileReader(parameterService.getParameterStringByKey("cerberus_testdatalibCSV_path", "", null) + lib.getCsvUrl()))) {
                    firstLine = reader.readLine();
                    secondLine = reader.readLine();
                    String[] firstLineSubData = (!dataLibWithUploadedFile.getSeparator().isEmpty()) ? firstLine.split(dataLibWithUploadedFile.getSeparator()) : firstLine.split(",");
                    String[] secondLineSubData = (!dataLibWithUploadedFile.getSeparator().isEmpty()) ? secondLine.split(dataLibWithUploadedFile.getSeparator()) : secondLine.split(",");
                    int i = 0;
                    int y = 1;
                    TestDataLibData firstLineLibData = tdldList.get(0);
                    tdldList = new ArrayList();
                    if (StringUtil.isNullOrEmpty(firstLineLibData.getColumnPosition())) {
                        firstLineLibData.setColumnPosition("1");
                    }
                    if (StringUtil.isNullOrEmpty(firstLineLibData.getValue())) {
                        firstLineLibData.setValue(secondLineSubData[0]);
                    }
                    if (StringUtil.isNullOrEmpty(firstLineLibData.getColumn())) {
                        firstLineLibData.setColumn(firstLineSubData[0]);
                    }
                    tdldList.add(firstLineLibData);
                    for (String item : firstLineSubData) {
                        TestDataLibData tdld = tdldFactory.create(null, dataLibWithUploadedFile.getTestDataLibID(), item + "_" + y, secondLineSubData[i], item, null, Integer.toString(y), null);
                        tdldList.add(tdld);
                        i++;
                        y++;
                    }
                // Update the Database with the new list.
                } finally {
                    try {
                        file.getInputStream().close();
                    } catch (Throwable ignore) {
                    }
                }
            }
            ans = tdldService.compareListAndUpdateInsertDeleteElements(dataLibWithUploadedFile.getTestDataLibID(), tdldList);
            finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
        }
        /**
         * Formating and returning the json result.
         */
        // sets the message returned by the operations
        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);
        response.getWriter().print(AnswerUtil.createGenericErrorAnswer());
        response.getWriter().flush();
    }
}
Also used : PolicyFactory(org.owasp.html.PolicyFactory) HashMap(java.util.HashMap) MessageEvent(org.cerberus.engine.entity.MessageEvent) IFactoryTestDataLibData(org.cerberus.crud.factory.IFactoryTestDataLibData) 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) FileReader(java.io.FileReader) TestDataLib(org.cerberus.crud.entity.TestDataLib) IFactoryTestDataLib(org.cerberus.crud.factory.IFactoryTestDataLib) IFactoryTestDataLib(org.cerberus.crud.factory.IFactoryTestDataLib) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) AnswerItem(org.cerberus.util.answer.AnswerItem) 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) 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 67 with FileUploadException

use of org.apache.commons.fileupload.FileUploadException in project canvas_course_manager by tl-its-umich-edu.

the class CourseSupportProcess method getAttachmentContent.

private String getAttachmentContent() {
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload();
    StringBuilder csv = new StringBuilder();
    try {
        // Parse the request
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            InputStream inputStream = item.openStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
            String strLine;
            while ((strLine = br.readLine()) != null) {
                String csvContent = strLine.trim();
                csv.append(csvContent);
                csv.append(Utils.CONSTANT_LINE_FEED);
            }
            M_log.debug(csv);
        }
    } catch (FileUploadException | IOException e) {
        M_log.error("Error getting attachment content from the UI due to " + e.getMessage());
        return null;
    } catch (Exception e) {
        M_log.error("Error getting attachment content from the UI due to " + e.getMessage());
        return null;
    }
    return csv.toString();
}
Also used : ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileItemStream(org.apache.commons.fileupload.FileItemStream) FileItemIterator(org.apache.commons.fileupload.FileItemIterator) FileUploadException(org.apache.commons.fileupload.FileUploadException) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 68 with FileUploadException

use of org.apache.commons.fileupload.FileUploadException in project wicket by apache.

the class Form method handleMultiPart.

/**
 * Handles multi-part processing of the submitted data. <h3>
 * WARNING</h3> If this method is overridden it can break {@link FileUploadField}s on this form
 *
 * @return false if form is multipart and upload failed
 */
protected boolean handleMultiPart() {
    if (isMultiPart()) {
        // parsed out correctly
        try {
            ServletWebRequest request = (ServletWebRequest) getRequest();
            final MultipartServletWebRequest multipartWebRequest = request.newMultipartWebRequest(getMaxSize(), getPage().getId());
            multipartWebRequest.setFileMaxSize(getFileMaxSize());
            multipartWebRequest.parseFileParts();
            // TODO: Can't this be detected from header?
            getRequestCycle().setRequest(multipartWebRequest);
        } catch (final FileUploadException fux) {
            // Create model with exception and maximum size values
            final Map<String, Object> model = new HashMap<>();
            model.put("exception", fux);
            model.put("maxSize", getMaxSize());
            model.put("fileMaxSize", getFileMaxSize());
            onFileUploadException(fux, model);
            // don't process the form if there is a FileUploadException
            return false;
        }
    }
    return true;
}
Also used : MultipartServletWebRequest(org.apache.wicket.protocol.http.servlet.MultipartServletWebRequest) MultipartServletWebRequest(org.apache.wicket.protocol.http.servlet.MultipartServletWebRequest) ServletWebRequest(org.apache.wicket.protocol.http.servlet.ServletWebRequest) HashMap(java.util.HashMap) Map(java.util.Map) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 69 with FileUploadException

use of org.apache.commons.fileupload.FileUploadException in project wicket by apache.

the class AjaxFileDropBehavior method onEvent.

@Override
protected void onEvent(AjaxRequestTarget target) {
    try {
        ServletWebRequest request = (ServletWebRequest) getComponent().getRequest();
        final MultipartServletWebRequest multipartWebRequest = request.newMultipartWebRequest(getMaxSize(), getComponent().getPage().getId());
        multipartWebRequest.setFileMaxSize(getFileMaxSize());
        multipartWebRequest.parseFileParts();
        // TODO: Can't this be detected from header?
        getComponent().getRequestCycle().setRequest(multipartWebRequest);
        ArrayList<FileUpload> fileUploads = new ArrayList<>();
        // Get the item for the path
        final List<FileItem> fileItems = multipartWebRequest.getFile(parameterName);
        if (fileItems != null) {
            for (FileItem item : fileItems) {
                fileUploads.add(new FileUpload(item));
            }
        }
        onFileUpload(target, fileUploads);
    } catch (final FileUploadException fux) {
        onError(target, fux);
    }
}
Also used : FileItem(org.apache.commons.fileupload.FileItem) MultipartServletWebRequest(org.apache.wicket.protocol.http.servlet.MultipartServletWebRequest) ArrayList(java.util.ArrayList) MultipartServletWebRequest(org.apache.wicket.protocol.http.servlet.MultipartServletWebRequest) ServletWebRequest(org.apache.wicket.protocol.http.servlet.ServletWebRequest) FileUpload(org.apache.wicket.markup.html.form.upload.FileUpload) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 70 with FileUploadException

use of org.apache.commons.fileupload.FileUploadException in project wicket by apache.

the class MultipartServletWebRequestImpl method newMultipartWebRequest.

@Override
public MultipartServletWebRequest newMultipartWebRequest(Bytes maxSize, String upload) throws FileUploadException {
    // FIXME mgrigorov: Why these checks are made here ?!
    // Why they are not done also at org.apache.wicket.protocol.http.servlet.MultipartServletWebRequestImpl.newMultipartWebRequest(org.apache.wicket.util.lang.Bytes, java.lang.String, org.apache.wicket.util.upload.FileItemFactory)() ?
    // Why there is no check that the summary of all files' sizes is less than the set maxSize ?
    // Setting a breakpoint here never breaks with the standard upload examples.
    Bytes fileMaxSize = getFileMaxSize();
    for (Map.Entry<String, List<FileItem>> entry : files.entrySet()) {
        List<FileItem> fileItems = entry.getValue();
        for (FileItem fileItem : fileItems) {
            if (fileMaxSize != null && fileItem.getSize() > fileMaxSize.bytes()) {
                String fieldName = entry.getKey();
                FileUploadException fslex = new FileUploadBase.FileSizeLimitExceededException("The field '" + fieldName + "' exceeds its maximum permitted size of '" + maxSize + "' characters.", fileItem.getSize(), fileMaxSize.bytes());
                throw fslex;
            }
        }
    }
    return this;
}
Also used : Bytes(org.apache.wicket.util.lang.Bytes) FileItem(org.apache.commons.fileupload.FileItem) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) ValueMap(org.apache.wicket.util.value.ValueMap) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Aggregations

FileUploadException (org.apache.commons.fileupload.FileUploadException)88 ServletFileUpload (org.apache.commons.fileupload.servlet.ServletFileUpload)65 FileItem (org.apache.commons.fileupload.FileItem)57 DiskFileItemFactory (org.apache.commons.fileupload.disk.DiskFileItemFactory)51 IOException (java.io.IOException)37 HashMap (java.util.HashMap)27 ArrayList (java.util.ArrayList)22 List (java.util.List)21 File (java.io.File)20 InputStream (java.io.InputStream)19 FileItemIterator (org.apache.commons.fileupload.FileItemIterator)19 FileItemStream (org.apache.commons.fileupload.FileItemStream)19 FileItemFactory (org.apache.commons.fileupload.FileItemFactory)16 ServletException (javax.servlet.ServletException)12 Map (java.util.Map)9 HttpServletRequest (javax.servlet.http.HttpServletRequest)9 Iterator (java.util.Iterator)8 ApplicationContext (org.springframework.context.ApplicationContext)8 UnsupportedEncodingException (java.io.UnsupportedEncodingException)6 HttpServletResponse (javax.servlet.http.HttpServletResponse)6