Example usage for org.apache.commons.fileupload.servlet ServletFileUpload setSizeMax

List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload setSizeMax

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.servlet ServletFileUpload setSizeMax.

Prototype

public void setSizeMax(long sizeMax) 

Source Link

Document

Sets the maximum allowed upload size.

Usage

From source file:org.silverpeas.mobile.server.servlets.FormServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {// ww w  .j  ava  2 s .c  o  m
        String instanceId = null;
        String currentAction = null;
        String currentRole = null;
        String currentState = null;
        String processId = null;
        HashMap<String, Object> fields = new HashMap<String, Object>();
        String charset = "UTF-8";
        String tempDir = MediaHelper.getTemporaryUploadMediaPath();

        // configures upload settings
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // sets memory threshold - beyond which files are stored in disk
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        // sets temporary location to store files
        factory.setRepository(new File(tempDir));

        ServletFileUpload upload = new ServletFileUpload(factory);

        // sets maximum size of upload file
        upload.setFileSizeMax(MAX_FILE_SIZE);

        // sets maximum size of request (include file + form data)
        upload.setSizeMax(MAX_REQUEST_SIZE);

        // Parse the request
        @SuppressWarnings("unchecked")
        List<FileItem> items = null;
        items = upload.parseRequest(request);

        // Process the uploaded items
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField()) {
                if (item.getFieldName().equals("instanceId")) {
                    instanceId = item.getString(charset);
                } else if (item.getFieldName().equals("currentAction")) {
                    currentAction = item.getString(charset);
                } else if (item.getFieldName().equals("currentRole")) {
                    currentRole = item.getString(charset);
                } else if (item.getFieldName().equals("currentState")) {
                    currentState = item.getString(charset);
                } else if (item.getFieldName().equals("processId")) {
                    processId = item.getString(charset);
                } else {
                    fields.put(item.getFieldName(), item.getString(charset));
                }
            } else {
                String fileName = item.getName();
                File file = new File(tempDir + File.separator + fileName);
                item.write(file);
                fields.put(item.getFieldName(), file);
            }
        }
        processAction(request, response, fields, instanceId, currentAction, currentRole, currentState,
                processId);
    } catch (FileUploadBase.FileSizeLimitExceededException eu) {
        response.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
        return;
    } catch (Exception e) {
        e.printStackTrace();
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:org.silverpeas.mobile.server.servlets.MediaServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String componentId = "";
    String albumId = "";
    String tempDir = MediaHelper.getTemporaryUploadMediaPath();

    // configures upload settings
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // sets memory threshold - beyond which files are stored in disk
    factory.setSizeThreshold(MEMORY_THRESHOLD);
    // sets temporary location to store files
    factory.setRepository(new File(tempDir));

    ServletFileUpload upload = new ServletFileUpload(factory);

    // sets maximum size of upload file
    upload.setFileSizeMax(MAX_FILE_SIZE);

    // sets maximum size of request (include file + form data)
    upload.setSizeMax(MAX_REQUEST_SIZE);

    // Parse the request
    @SuppressWarnings("unchecked")
    List<FileItem> items = null;
    try {/*from  w  w  w . j  a v  a2  s .c  om*/
        items = upload.parseRequest(request);
    } catch (FileUploadBase.FileSizeLimitExceededException eu) {
        response.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
        return;
    } catch (FileUploadException e) {
        e.printStackTrace();
    }

    // Process the uploaded items
    Iterator iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();
        if (item.isFormField()) {
            if (item.getFieldName().equals("componentId"))
                componentId = item.getString();
            if (item.getFieldName().equals("albumId"))
                albumId = item.getString();

        } else {
            String fileName = item.getName();
            File file = new File(tempDir + File.separator + fileName);
            try {
                item.write(file);
                createMedia(request, response, fileName, getUserInSession(request).getId(), componentId,
                        albumId, file, false, "", "", true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:org.unitime.timetable.gwt.server.UploadServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/*from  w  ww .j a v a 2s.  c  o  m*/
        String maxSizeProperty = ApplicationProperty.MaxUploadSize.value();
        int maxSize = (maxSizeProperty == null ? DEFAULT_MAX_SIZE : Integer.parseInt(maxSizeProperty));

        ServletFileUpload upload = new ServletFileUpload(
                new DiskFileItemFactory(maxSize, ApplicationProperties.getTempFolder()));
        upload.setSizeMax(maxSize);

        List<FileItem> files = (List<FileItem>) upload.parseRequest(request);

        String message = null;
        if (files.size() == 1) {
            FileItem file = files.get(0);
            if (file.getSize() <= 0) {
                request.getSession().removeAttribute(SESSION_LAST_FILE);
                message = "No file is selected.";
            } else {
                request.getSession().setAttribute(SESSION_LAST_FILE, file);
                message = "File " + file.getName() + " (" + file.getSize() + " bytes) selected.";
            }
        } else {
            request.getSession().removeAttribute(SESSION_LAST_FILE);
            message = "No file is selected.";
        }

        response.setContentType("text/html; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        out.print(message);
        out.flush();
        out.close();
    } catch (FileUploadException e) {
        response.setContentType("text/html; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        out.print("ERROR:Upload failed: " + e.getMessage());
        out.flush();
        out.close();
    }
}

From source file:org.xchain.framework.servlet.MultipartFormDataServletRequest.java

public MultipartFormDataServletRequest(HttpServletRequest request, long maxSize, int sizeThreshold,
        String repositoryPath) throws FileUploadException {
    super(request);

    // Create the disk file item factory.
    DiskFileItemFactory factory = createDiskFileItemFactory(sizeThreshold, repositoryPath);
    ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
    // maximum size before a FileUploadException will be thrown
    servletFileUpload.setSizeMax(maxSize);

    // parse the request.
    Iterator<FileItem> fileItemIterator = servletFileUpload.parseRequest(request).iterator(); // Oye! Unchecked type conversion.

    // create temporary maps for parameters and file items.
    Map<String, List<String>> parameterMap = new HashMap<String, List<String>>();
    Map<String, List<FileItem>> fileItemMap = new HashMap<String, List<FileItem>>();

    // populate the maps.
    while (fileItemIterator.hasNext()) {
        FileItem fileItem = fileItemIterator.next();
        if (fileItem.isFormField()) {
            putListMapValue(parameterMap, fileItem.getFieldName(), fileItem.getString());
        } else {/*from   w  w w . java2s .  c  om*/
            putListMapValue(fileItemMap, fileItem.getFieldName(), fileItem);
        }
    }

    // convert the array lists.
    convertListMapToArrayMap(parameterMap, this.parameterMap, String.class);
    convertListMapToArrayMap(fileItemMap, this.fileItemMap, FileItem.class);

    if (log.isDebugEnabled()) {
        logFileItemMap();
    }

}

From source file:org.xmlactions.web.conceal.HtmlRequestMapper.java

/**
 * Get the request parameters. If this is a 'post' page the parameters come
 * from the body else they come from the request.getParameter().
 * //from   ww w.  j a v a  2s.co  m
 * @param request
 *            the HttpServletRequest
 * @return an array of KeyPairs with the parameters.
 * @throws IOException
 * @throws FileUploadException
 * @throws java.lang.Exception
 */
public Map<String, Object> getRequestParamsAsMap(HttpServletRequest request)
        throws IOException, FileUploadException {
    Map<String, Object> map = new HashMap<String, Object>();

    //
    // Get all parameters.
    //
    Enumeration<String> e = request.getParameterNames();
    while (e.hasMoreElements()) {
        String key = e.nextElement();
        String[] values = request.getParameterValues(key);
        if (values != null) {
            if (values.length == 1) {
                map.put(key, values[0]);
            } else {
                map.put(key, values);
            }
        }
    }
    if (this.is_multipart_form_data(request) == true) {

        DiskFileItemFactory factory = new DiskFileItemFactory();

        // maximum size that will be stored in memory
        // factory.setSizeThreshold(fileUploadMaxSize);

        ServletFileUpload upload = new ServletFileUpload(factory);
        // maximum size before a FileUploadException will be thrown
        if (fileUploadMaxSize > 0) {
            upload.setSizeMax(fileUploadMaxSize);
        }

        List<FileItem> list = upload.parseRequest(request);
        for (FileItem fi : list) {
            if (fi.getContentType() != null) {
                byte buffer[] = new byte[fi.getInputStream().available()];
                fi.getInputStream().read(buffer);
                // TODO emm, need to keys for the buffer for a file upload
                // parameters.add(new KeyPair(fi.getFieldName(),
                // fi.getName(), buffer));
                // log.debug(fi.getFieldName() + " = " + fi.getName());
                map.put(UPLOAD_FILE_NAME, fi.getName());
                map.put(UPLOAD_FILE_SIZE, fi.getSize());
                // map.put(fi.getFieldName(), buffer);
                map.put(UPLOAD_FILE_DATA, buffer);
                if (log.isDebugEnabled()) {
                    if (buffer.length > 100) {
                        log.debug(fi.getFieldName() + " = " + new String(buffer).substring(0, 100));
                    } else {
                        log.debug(fi.getFieldName() + " = " + new String(buffer));
                    }
                }
            } else {
                log.debug(fi.getFieldName() + " = " + fi.getString());
                map.put(fi.getFieldName(), fi.getString());
            }
        }
    }
    return (map);
}

From source file:org.xmlactions.web.conceal.HtmlRequestMapper.java

/**
 * Get the request parameters. If this is a 'post' page the parameters come
 * from the body else they come from the request.getParameter().
 * //from  www. jav  a 2  s  .  co  m
 * @param request
 *            the HttpServletRequest
 * @return an List of HttpParam created from the incoming request.
 * @throws IOException
 * @throws FileUploadException
 * @throws java.lang.Exception
 */
public List<HttpParam> getRequestParamsAsVector(HttpServletRequest request)
        throws IOException, FileUploadException {

    List<HttpParam> paramList = new ArrayList<HttpParam>();

    Enumeration<String> e = request.getParameterNames();
    while (e.hasMoreElements()) {
        String key = e.nextElement();
        String[] values = request.getParameterValues(key);
        if (values != null) {
            for (String value : values) {
                paramList.add(new HttpParam(key, value));
                if (log.isDebugEnabled()) {
                    log.debug(key + " = " + value);
                }
            }
        }
    }

    if (this.is_multipart_form_data(request) == true) {

        DiskFileItemFactory factory = new DiskFileItemFactory();

        // maximum size that will be stored in memory
        // factory.setSizeThreshold(fileUploadMaxSize);

        ServletFileUpload upload = new ServletFileUpload(factory);
        // maximum size before a FileUploadException will be thrown
        if (fileUploadMaxSize > 0) {
            upload.setSizeMax(fileUploadMaxSize);
        }

        List<FileItem> list = upload.parseRequest(request);
        for (FileItem fi : list) {
            if (fi.getContentType() != null) {
                byte buffer[] = new byte[fi.getInputStream().available()];
                fi.getInputStream().read(buffer);
                // TODO emm, need to keys for the buffer for a file upload
                // parameters.add(new KeyPair(fi.getFieldName(),
                // fi.getName(), buffer));
                // log.debug(fi.getFieldName() + " = " + fi.getName());
                paramList.add(new HttpParam(UPLOAD_FILE_NAME, fi.getName()));
                paramList.add(new HttpParam(UPLOAD_FILE_SIZE, fi.getSize()));
                // map.put(fi.getFieldName(), buffer);
                paramList.add(new HttpParam(UPLOAD_FILE_DATA, buffer));
                if (log.isDebugEnabled()) {
                    if (buffer.length > 100) {
                        log.debug(fi.getFieldName() + " = " + new String(buffer).substring(0, 100));
                    } else {
                        log.debug(fi.getFieldName() + " = " + new String(buffer));
                    }
                }
            } else {
                log.debug(fi.getFieldName() + " = " + fi.getString());
                paramList.add(new HttpParam(fi.getFieldName(), fi.getString()));
            }
        }
    }
    return (paramList);
}

From source file:org.zmail.clientuploader.ZClientUploader.java

/**
 * Save the uploaded file from request//  w  w w.j ava 2  s.  c o m
 * @param req
 * @throws ZClientUploaderException if fails to save
 */
public void upload(HttpServletRequest req) throws ZClientUploaderException {
    if (!ServletFileUpload.isMultipartContent(req)) {
        throw new ZClientUploaderException(ZClientUploaderRespCode.NOT_A_FILE);
    }

    DiskFileItemFactory factory = new DiskFileItemFactory(BUFFER_SIZE, getClientRepoTmp());

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(ClientUploaderLC.client_software_max_size.longValue());
    upload.setHeaderEncoding(ENCODING);

    File parent = getClientRepo();
    try {
        List<FileItem> items = upload.parseRequest(req);
        if (items == null || items.size() <= 0) {
            throw new ZClientUploaderException(ZClientUploaderRespCode.NOT_A_FILE);
        }

        Iterator iter = items.iterator();
        int count = 0;
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (!item.isFormField()) {
                String fileName = item.getName();
                if (fileName != null && !fileName.isEmpty()) {
                    item.write(new File(parent, fileName));
                    count++;
                }
            }
        }

        if (count == 0) {
            throw new ZClientUploaderException(ZClientUploaderRespCode.NOT_A_FILE);
        }
    } catch (ZClientUploaderException e) {
        throw e;
    } catch (FileUploadBase.SizeLimitExceededException e) {
        throw new ZClientUploaderException(ZClientUploaderRespCode.FILE_EXCEED_LIMIT, e);
    } catch (FileUploadException e) {
        throw new ZClientUploaderException(ZClientUploaderRespCode.PARSE_REQUEST_ERROR, e);
    } catch (Exception e) {
        throw new ZClientUploaderException(ZClientUploaderRespCode.SAVE_ERROR, e);
    }
}

From source file:presentation.ui.ExtendedMultiPartRequestHandler.java

/**
 * Parses the input stream and partitions the parsed items into a set of
 * form fields and a set of file items. In the process, the parsed items are
 * translated from Commons FileUpload <code>FileItem</code> instances to
 * Struts <code>FormFile</code> instances.
 * /*from  www  .j  av a2  s. com*/
 * @param request
 *            The multipart request to be processed.
 * 
 * @throws ServletException
 *             if an unrecoverable error occurs.
 */
public void handleRequest(HttpServletRequest request) throws ServletException {

    // Get the app config for the current request.
    ModuleConfig ac = (ModuleConfig) request.getAttribute(Globals.MODULE_KEY);

    // ----------------------------------------------------------
    // Changed this section of code, that is it.
    // -----------------------------------------------------------
    if (logger.isDebugEnabled())
        logger.debug("Handling the request..");
    UploadListener listener = new UploadListener(request, 1);
    if (logger.isDebugEnabled())
        logger.debug("uploading file with optional monitoring..");
    // Create a factory for disk-based file items

    FileItemFactory factory = new MonitoredDiskFileItemFactory(listener);
    if (logger.isDebugEnabled())
        logger.debug("got the factory now get the ServletFileUpload");
    ServletFileUpload upload = new ServletFileUpload(factory);
    if (logger.isDebugEnabled())
        logger.debug("Should have the ServletFileUpload by now.");
    // The following line is to support an "EncodingFilter"
    // see http://nagoya.apache.org/bugzilla/show_bug.cgi?id=23255
    upload.setHeaderEncoding(request.getCharacterEncoding());
    // Set the maximum size before a FileUploadException will be thrown.
    try {
        upload.setSizeMax(maxFileSize(request, getSizeMax(ac)));
    } catch (BusinessException e) {
        finish();
        listener.error(e.getMessage());
        // WebInfoHelper.getInstance().setWebError(request, e);
        throw new ServletException(e);
    }

    // ----------------------------------------------------------------
    // Create the hash tables to be populated.
    elementsText = new Hashtable<String, String[]>();
    elementsFile = new Hashtable<String, FormFile>();
    elementsAll = new Hashtable<String, Object>();

    // Parse the request into file items.

    List<?> items = null;
    try {
        items = upload.parseRequest(request);
    } catch (SizeLimitExceededException e) {
        // Special handling for uploads that are too big.
        listener.error(e.getMessage());
        request.setAttribute(MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED, Boolean.TRUE);
        return;
    } catch (FileUploadException e) {
        // WebInfoHelper.getInstance().setWebError(request, e);
        throw new ServletException(e);
    }

    // Partition the items into form fields and files.
    Iterator<?> iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();

        if (item.isFormField()) {
            addTextParameter(request, item);
        } else {
            addFileParameter(item);
        }
    }
}

From source file:projectServlet.UploadServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (!isMultipart) {
        return;/*from  w ww.  j  a  v  a 2s. co m*/
    }

    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // Sets the size threshold beyond which files are written directly to
    // disk.
    factory.setSizeThreshold(MAX_MEMORY_SIZE);

    // Sets the directory used to temporarily store files that are larger
    // than the configured size threshold. We use temporary directory for
    // java
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    // constructs the folder where uploaded file will be stored
    String uploadFolder = getServletContext().getRealPath("") + File.separator + DATA_DIRECTORY;

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    // Set overall request size constraint
    upload.setSizeMax(MAX_REQUEST_SIZE);

    try {
        Map<String, String> map = new HashMap<String, String>();
        ArrayList<String> imgs_str = new ArrayList<String>();
        boolean result = false;
        float price = 0;

        ArrayList<ImageDO> imagesDO = new ArrayList<ImageDO>();
        // Parse the request
        List items = upload.parseRequest(request);
        Iterator iter = items.iterator();
        String field_name;
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            field_name = item.getFieldName();
            if (!item.isFormField()) {
                String fileName = new File(item.getName()).getName();

                String fullFileName = field_name + "_" + System.currentTimeMillis() + "_" + fileName;

                String filePath = uploadFolder + File.separator + fullFileName;
                File uploadedFile = new File(filePath);

                System.out.print("filePath loop: " + filePath);
                if (field_name.equals("projectFile")) {
                    if (fileName == "" || fileName.isEmpty()) {
                        //RequestDispatcher rd = getServletContext().getRequestDispatcher("/PaginaDoDesenvolvedor/uploadprojeto.jsp");
                        PrintWriter out3 = response.getWriter();

                        //rd.include(request, response);

                        response.sendRedirect("./PaginaDoDesenvolvedor/uploadprojeto.jsp?error=nofile");
                        //out3.println("<font color=red>Favor escolher um arquivo.</font>");
                        return;
                    }
                    map.put(field_name, fullFileName);
                    System.out.print("projectFile: " + fullFileName);
                    // saves the file to upload directory
                    item.write(uploadedFile);
                } else if (field_name.equals("image") && (fileName != "" && !fileName.isEmpty())) {
                    ImageDO image = new ImageDO();
                    image.setImagelink(fullFileName);
                    imagesDO.add(image);
                    // saves the file to upload directory
                    item.write(uploadedFile);
                }
            } else {
                System.out.print("var " + item.getFieldName() + ": " + item.getString());
                map.put(item.getFieldName(), item.getString());
            }
        }

        try {
            String price_str = map.get("price");
            if (!utils.MetodosUteis.isEmpty(price_str)) {
                price = Float.valueOf(price_str).floatValue();
            }
            project.projectDO project = new project.projectDO(map.get("name"), map.get("description"),
                    map.get("comments"), price, 0);
            project.versionDO version = new project.versionDO();
            version.setFilepath(map.get("projectFile"));
            System.out.print("filename:" + map.get("projectFile"));
            transaction.UploadProject upProject = new transaction.UploadProject();
            try {
                result = upProject.uploadProject(project, version, imagesDO);
            } catch (Exception e) {
                System.out.print("ERROR! Upload");
                response.sendRedirect("./PaginaDoDesenvolvedor/uploadprojeto.jsp?error=erroruploading");
                //RequestDispatcher rd = getServletContext().getRequestDispatcher("/done.jsp");
                //PrintWriter out = response.getWriter();
                //out.println("<font color=red>Erro ao subir pr0ojeto.</font>");
                //rd.include(request, response);

                return;
            }
        } catch (NumberFormatException e) {
            System.out.print("ERROR! Number Format");
        }

        // displays done.jsp page after upload finished

        PrintWriter out2 = response.getWriter();
        RequestDispatcher rd;
        if (result) {
            response.sendRedirect("./done.jsp");
            out2.println(
                    "<h3>Seu arquivo projeto foi enviado com sucesso para aprovao dos moderadores!</h3>");
        } else {
            //rd = getServletContext().getRequestDispatcher("/PaginaDoDesenvolvedor/uploadprojeto.jsp");
            //out2.println("<font color=red>Favor preencher os campos corretamente.</font>");
            response.sendRedirect("./PaginaDoDesenvolvedor/uploadprojeto.jsp?error=wrongfields");
        }
        //rd.include(request, response);

    } catch (FileUploadException ex) {
        throw new ServletException(ex);
    } catch (Exception ex) {
        throw new ServletException(ex);
    }

}

