Search in sources :

Example 81 with FileUploadException

use of org.apache.commons.fileupload.FileUploadException 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 82 with FileUploadException

use of org.apache.commons.fileupload.FileUploadException 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)

Example 83 with FileUploadException

use of org.apache.commons.fileupload.FileUploadException in project data-access by pentaho.

the class UploadFileDebugServlet method getFileItem.

private FileItem getFileItem(HttpServletRequest request) {
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    try {
        List items = upload.parseRequest(request);
        Iterator it = items.iterator();
        while (it.hasNext()) {
            FileItem item = (FileItem) it.next();
            if (!item.isFormField() && "uploadFormElement".equals(item.getFieldName())) {
                // $NON-NLS-1$
                return item;
            }
        }
    } catch (FileUploadException e) {
        return null;
    }
    return null;
}
Also used : FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) Iterator(java.util.Iterator) List(java.util.List) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItemFactory(org.apache.commons.fileupload.FileItemFactory) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 84 with FileUploadException

use of org.apache.commons.fileupload.FileUploadException in project nimbus by nimbus-org.

the class HttpServletRequestFileConverter method convert.

public Object convert(Object obj) throws ConvertException {
    if (!(obj instanceof HttpServletRequest)) {
        throw new ConvertException("Parameter is not instancce of HttpServletRequest.");
    }
    DiskFileItemFactory factory = new DiskFileItemFactory();
    if (repositoryPath != null) {
        factory.setRepository(new File(repositoryPath));
    }
    factory.setSizeThreshold(sizeThreshold);
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(requestSizeThreshold);
    if (headerEncoding != null) {
        upload.setHeaderEncoding(headerEncoding);
    }
    try {
        return upload.parseRequest((HttpServletRequest) obj);
    } catch (FileUploadException e) {
        throw new ConvertException(e);
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) File(java.io.File) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 85 with FileUploadException

use of org.apache.commons.fileupload.FileUploadException in project ghostdriver by detro.

the class DirectFileUploadTest method checkFileUploadCompletes.

@Test
public void checkFileUploadCompletes() throws IOException {
    WebDriver d = getDriver();
    if (!(d instanceof PhantomJSDriver)) {
        // The command under test is only available when using PhantomJS
        return;
    }
    PhantomJSDriver phantom = (PhantomJSDriver) d;
    String buttonId = "upload";
    // Create the test file for uploading
    File testFile = File.createTempFile("webdriver", "tmp");
    testFile.deleteOnExit();
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(testFile.getAbsolutePath()), "utf-8"));
    writer.write(FILE_HTML);
    writer.close();
    server.setHttpHandler("POST", new HttpRequestCallback() {

        @Override
        public void call(HttpServletRequest req, HttpServletResponse res) throws IOException {
            if (ServletFileUpload.isMultipartContent(req) && req.getPathInfo().endsWith("/upload")) {
                // Create a factory for disk-based file items
                DiskFileItemFactory factory = new DiskFileItemFactory(1024, new File(System.getProperty("java.io.tmpdir")));
                // Create a new file upload handler
                ServletFileUpload upload = new ServletFileUpload(factory);
                // Parse the request
                List<FileItem> items;
                try {
                    items = upload.parseRequest(req);
                } catch (FileUploadException fue) {
                    throw new IOException(fue);
                }
                res.setHeader("Content-Type", "text/html; charset=UTF-8");
                InputStream is = items.get(0).getInputStream();
                OutputStream os = res.getOutputStream();
                IOUtils.copy(is, os);
                os.write("<script>window.top.window.onUploadDone();</script>".getBytes());
                IOUtils.closeQuietly(is);
                IOUtils.closeQuietly(os);
                return;
            }
            res.sendError(400);
        }
    });
    // Upload the temp file
    phantom.get(server.getBaseUrl() + "/common/upload.html");
    phantom.executePhantomJS("var page = this; page.uploadFile('input#" + buttonId + "', '" + testFile.getAbsolutePath() + "');");
    phantom.findElement(By.id("go")).submit();
    // Uploading files across a network may take a while, even if they're really small.
    // Wait for the loading label to disappear.
    WebDriverWait wait = new WebDriverWait(phantom, 10);
    wait.until(ExpectedConditions.invisibilityOfElementLocated(By.id("upload_label")));
    phantom.switchTo().frame("upload_target");
    wait = new WebDriverWait(phantom, 5);
    wait.until(ExpectedConditions.textToBePresentInElementLocated(By.xpath("//body"), LOREM_IPSUM_TEXT));
    // Navigate after file upload to verify callbacks are properly released.
    phantom.get("http://www.google.com/");
}
Also used : WebDriver(org.openqa.selenium.WebDriver) PhantomJSDriver(org.openqa.selenium.phantomjs.PhantomJSDriver) HttpRequestCallback(ghostdriver.server.HttpRequestCallback) HttpServletResponse(javax.servlet.http.HttpServletResponse) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) WebDriverWait(org.openqa.selenium.support.ui.WebDriverWait) List(java.util.List) FileUploadException(org.apache.commons.fileupload.FileUploadException) Test(org.junit.Test)

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