From source file:psiprobe.controllers.deploy.CopySingleFileController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    List<Context> apps;
    try {//from   w  ww. j  ava2s.c o  m
        apps = getContainerWrapper().getTomcatContainer().findContexts();
    } catch (NullPointerException ex) {
        throw new IllegalStateException(
                "No container found for your server: " + getServletContext().getServerInfo(), ex);
    }

    List<Map<String, String>> applications = new ArrayList<>();
    for (Context appContext : apps) {
        // check if this is not the ROOT webapp
        if (appContext.getName() != null && appContext.getName().trim().length() > 0) {
            Map<String, String> app = new HashMap<>();
            app.put("value", appContext.getName());
            app.put("label", appContext.getName());
            applications.add(app);
        }
    }
    request.setAttribute("apps", applications);

    if (FileUploadBase.isMultipartContent(new ServletRequestContext(request))) {

        File tmpFile = null;
        String contextName = null;
        String where = null;
        boolean reload = false;
        boolean discard = false;

        // parse multipart request and extract the file
        FileItemFactory factory = new DiskFileItemFactory(1048000,
                new File(System.getProperty("java.io.tmpdir")));
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(-1);
        upload.setHeaderEncoding(StandardCharsets.UTF_8.name());
        try {
            List<FileItem> fileItems = upload.parseRequest(request);
            for (FileItem fi : fileItems) {
                if (!fi.isFormField()) {
                    if (fi.getName() != null && fi.getName().length() > 0) {
                        tmpFile = new File(System.getProperty("java.io.tmpdir"),
                                FilenameUtils.getName(fi.getName()));
                        fi.write(tmpFile);
                    }
                } else if ("context".equals(fi.getFieldName())) {
                    contextName = fi.getString();
                } else if ("where".equals(fi.getFieldName())) {
                    where = fi.getString();
                } else if ("reload".equals(fi.getFieldName()) && "yes".equals(fi.getString())) {
                    reload = true;
                } else if ("discard".equals(fi.getFieldName()) && "yes".equals(fi.getString())) {
                    discard = true;
                }
            }
        } catch (Exception e) {
            logger.error("Could not process file upload", e);
            request.setAttribute("errorMessage", getMessageSourceAccessor()
                    .getMessage("probe.src.deploy.file.uploadfailure", new Object[] { e.getMessage() }));
            if (tmpFile != null && tmpFile.exists() && !tmpFile.delete()) {
                logger.error("Unable to delete temp upload file");
            }
            tmpFile = null;
        }

        String errMsg = null;

        if (tmpFile != null) {
            try {
                if (tmpFile.getName() != null && tmpFile.getName().trim().length() > 0) {

                    contextName = getContainerWrapper().getTomcatContainer().formatContextName(contextName);

                    String visibleContextName = "".equals(contextName) ? "/" : contextName;
                    request.setAttribute("contextName", visibleContextName);

                    // Check if context is already deployed
                    if (getContainerWrapper().getTomcatContainer().findContext(contextName) != null) {

                        File destFile = new File(getContainerWrapper().getTomcatContainer().getAppBase(),
                                contextName + where);
                        // Checks if the destination path exists

                        if (destFile.exists()) {
                            if (!destFile.getAbsolutePath().contains("..")) {
                                // Copy the file overwriting it if it
                                // already exists
                                FileUtils.copyFileToDirectory(tmpFile, destFile);

                                request.setAttribute("successFile", Boolean.TRUE);
                                // Logging action
                                Authentication auth = SecurityContextHolder.getContext().getAuthentication();
                                String name = auth.getName(); // get username
                                                              // logger
                                logger.info(getMessageSourceAccessor().getMessage("probe.src.log.copyfile"),
                                        name, contextName);
                                Context context = getContainerWrapper().getTomcatContainer()
                                        .findContext(contextName);
                                // Checks if DISCARD "work" directory is
                                // selected
                                if (discard) {
                                    getContainerWrapper().getTomcatContainer().discardWorkDir(context);
                                    logger.info(
                                            getMessageSourceAccessor().getMessage("probe.src.log.discardwork"),
                                            name, contextName);
                                }
                                // Checks if RELOAD option is selected
                                if (reload) {

                                    if (context != null) {
                                        context.reload();
                                        request.setAttribute("reloadContext", Boolean.TRUE);
                                        logger.info(
                                                getMessageSourceAccessor().getMessage("probe.src.log.reload"),
                                                name, contextName);
                                    }
                                }
                            } else {
                                errMsg = getMessageSourceAccessor()
                                        .getMessage("probe.src.deploy.file.pathNotValid");
                            }
                        } else {
                            errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.file.notPath");
                        }
                    } else {
                        errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.file.notExists",
                                new Object[] { visibleContextName });
                    }
                } else {
                    errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.file.notFile.failure");
                }
            } catch (Exception e) {
                errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.file.failure",
                        new Object[] { e.getMessage() });
                logger.error("Tomcat throw an exception when trying to deploy", e);
            } finally {
                if (errMsg != null) {
                    request.setAttribute("errorMessage", errMsg);
                }
                if (!tmpFile.delete()) {
                    logger.error("Unable to delete temp upload file");
                }
            }
        }
    }
    return new ModelAndView(new InternalResourceView(getViewName()));
}