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:com.mx.nibble.middleware.web.util.FileUpload.java

public void performTask(javax.servlet.http.HttpServletRequest request,
        javax.servlet.http.HttpServletResponse response) {

    /**//w  ww  . j av  a 2s  .com
    * This pages gives a sample of java upload management. It needs the commons FileUpload library, which can be found on apache.org.
    *
    * Note:
    * - putting error=true as a parameter on the URL will generate an error. Allows test of upload error management in the applet. 
    * 
    * 
    * 
    * 
    * 
    * 
    */

    logger.debug(" Directory to store all the uploaded files");

    String ourTempDirectory = "/opt/erp/import/obras/";
    try {
        out = response.getWriter();
    } catch (Exception e) {
        e.printStackTrace();
    }

    byte[] cr = { 13 };
    byte[] lf = { 10 };
    String CR = new String(cr);
    String LF = new String(lf);
    String CRLF = CR + LF;
    out.println("Before a LF=chr(10)" + LF + "Before a CR=chr(13)" + CR + "Before a CRLF" + CRLF);

    logger.debug("Initialization for chunk management.");
    boolean bLastChunk = false;
    int numChunk = 0;

    logger.debug(
            "CAN BE OVERRIDEN BY THE postURL PARAMETER: if error=true is passed as a parameter on the URL");
    boolean generateError = false;
    boolean generateWarning = false;
    boolean sendRequest = false;

    response.setContentType("text/plain");

    java.util.Enumeration<String> headers = request.getHeaderNames();
    out.println("[parseRequest.jsp]  ------------------------------ ");
    out.println("[parseRequest.jsp]  Headers of the received request:");
    logger.debug("[parseRequest.jsp]  Headers of the received request:");
    while (headers.hasMoreElements()) {
        String header = headers.nextElement();
        out.println("[parseRequest.jsp]  " + header + ": " + request.getHeader(header));
        logger.debug("[parseRequest.jsp]  " + header + ": " + request.getHeader(header));
    }
    out.println("[parseRequest.jsp]  ------------------------------ ");

    try {
        logger.debug(" Get URL Parameters.");
        Enumeration paraNames = request.getParameterNames();
        out.println("[parseRequest.jsp]  ------------------------------ ");
        out.println("[parseRequest.jsp]  Parameters: ");
        logger.debug("[parseRequest.jsp]  Parameters: ");
        String pname;
        String pvalue;
        while (paraNames.hasMoreElements()) {
            pname = (String) paraNames.nextElement();
            pvalue = request.getParameter(pname);
            out.println("[parseRequest.jsp] " + pname + " = " + pvalue);
            logger.debug("[parseRequest.jsp] " + pname + " = " + pvalue);
            if (pname.equals("jufinal")) {
                bLastChunk = pvalue.equals("1");
            } else if (pname.equals("jupart")) {
                numChunk = Integer.parseInt(pvalue);
            }

            if (pname.equals("error") && pvalue.equals("true")) {
                generateError = true;
                logger.debug(
                        "For debug convenience, putting error=true as a URL parameter, will generate an error in this response.");
            }

            if (pname.equals("warning") && pvalue.equals("true")) {
                generateWarning = true;
                logger.debug(
                        "For debug convenience, putting warning=true as a URL parameter, will generate a warning in this response.");
            }

            if (pname.equals("sendRequest") && pvalue.equals("true")) {
                sendRequest = true;
                logger.debug(
                        "For debug convenience, putting readRequest=true as a URL parameter, will send back the request content into the response of this page.");
            }

        }
        out.println("[parseRequest.jsp]  ------------------------------ ");

        int ourMaxMemorySize = 10000000;
        int ourMaxRequestSize = 2000000000;

        ///////////////////////////////////////////////////////////////////////////////////////////////////////
        //The code below is directly taken from the jakarta fileupload common classes
        //All informations, and download, available here : http://jakarta.apache.org/commons/fileupload/
        ///////////////////////////////////////////////////////////////////////////////////////////////////////

        logger.debug(" Create a factory for disk-based file items");
        DiskFileItemFactory factory = new DiskFileItemFactory();

        logger.debug(" Set factory constraints");
        factory.setSizeThreshold(ourMaxMemorySize);
        logger.debug("ourTempDirectory" + ourTempDirectory);
        factory.setRepository(new File(ourTempDirectory));

        logger.debug(" Create a new file upload handler");
        ServletFileUpload upload = new ServletFileUpload(factory);

        logger.debug(" Set overall request size constraint");
        upload.setSizeMax(ourMaxRequestSize);

        logger.debug(" Parse the request");
        if (sendRequest) {
            logger.debug("For debug only. Should be removed for production systems. ");
            out.println(
                    "[parseRequest.jsp] ===========================================================================");
            out.println("[parseRequest.jsp] Sending the received request content: ");
            logger.debug("[parseRequest.jsp] Sending the received request content: ");
            InputStream is = request.getInputStream();
            int c;
            while ((c = is.read()) >= 0) {
                out.write(c);
            }
            logger.debug("while");
            is.close();
            out.println(
                    "[parseRequest.jsp] ===========================================================================");
        } else if (!request.getContentType().startsWith("multipart/form-data")) {
            out.println("[parseRequest.jsp] No parsing of uploaded file: content type is "
                    + request.getContentType());
        } else {

            List /* FileItem */ items = upload.parseRequest(request);

            logger.debug(" Process the uploaded items" + items.size());

            Iterator iter = items.iterator();
            FileItem fileItem;
            File fout;
            out.println("[parseRequest.jsp]  Let's read the sent data   (" + items.size() + " items)");
            while (iter.hasNext()) {
                fileItem = (FileItem) iter.next();

                if (fileItem.isFormField()) {
                    out.println("[parseRequest.jsp] (form field) " + fileItem.getFieldName() + " = "
                            + fileItem.getString());

                    logger.debug(
                            "If we receive the md5sum parameter, we've read finished to read the current file. It's not");
                    logger.debug(
                            "a very good (end of file) signal. Will be better in the future ... probably !");
                    logger.debug("Let's put a separator, to make output easier to read.");
                    if (fileItem.getFieldName().equals("md5sum[]")) {
                        out.println("[parseRequest.jsp]  ------------------------------ ");
                    }
                } else {
                    logger.debug("Ok, we've got a file. Let's process it.");
                    logger.debug("Again, for all informations of what is exactly a FileItem, please");
                    logger.debug("have a look to http://jakarta.apache.org/commons/fileupload/");

                    out.println("[parseRequest.jsp] FieldName: " + fileItem.getFieldName());
                    out.println("[parseRequest.jsp] File Name: " + fileItem.getName());
                    out.println("[parseRequest.jsp] ContentType: " + fileItem.getContentType());
                    out.println("[parseRequest.jsp] Size (Bytes): " + fileItem.getSize());
                    logger.debug(
                            "If we are in chunk mode, we add .partN at the end of the file, where N is the chunk number.");
                    String uploadedFilename = fileItem.getName() + (numChunk > 0 ? ".part" + numChunk : "");
                    fout = new File(ourTempDirectory + (new File(uploadedFilename)).getName());
                    out.println("[parseRequest.jsp] File Out: " + fout.toString());
                    logger.debug(" write the file");
                    fileItem.write(fout);

                    //
                    logger.debug("Chunk management: if it was the last chunk, let's recover the complete file");
                    logger.debug("by concatenating all chunk parts.");
                    logger.debug("");
                    if (bLastChunk) {
                        out.println("[parseRequest.jsp]  Last chunk received: let's rebuild the complete file ("
                                + fileItem.getName() + ")");
                        logger.debug("First: construct the final filename.");
                        FileInputStream fis;
                        FileOutputStream fos = new FileOutputStream(ourTempDirectory + fileItem.getName());
                        int nbBytes;
                        byte[] byteBuff = new byte[1024];
                        String filename;
                        for (int i = 1; i <= numChunk; i += 1) {
                            filename = fileItem.getName() + ".part" + i;
                            out.println("[parseRequest.jsp] " + "  Concatenating " + filename);
                            fis = new FileInputStream(ourTempDirectory + filename);
                            while ((nbBytes = fis.read(byteBuff)) >= 0) {
                                //out.println("[parseRequest.jsp] " + "     Nb bytes read: " + nbBytes);
                                fos.write(byteBuff, 0, nbBytes);
                            }
                            fis.close();
                        }
                        fos.close();
                    }

                    logger.debug(" End of chunk management");
                    //

                    fileItem.delete();
                }
            }
            logger.debug("while");
        }

        if (generateWarning) {
            out.println("WARNING: just a warning message.\\nOn two lines!");
        }

        out.println("[parseRequest.jsp] " + "Let's write a status, to finish the server response :");

        logger.debug("Let's wait a little, to simulate the server time to manage the file.");
        Thread.sleep(500);

        logger.debug("Do you want to test a successful upload, or the way the applet reacts to an error ?");
        if (generateError) {
            out.println(
                    "ERROR: this is a test error (forced in /wwwroot/pages/parseRequest.jsp).\\nHere is a second line!");
        } else {
            out.println("SUCCESS");
            logger.debug("");
        }

        out.println("[parseRequest.jsp] " + "End of server treatment ");

    } catch (Exception e) {
        out.println("");
        out.println("ERROR: Exception e = " + e.toString());
        out.println("");
    }
}

From source file:edu.harvard.hul.ois.fits.service.servlets.FitsServlet.java

/**
 * Handles the file upload for FITS processing via streaming of the file using the
 * <code>POST</code> method.
 * Example: curl -X POST -F datafile=@<path/to/file> <host>:[<port>]/fits/examine
 * Note: "fits" in the above URL needs to be adjusted to the final name of the WAR file.
 *
 * @param request servlet request/*from  w w w. j av a 2s  . c  o m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    logger.debug("Entering doPost()");
    if (!ServletFileUpload.isMultipartContent(request)) {
        ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_BAD_REQUEST,
                "Missing multipart POST form data.", request.getRequestURL().toString());
        sendErrorMessageResponse(errorMessage, response);
        return;
    }

    // configures upload settings
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold((maxInMemoryFileSizeMb * (int) MB_MULTIPLIER));
    String tempDir = System.getProperty("java.io.tmpdir");
    logger.debug("Creating temp directory for storing uploaded files: " + tempDir);
    factory.setRepository(new File(tempDir));

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(maxFileUploadSizeMb * MB_MULTIPLIER);
    upload.setSizeMax(maxRequestSizeMb * MB_MULTIPLIER);

    try {
        List<FileItem> formItems = upload.parseRequest(request);
        Iterator<FileItem> iter = formItems.iterator();
        Map<String, String[]> paramMap = request.getParameterMap();

        boolean includeStdMetadata = true;
        String[] vals = paramMap.get(Constants.INCLUDE_STANDARD_OUTPUT_PARAM);
        if (vals != null && vals.length > 0) {
            if (FALSE.equalsIgnoreCase(vals[0])) {
                includeStdMetadata = false;
                logger.debug("flag includeStdMetadata set to : " + includeStdMetadata);
            }
        }

        // file-specific directory path to store uploaded file
        // ensures unique sub-directory to handle rare case of duplicate file name
        String subDir = String.valueOf((new Date()).getTime());
        String uploadPath = uploadBaseDir + File.separator + subDir;
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }

        // iterates over form's fields -- should only be one for uploaded file
        while (iter.hasNext()) {
            FileItem item = iter.next();
            if (!item.isFormField() && item.getFieldName().equals(FITS_FORM_FIELD_DATAFILE)) {

                String fileName = item.getName();
                if (StringUtils.isEmpty(fileName)) {
                    ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_BAD_REQUEST,
                            "Missing File Data.", request.getRequestURL().toString());
                    sendErrorMessageResponse(errorMessage, response);
                    return;
                }
                // ensure a unique local fine name
                String fileNameAndPath = uploadPath + File.separator + item.getName();
                File storeFile = new File(fileNameAndPath);
                item.write(storeFile); // saves the file on disk

                if (!storeFile.exists()) {
                    ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                            "Uploaded file does not exist.", request.getRequestURL().toString());
                    sendErrorMessageResponse(errorMessage, response);
                    return;
                }
                // Send it to the FITS processor...
                try {

                    sendFitsExamineResponse(storeFile.getAbsolutePath(), includeStdMetadata, request, response);

                } catch (Exception e) {
                    logger.error("Unexpected exception: " + e.getMessage(), e);
                    ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                            e.getMessage(), request.getRequestURL().toString());
                    sendErrorMessageResponse(errorMessage, response);
                    return;
                } finally {
                    // delete the uploaded file
                    if (storeFile.delete()) {
                        logger.debug(storeFile.getName() + " is deleted!");
                    } else {
                        logger.warn(storeFile.getName() + " could not be deleted!");
                    }
                    if (uploadDir.delete()) {
                        logger.debug(uploadDir.getName() + " is deleted!");
                    } else {
                        logger.warn(uploadDir.getName() + " could not be deleted!");
                    }
                }
            } else {
                ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_BAD_REQUEST,
                        "The request did not have the correct name attribute of \"datafile\" in the form processing. ",
                        request.getRequestURL().toString(), "Processing halted.");
                sendErrorMessageResponse(errorMessage, response);
                return;
            }

        }

    } catch (Exception ex) {
        logger.error("Unexpected exception: " + ex.getMessage(), ex);
        ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                ex.getMessage(), request.getRequestURL().toString(), "Processing halted.");
        sendErrorMessageResponse(errorMessage, response);
        return;
    }
}

From source file:com.example.web.Create_story.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    int count = 1;
    String storyid, storystep;//from w ww.j a v a 2s  . com
    String fileName = "";
    int f = 0;
    String action = "";
    String first = request.getParameter("first");
    String user = null;
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("user"))
                user = cookie.getValue();
        }
    }
    String title = request.getParameter("title");
    String header = request.getParameter("header");
    String text_field = request.getParameter("text_field");

    String latitude = request.getParameter("lat");
    String longitude = request.getParameter("lng");
    storyid = (request.getParameter("storyid"));
    storystep = (request.getParameter("storystep"));
    String message = "";
    int valid = 1;
    String query;
    ResultSet rs;
    Connection conn;
    String url = "jdbc:mysql://localhost:3306/";
    String dbName = "tworld";
    String driver = "com.mysql.jdbc.Driver";

    isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // maximum size that will be stored in memory
        factory.setSizeThreshold(maxMemSize);
        // Location to save data that is larger than maxMemSize.
        //factory.setRepository(new File("/var/lib/tomcat7/webapps/www_term_project/temp/"));
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        // maximum file size to be uploaded.
        upload.setSizeMax(maxFileSize);

        try {
            // Parse the request to get file items.
            List fileItems = upload.parseRequest(request);

            // Process the uploaded file items
            Iterator i = fileItems.iterator();

            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (!fi.isFormField()) {
                    // Get the uploaded file parameters
                    String fieldName = fi.getFieldName();
                    fileName = fi.getName();
                    String contentType = fi.getContentType();
                    boolean isInMemory = fi.isInMemory();
                    long sizeInBytes = fi.getSize();
                    String[] spliting = fileName.split("\\.");
                    // Write the file
                    System.out.println(sizeInBytes + " " + maxFileSize);
                    System.out.println(spliting[spliting.length - 1]);
                    if (!fileName.equals("")) {
                        if ((sizeInBytes < maxFileSize) && (spliting[spliting.length - 1].equals("jpg")
                                || spliting[spliting.length - 1].equals("png")
                                || spliting[spliting.length - 1].equals("jpeg"))) {

                            if (fileName.lastIndexOf("\\") >= 0) {
                                file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                            } else {
                                file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
                            }
                            fi.write(file);
                            System.out.println("Uploaded Filename: " + fileName + "<br>");
                        } else {
                            valid = 0;
                            message = "not a valid image";
                        }
                    }
                }
                BufferedReader br = null;
                StringBuilder sb = new StringBuilder();

                String line;
                try {
                    br = new BufferedReader(new InputStreamReader(fi.getInputStream()));
                    while ((line = br.readLine()) != null) {
                        sb.append(line);
                    }
                } catch (IOException e) {
                } finally {
                    if (br != null) {
                        try {
                            br.close();
                        } catch (IOException e) {
                        }
                    }
                }
                if (f == 0)
                    action = sb.toString();
                else if (f == 1)
                    storyid = sb.toString();
                else if (f == 2)
                    storystep = sb.toString();
                else if (f == 3)
                    title = sb.toString();
                else if (f == 4)
                    header = sb.toString();
                else if (f == 5)
                    text_field = sb.toString();
                else if (f == 6)
                    latitude = sb.toString();
                else if (f == 7)
                    longitude = sb.toString();
                else if (f == 8)
                    first = sb.toString();
                f++;

            }
        } catch (Exception ex) {
            System.out.println("hi");
            System.out.println(ex);

        }
    }
    if (latitude == null)
        latitude = "";
    if (latitude.equals("") && first == null) {

        request.setAttribute("message", "please enter a marker");
        request.setAttribute("storyid", storyid);
        request.setAttribute("s_page", "3");
        request.setAttribute("storystep", storystep);
        request.getRequestDispatcher("/index.jsp").forward(request, response);
    } else if (valid == 1) {
        try {
            Class.forName(driver).newInstance();
            conn = DriverManager.getConnection(url + dbName, "admin", "admin");
            if (first != null) {
                if (first.equals("first_step")) {
                    do {
                        query = "select * from story_database where story_id='" + count + "' ";
                        Statement st = conn.createStatement();
                        rs = st.executeQuery(query);
                        count++;
                    } while (rs.next());

                    int a = count - 1;
                    request.setAttribute("storyid", a);
                    storyid = Integer.toString(a);
                    request.setAttribute("storystep", 2);

                }
            }
            query = "select * from story_database where `story_id`='" + storyid + "' && `step_num`='"
                    + storystep + "' ";
            Statement st = conn.createStatement();
            rs = st.executeQuery(query);

            if (!rs.next()) {

                PreparedStatement pst = (PreparedStatement) conn.prepareStatement(
                        "insert into `tworld`.`story_database`(`story_id`, `step_num`, `content`, `latitude`, `longitude`, `title`, `header`, `max_steps`, `username`,`image_name`) values(?,?,?,?,?,?,?,?,?,?)");

                pst.setInt(1, Integer.parseInt(storyid));
                pst.setInt(2, Integer.parseInt(storystep));
                pst.setString(3, text_field);
                pst.setString(4, latitude);
                pst.setString(5, longitude);
                pst.setString(6, title);
                pst.setString(7, header);
                pst.setInt(8, Integer.parseInt(storystep));
                pst.setString(9, user);
                if (fileName.equals(""))
                    pst.setString(10, "");
                else
                    pst.setString(10, fileName);
                pst.executeUpdate();
                pst.close();

                pst = (PreparedStatement) conn.prepareStatement(
                        "UPDATE `tworld`.`story_database` SET `max_steps` = ? WHERE `story_id` = ?");
                pst.setInt(1, Integer.parseInt(storystep));
                pst.setInt(2, Integer.parseInt(storyid));
                pst.executeUpdate();
                pst.close();
            } else {
                PreparedStatement pst = (PreparedStatement) conn.prepareStatement(
                        "UPDATE `tworld`.`story_database` SET `content`=?, `latitude`=?, `longitude`=?, `title`=?, `header`=?, `max_steps`=?, `username`=? WHERE `story_id` = ? && `step_num`=?");

                pst.setString(1, text_field);
                pst.setString(2, latitude);
                pst.setString(3, longitude);
                pst.setString(4, title);
                pst.setString(5, header);

                pst.setInt(6, Integer.parseInt(storystep));
                pst.setString(7, user);
                pst.setInt(8, Integer.parseInt(storyid));
                pst.setInt(9, Integer.parseInt(storystep));

                pst.executeUpdate();
                pst.close();

                pst = (PreparedStatement) conn.prepareStatement(
                        "UPDATE `tworld`.`story_database` SET `max_steps` = ? WHERE `story_id` = ?");
                pst.setInt(1, Integer.parseInt(storystep));
                pst.setInt(2, Integer.parseInt(storyid));
                pst.executeUpdate();
                pst.close();
            }
            request.setAttribute("storyid", storyid);
            storystep = Integer.toString(Integer.parseInt(storystep) + 1);
            request.setAttribute("storystep", storystep);

        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException ex) {

            //            Logger.getLogger(MySignInServlet.class.getName()).log(Level.SEVERE, null, ex);  
        }
        request.setAttribute("s_page", "3");
        request.getRequestDispatcher("/index.jsp").forward(request, response);

    } else {
        request.setAttribute("storyid", storyid);
        request.setAttribute("message", message);
        request.setAttribute("storystep", storystep);

        request.setAttribute("s_page", "3");
        request.getRequestDispatcher("/index.jsp").forward(request, response);
    }
}

From source file:com.github.thorqin.toolkit.web.utility.UploadManager.java

/**
 * Save upload file to disk/*from   ww  w.j av  a 2 s.  c o  m*/
 * @param request HttpServletRequest
 * @param maxSize maximum size of the upload file, in bytes.
 * @return Saved file info list
 * @throws ServletException
 * @throws IOException
 * @throws FileUploadException
 */
public List<FileInfo> saveUploadFiles(HttpServletRequest request, int maxSize)
        throws ServletException, IOException, FileUploadException {
    List<FileInfo> uploadList = new LinkedList<>();
    request.setCharacterEncoding("utf-8");
    ServletFileUpload upload = new ServletFileUpload();
    upload.setHeaderEncoding("UTF-8");
    if (!ServletFileUpload.isMultipartContent(request)) {
        return uploadList;
    }
    upload.setSizeMax(maxSize);
    FileItemIterator iterator = upload.getItemIterator(request);
    while (iterator.hasNext()) {
        FileItemStream item = iterator.next();
        try (InputStream stream = item.openStream()) {
            if (!item.isFormField()) {
                FileInfo info = new FileInfo();
                info.setFileName(item.getName());
                if (pattern != null && !pattern.matcher(info.fileName).matches()) {
                    continue;
                }
                info = store(stream, info.fileName);
                uploadList.add(info);
            }
        }
    }
    return uploadList;
}

From source file:at.gv.egiz.pdfas.web.servlets.ExternSignServlet.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)// ww w.j a  v a2s. c om
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    //PdfAsHelper.regenerateSession(request);

    logger.debug("Post signing request");

    String errorUrl = PdfAsParameterExtractor.getInvokeErrorURL(request);
    PdfAsHelper.setErrorURL(request, response, errorUrl);

    StatisticEvent statisticEvent = new StatisticEvent();
    statisticEvent.setStartNow();
    statisticEvent.setSource(Source.WEB);
    statisticEvent.setOperation(Operation.SIGN);
    statisticEvent.setUserAgent(UserAgentFilter.getUserAgent());

    try {
        byte[] filecontent = null;

        // checks if the request actually contains upload file
        if (!ServletFileUpload.isMultipartContent(request)) {
            // No Uploaded data!
            if (PdfAsParameterExtractor.getPdfUrl(request) != null) {
                doGet(request, response);
                return;
            } else {
                throw new PdfAsWebException("No Signature data defined!");
            }
        } else {
            // configures upload settings
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(WebConfiguration.getFilesizeThreshold());
            factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setFileSizeMax(WebConfiguration.getMaxFilesize());
            upload.setSizeMax(WebConfiguration.getMaxRequestsize());

            // constructs the directory path to store upload file
            String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
            // creates the directory if it does not exist
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdir();
            }

            List<?> formItems = upload.parseRequest(request);
            logger.debug(formItems.size() + " Items in form data");
            if (formItems.size() < 1) {
                // No Uploaded data!
                // Try do get
                // No Uploaded data!
                if (PdfAsParameterExtractor.getPdfUrl(request) != null) {
                    doGet(request, response);
                    return;
                } else {
                    throw new PdfAsWebException("No Signature data defined!");
                }
            } else {
                for (int i = 0; i < formItems.size(); i++) {
                    Object obj = formItems.get(i);
                    if (obj instanceof FileItem) {
                        FileItem item = (FileItem) obj;
                        if (item.getFieldName().equals(UPLOAD_PDF_DATA)) {
                            filecontent = item.get();
                            try {
                                File f = new File(item.getName());
                                String name = f.getName();
                                logger.debug("Got upload: " + item.getName());
                                if (name != null) {
                                    if (!(name.endsWith(".pdf") || name.endsWith(".PDF"))) {
                                        name += ".pdf";
                                    }

                                    logger.debug("Setting Filename in session: " + name);
                                    PdfAsHelper.setPDFFileName(request, name);
                                }
                            } catch (Throwable e) {
                                logger.warn("In resolving filename", e);
                            }
                            if (filecontent.length < 10) {
                                filecontent = null;
                            } else {
                                logger.debug("Found pdf Data! Size: " + filecontent.length);
                            }
                        } else {
                            request.setAttribute(item.getFieldName(), item.getString());
                            logger.debug("Setting " + item.getFieldName() + " = " + item.getString());
                        }
                    } else {
                        logger.debug(obj.getClass().getName() + " - " + obj.toString());
                    }
                }
            }
        }

        if (filecontent == null) {
            if (PdfAsParameterExtractor.getPdfUrl(request) != null) {
                filecontent = RemotePDFFetcher.fetchPdfFile(PdfAsParameterExtractor.getPdfUrl(request));
            }
        }

        if (filecontent == null) {
            Object sourceObj = request.getAttribute("source");
            if (sourceObj != null) {
                String source = sourceObj.toString();
                if (source.equals("internal")) {
                    request.setAttribute("FILEERR", true);
                    request.getRequestDispatcher("index.jsp").forward(request, response);

                    statisticEvent.setStatus(Status.ERROR);
                    statisticEvent.setException(new Exception("No file uploaded"));
                    statisticEvent.setEndNow();
                    statisticEvent.setTimestampNow();
                    StatisticFrontend.getInstance().storeEvent(statisticEvent);
                    statisticEvent.setLogged(true);

                    return;
                }
            }
            throw new PdfAsException("No Signature data available");
        }

        doSignature(request, response, filecontent, statisticEvent);
    } catch (Exception e) {
        logger.error("Signature failed", e);
        statisticEvent.setStatus(Status.ERROR);
        statisticEvent.setException(e);
        if (e instanceof PDFASError) {
            statisticEvent.setErrorCode(((PDFASError) e).getCode());
        }
        statisticEvent.setEndNow();
        statisticEvent.setTimestampNow();
        StatisticFrontend.getInstance().storeEvent(statisticEvent);
        statisticEvent.setLogged(true);

        PdfAsHelper.setSessionException(request, response, e.getMessage(), e);
        PdfAsHelper.gotoError(getServletContext(), request, response);
    }
}

From source file:com.mx.nibble.middleware.web.util.FileUploadOLD.java

public String execute() throws Exception {

    //ActionContext ac = invocation.getInvocationContext();

    HttpServletResponse response = ServletActionContext.getResponse();

    // MultiPartRequestWrapper multipartRequest = ((MultiPartRequestWrapper)ServletActionContext.getRequest());
    HttpServletRequest multipartRequest = ServletActionContext.getRequest();

    List<FileItem> items2 = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(multipartRequest);
    System.out.println("TAMAO ITEMS " + items2.size());
    System.out.println("Check that we have a file upload request");
    boolean isMultipart = ServletFileUpload.isMultipartContent(multipartRequest);
    System.out.println("isMultipart: " + isMultipart);

    String ourTempDirectory = "/opt/erp/import/obras/";

    byte[] cr = { 13 };
    byte[] lf = { 10 };
    String CR = new String(cr);
    String LF = new String(lf);
    String CRLF = CR + LF;//  w  w  w. j ava  2 s  .c  om
    System.out.println("Before a LF=chr(10)" + LF + "Before a CR=chr(13)" + CR + "Before a CRLF" + CRLF);

    //Initialization for chunk management.
    boolean bLastChunk = false;
    int numChunk = 0;

    //CAN BE OVERRIDEN BY THE postURL PARAMETER: if error=true is passed as a parameter on the URL
    boolean generateError = false;
    boolean generateWarning = false;
    boolean sendRequest = false;

    response.setContentType("text/plain");

    java.util.Enumeration<String> headers = multipartRequest.getHeaderNames();
    System.out.println("[parseRequest.jsp]  ------------------------------ ");
    System.out.println("[parseRequest.jsp]  Headers of the received request:");
    while (headers.hasMoreElements()) {
        String header = headers.nextElement();
        System.out.println("[parseRequest.jsp]  " + header + ": " + multipartRequest.getHeader(header));
    }
    System.out.println("[parseRequest.jsp]  ------------------------------ ");

    try {
        System.out.println(" Get URL Parameters.");
        Enumeration paraNames = multipartRequest.getParameterNames();
        System.out.println("[parseRequest.jsp]  ------------------------------ ");
        System.out.println("[parseRequest.jsp]  Parameters: ");
        String pname;
        String pvalue;
        while (paraNames.hasMoreElements()) {
            pname = (String) paraNames.nextElement();
            pvalue = multipartRequest.getParameter(pname);
            System.out.println("[parseRequest.jsp] " + pname + " = " + pvalue);
            if (pname.equals("jufinal")) {
                System.out.println("pname.equals(\"jufinal\")");
                bLastChunk = pvalue.equals("1");
            } else if (pname.equals("jupart")) {
                System.out.println("pname.equals(\"jupart\")");
                numChunk = Integer.parseInt(pvalue);
            }

            //For debug convenience, putting error=true as a URL parameter, will generate an error
            //in this response.
            if (pname.equals("error") && pvalue.equals("true")) {
                generateError = true;
            }

            //For debug convenience, putting warning=true as a URL parameter, will generate a warning
            //in this response.
            if (pname.equals("warning") && pvalue.equals("true")) {
                generateWarning = true;
            }

            //For debug convenience, putting readRequest=true as a URL parameter, will send back the request content
            //into the response of this page.
            if (pname.equals("sendRequest") && pvalue.equals("true")) {
                sendRequest = true;
            }

        }
        System.out.println("[parseRequest.jsp]  ------------------------------ ");

        int ourMaxMemorySize = 10000000;
        int ourMaxRequestSize = 2000000000;

        ///////////////////////////////////////////////////////////////////////////////////////////////////////
        //The code below is directly taken from the jakarta fileupload common classes
        //All informations, and download, available here : http://jakarta.apache.org/commons/fileupload/
        ///////////////////////////////////////////////////////////////////////////////////////////////////////

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

        // Set factory constraints
        factory.setSizeThreshold(ourMaxMemorySize);
        factory.setRepository(new File(ourTempDirectory));

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

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

        // Parse the request
        if (sendRequest) {
            //For debug only. Should be removed for production systems. 
            System.out.println(
                    "[parseRequest.jsp] ===========================================================================");
            System.out.println("[parseRequest.jsp] Sending the received request content: ");
            InputStream is = multipartRequest.getInputStream();
            int c;
            while ((c = is.read()) >= 0) {
                System.out.write(c);
            } //while
            is.close();
            System.out.println(
                    "[parseRequest.jsp] ===========================================================================");
        } else if (!multipartRequest.getContentType().startsWith("multipart/form-data")) {
            System.out.println("[parseRequest.jsp] No parsing of uploaded file: content type is "
                    + multipartRequest.getContentType());
        } else {
            List /* FileItem */ items = upload.parseRequest(multipartRequest);
            // Process the uploaded items
            Iterator iter = items.iterator();
            FileItem fileItem;
            File fout;
            System.out.println("[parseRequest.jsp]  Let's read the sent data   (" + items.size() + " items)");
            while (iter.hasNext()) {
                fileItem = (FileItem) iter.next();

                if (fileItem.isFormField()) {
                    System.out.println("[parseRequest.jsp] (form field) " + fileItem.getFieldName() + " = "
                            + fileItem.getString());

                    //If we receive the md5sum parameter, we've read finished to read the current file. It's not
                    //a very good (end of file) signal. Will be better in the future ... probably !
                    //Let's put a separator, to make output easier to read.
                    if (fileItem.getFieldName().equals("md5sum[]")) {
                        System.out.println("[parseRequest.jsp]  ------------------------------ ");
                    }
                } else {
                    //Ok, we've got a file. Let's process it.
                    //Again, for all informations of what is exactly a FileItem, please
                    //have a look to http://jakarta.apache.org/commons/fileupload/
                    //
                    System.out.println("[parseRequest.jsp] FieldName: " + fileItem.getFieldName());
                    System.out.println("[parseRequest.jsp] File Name: " + fileItem.getName());
                    System.out.println("[parseRequest.jsp] ContentType: " + fileItem.getContentType());
                    System.out.println("[parseRequest.jsp] Size (Bytes): " + fileItem.getSize());
                    //If we are in chunk mode, we add ".partN" at the end of the file, where N is the chunk number.
                    String uploadedFilename = fileItem.getName() + (numChunk > 0 ? ".part" + numChunk : "");
                    fout = new File(ourTempDirectory + (new File(uploadedFilename)).getName());
                    System.out.println("[parseRequest.jsp] File Out: " + fout.toString());
                    System.out.println(" write the file");
                    fileItem.write(fout);

                    //////////////////////////////////////////////////////////////////////////////////////
                    System.out.println(
                            " Chunk management: if it was the last chunk, let's recover the complete file");
                    System.out.println(" by concatenating all chunk parts.");
                    //
                    if (bLastChunk) {
                        System.out.println(
                                "[parseRequest.jsp]  Last chunk received: let's rebuild the complete file ("
                                        + fileItem.getName() + ")");
                        //First: construct the final filename.
                        FileInputStream fis;
                        FileOutputStream fos = new FileOutputStream(ourTempDirectory + fileItem.getName());
                        int nbBytes;
                        byte[] byteBuff = new byte[1024];
                        String filename;
                        for (int i = 1; i <= numChunk; i += 1) {
                            filename = fileItem.getName() + ".part" + i;
                            System.out.println("[parseRequest.jsp] " + "  Concatenating " + filename);
                            fis = new FileInputStream(ourTempDirectory + filename);
                            while ((nbBytes = fis.read(byteBuff)) >= 0) {
                                //out.println("[parseRequest.jsp] " + "     Nb bytes read: " + nbBytes);
                                fos.write(byteBuff, 0, nbBytes);
                            }
                            fis.close();
                        }
                        fos.close();
                    }

                    // End of chunk management
                    //////////////////////////////////////////////////////////////////////////////////////

                    fileItem.delete();
                }
            } //while
        }

        if (generateWarning) {
            System.out.println("WARNING: just a warning message.\\nOn two lines!");
        }

        System.out.println("[parseRequest.jsp] " + "Let's write a status, to finish the server response :");

        //Let's wait a little, to simulate the server time to manage the file.
        Thread.sleep(500);

        //Do you want to test a successful upload, or the way the applet reacts to an error ?
        if (generateError) {
            System.out.println(
                    "ERROR: this is a test error (forced in /wwwroot/pages/parseRequest.jsp).\\nHere is a second line!");
        } else {
            System.out.println("SUCCESS");
            //out.println("                        <span class=\"cpg_user_message\">Il y eu une erreur lors de l'excution de la requte</span>");
        }

        System.out.println("[parseRequest.jsp] " + "End of server treatment ");

    } catch (Exception e) {
        System.out.println("");
        System.out.println("ERROR: Exception e = " + e.toString());
        System.out.println("");
    }
    return SUCCESS;
}

From source file:de.ingrid.portal.portlets.ContactPortlet.java

public void processAction(ActionRequest request, ActionResponse actionResponse)
        throws PortletException, IOException {
    List<FileItem> items = null;
    File uploadFile = null;//from www .  j a  va2 s . c om
    boolean uploadEnable = PortalConfig.getInstance().getBoolean(PortalConfig.PORTAL_CONTACT_UPLOAD_ENABLE,
            Boolean.FALSE);
    int uploadSize = PortalConfig.getInstance().getInt(PortalConfig.PORTAL_CONTACT_UPLOAD_SIZE, 10);

    RequestContext requestContext = (RequestContext) request.getAttribute(RequestContext.REQUEST_PORTALENV);
    HttpServletRequest servletRequest = requestContext.getRequest();
    if (ServletFileUpload.isMultipartContent(servletRequest)) {
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // Set factory constraints
        factory.setSizeThreshold(uploadSize * 1000 * 1000);
        File file = new File(".");
        factory.setRepository(file);
        ServletFileUpload.isMultipartContent(servletRequest);
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Set overall request size constraint
        upload.setSizeMax(uploadSize * 1000 * 1000);

        // Parse the request
        try {
            items = upload.parseRequest(servletRequest);
        } catch (FileUploadException e) {
            // TODO Auto-generated catch block
        }
    }
    if (items != null) {
        // check form input
        if (request.getParameter(PARAMV_ACTION_DB_DO_REFRESH) != null) {

            ContactForm cf = (ContactForm) Utils.getActionForm(request, ContactForm.SESSION_KEY,
                    ContactForm.class);
            cf.populate(items);

            String urlViewParam = "?" + Utils.toURLParam(Settings.PARAM_ACTION, Settings.MSGV_TRUE);
            actionResponse.sendRedirect(actionResponse.encodeURL(Settings.PAGE_CONTACT + urlViewParam));
            return;
        } else {
            Boolean isResponseCorrect = false;

            ContactForm cf = (ContactForm) Utils.getActionForm(request, ContactForm.SESSION_KEY,
                    ContactForm.class);
            cf.populate(items);
            if (!cf.validate()) {
                // add URL parameter indicating that portlet action was called
                // before render request

                String urlViewParam = "?" + Utils.toURLParam(Settings.PARAM_ACTION, Settings.MSGV_TRUE);
                actionResponse.sendRedirect(actionResponse.encodeURL(Settings.PAGE_CONTACT + urlViewParam));

                return;
            }

            //remenber that we need an id to validate!
            String sessionId = request.getPortletSession().getId();
            //retrieve the response
            boolean enableCaptcha = PortalConfig.getInstance().getBoolean("portal.contact.enable.captcha",
                    Boolean.TRUE);

            if (enableCaptcha) {
                String response = request.getParameter("jcaptcha");
                for (FileItem item : items) {
                    if (item.getFieldName() != null) {
                        if (item.getFieldName().equals("jcaptcha")) {
                            response = item.getString();
                            break;
                        }
                    }
                }
                // Call the Service method
                try {
                    isResponseCorrect = CaptchaServiceSingleton.getInstance().validateResponseForID(sessionId,
                            response);
                } catch (CaptchaServiceException e) {
                    //should not happen, may be thrown if the id is not valid
                }
            }

            if (isResponseCorrect || !enableCaptcha) {
                try {
                    IngridResourceBundle messages = new IngridResourceBundle(
                            getPortletConfig().getResourceBundle(request.getLocale()), request.getLocale());

                    HashMap mailData = new HashMap();
                    mailData.put("user.name.given", cf.getInput(ContactForm.FIELD_FIRSTNAME));
                    mailData.put("user.name.family", cf.getInput(ContactForm.FIELD_LASTNAME));
                    mailData.put("user.employer", cf.getInput(ContactForm.FIELD_COMPANY));
                    mailData.put("user.business-info.telecom.telephone", cf.getInput(ContactForm.FIELD_PHONE));
                    mailData.put("user.business-info.online.email", cf.getInput(ContactForm.FIELD_EMAIL));
                    mailData.put("user.area.of.profession",
                            messages.getString("contact.report.email.area.of.profession."
                                    + cf.getInput(ContactForm.FIELD_ACTIVITY)));
                    mailData.put("user.interest.in.enviroment.info",
                            messages.getString("contact.report.email.interest.in.enviroment.info."
                                    + cf.getInput(ContactForm.FIELD_INTEREST)));
                    if (cf.hasInput(ContactForm.FIELD_NEWSLETTER)) {
                        Session session = HibernateUtil.currentSession();
                        Transaction tx = null;

                        try {

                            mailData.put("user.subscribed.to.newsletter", "yes");
                            // check for email address in newsletter list
                            tx = session.beginTransaction();
                            List newsletterDataList = session.createCriteria(IngridNewsletterData.class)
                                    .add(Restrictions.eq("emailAddress", cf.getInput(ContactForm.FIELD_EMAIL)))
                                    .list();
                            tx.commit();
                            // register for newsletter if not already registered
                            if (newsletterDataList.isEmpty()) {
                                IngridNewsletterData data = new IngridNewsletterData();
                                data.setFirstName(cf.getInput(ContactForm.FIELD_FIRSTNAME));
                                data.setLastName(cf.getInput(ContactForm.FIELD_LASTNAME));
                                data.setEmailAddress(cf.getInput(ContactForm.FIELD_EMAIL));
                                data.setDateCreated(new Date());

                                tx = session.beginTransaction();
                                session.save(data);
                                tx.commit();
                            }
                        } catch (Throwable t) {
                            if (tx != null) {
                                tx.rollback();
                            }
                            throw new PortletException(t.getMessage());
                        } finally {
                            HibernateUtil.closeSession();
                        }
                    } else {
                        mailData.put("user.subscribed.to.newsletter", "no");
                    }
                    mailData.put("message.body", cf.getInput(ContactForm.FIELD_MESSAGE));

                    Locale locale = request.getLocale();

                    String language = locale.getLanguage();
                    String localizedTemplatePath = EMAIL_TEMPLATE;
                    int period = localizedTemplatePath.lastIndexOf(".");
                    if (period > 0) {
                        String fixedTempl = localizedTemplatePath.substring(0, period) + "_" + language + "."
                                + localizedTemplatePath.substring(period + 1);
                        if (new File(getPortletContext().getRealPath(fixedTempl)).exists()) {
                            localizedTemplatePath = fixedTempl;
                        }
                    }

                    String emailSubject = messages.getString("contact.report.email.subject");

                    if (PortalConfig.getInstance().getBoolean("email.contact.subject.add.topic",
                            Boolean.FALSE)) {
                        if (cf.getInput(ContactForm.FIELD_ACTIVITY) != null
                                && !cf.getInput(ContactForm.FIELD_ACTIVITY).equals("none")) {
                            emailSubject = emailSubject + " - "
                                    + messages.getString("contact.report.email.area.of.profession."
                                            + cf.getInput(ContactForm.FIELD_ACTIVITY));
                        }
                    }

                    String from = cf.getInput(ContactForm.FIELD_EMAIL);
                    String to = PortalConfig.getInstance().getString(PortalConfig.EMAIL_CONTACT_FORM_RECEIVER,
                            "foo@bar.com");

                    String text = Utils.mergeTemplate(getPortletConfig(), mailData, "map",
                            localizedTemplatePath);
                    if (uploadEnable) {
                        if (uploadEnable) {
                            for (FileItem item : items) {
                                if (item.getFieldName() != null) {
                                    if (item.getFieldName().equals("upload")) {
                                        uploadFile = new File(sessionId + "_" + item.getName());
                                        // read this file into InputStream
                                        InputStream inputStream = item.getInputStream();

                                        // write the inputStream to a FileOutputStream
                                        OutputStream out = new FileOutputStream(uploadFile);
                                        int read = 0;
                                        byte[] bytes = new byte[1024];

                                        while ((read = inputStream.read(bytes)) != -1) {
                                            out.write(bytes, 0, read);
                                        }

                                        inputStream.close();
                                        out.flush();
                                        out.close();
                                        break;
                                    }
                                }
                            }
                        }
                        Utils.sendEmail(from, emailSubject, new String[] { to }, text, null, uploadFile);
                    } else {
                        Utils.sendEmail(from, emailSubject, new String[] { to }, text, null);
                    }
                } catch (Throwable t) {
                    cf.setError("", "Error sending mail from contact form.");
                    log.error("Error sending mail from contact form.", t);
                }

                // temporarily show same page with content
                String urlViewParam = "?" + Utils.toURLParam(Settings.PARAM_ACTION, PARAMV_ACTION_SUCCESS);
                actionResponse.sendRedirect(actionResponse.encodeURL(Settings.PAGE_CONTACT + urlViewParam));
            } else {
                cf.setErrorCaptcha();
                String urlViewParam = "?" + Utils.toURLParam(Settings.PARAM_ACTION, Settings.MSGV_TRUE);
                actionResponse.sendRedirect(actionResponse.encodeURL(Settings.PAGE_CONTACT + urlViewParam));
                return;
            }
        }
    } else {
        ContactForm cf = (ContactForm) Utils.getActionForm(request, ContactForm.SESSION_KEY, ContactForm.class);
        cf.setErrorUpload();
        String urlViewParam = "?" + Utils.toURLParam(Settings.PARAM_ACTION, Settings.MSGV_TRUE);
        actionResponse.sendRedirect(actionResponse.encodeURL(Settings.PAGE_CONTACT + urlViewParam));
        return;
    }
}

From source file:com.glaf.core.web.servlet.FileUploadServlet.java

public void upload(HttpServletRequest request, HttpServletResponse response) {
    response.setContentType("text/html;charset=UTF-8");
    LoginContext loginContext = RequestUtils.getLoginContext(request);
    if (loginContext == null) {
        return;//from   w w  w.j av  a 2 s  .c o  m
    }
    String serviceKey = request.getParameter("serviceKey");
    String type = request.getParameter("type");
    if (StringUtils.isEmpty(type)) {
        type = "0";
    }
    Map<String, Object> paramMap = RequestUtils.getParameterMap(request);
    logger.debug("paramMap:" + paramMap);
    String rootDir = SystemProperties.getConfigRootPath();

    InputStream inputStream = null;
    try {
        DiskFileItemFactory diskFactory = new DiskFileItemFactory();
        // threshold ???? 8M
        diskFactory.setSizeThreshold(8 * FileUtils.MB_SIZE);
        // repository 
        diskFactory.setRepository(new File(rootDir + "/temp"));
        ServletFileUpload upload = new ServletFileUpload(diskFactory);
        int maxUploadSize = conf.getInt(serviceKey + ".maxUploadSize", 0);
        if (maxUploadSize == 0) {
            maxUploadSize = conf.getInt("upload.maxUploadSize", 50);// 50MB
        }
        maxUploadSize = maxUploadSize * FileUtils.MB_SIZE;
        logger.debug("maxUploadSize:" + maxUploadSize);

        upload.setHeaderEncoding("UTF-8");
        upload.setSizeMax(maxUploadSize);
        upload.setFileSizeMax(maxUploadSize);
        String uploadDir = Constants.UPLOAD_PATH;

        if (ServletFileUpload.isMultipartContent(request)) {
            logger.debug("#################start upload process#########################");
            FileItemIterator iter = upload.getItemIterator(request);
            PrintWriter out = response.getWriter();
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                if (!item.isFormField()) {
                    // ????
                    String autoCreatedDateDirByParttern = "yyyy/MM/dd";
                    String autoCreatedDateDir = DateFormatUtils.format(new java.util.Date(),
                            autoCreatedDateDirByParttern);

                    File savePath = new File(rootDir + uploadDir + autoCreatedDateDir);
                    if (!savePath.exists()) {
                        savePath.mkdirs();
                    }

                    String fileId = UUID32.getUUID();
                    String fileName = savePath + "/" + fileId;

                    BlobItem dataFile = new BlobItemEntity();
                    dataFile.setLastModified(System.currentTimeMillis());
                    dataFile.setCreateBy(loginContext.getActorId());
                    dataFile.setFileId(fileId);
                    dataFile.setPath(uploadDir + autoCreatedDateDir + "/" + fileId);
                    dataFile.setFilename(item.getName());
                    dataFile.setName(item.getName());
                    dataFile.setContentType(item.getContentType());
                    dataFile.setType(type);
                    dataFile.setStatus(0);
                    dataFile.setServiceKey(serviceKey);
                    getBlobService().insertBlob(dataFile);

                    inputStream = item.openStream();

                    FileUtils.save(fileName, inputStream);

                    logger.debug(fileName + " save ok.");

                    out.print(fileId);
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        IOUtils.close(inputStream);
    }
}

From source file:cn.webwheel.ActionSetter.java

@SuppressWarnings("unchecked")
public Object[] set(Object action, ActionInfo ai, HttpServletRequest request) throws IOException {
    SetterConfig cfg = ai.getSetterConfig();
    List<SetterInfo> setters;
    if (action != null) {
        Class cls = action.getClass();
        setters = setterMap.get(cls);// w w w. j av a 2  s.  c om
        if (setters == null) {
            synchronized (this) {
                setters = setterMap.get(cls);
                if (setters == null) {
                    Map<Class, List<SetterInfo>> map = new HashMap<Class, List<SetterInfo>>(setterMap);
                    map.put(cls, setters = parseSetters(cls));
                    setterMap = map;
                }
            }
        }
    } else {
        setters = Collections.emptyList();
    }

    List<SetterInfo> args = argMap.get(ai.actionMethod);
    if (args == null) {
        synchronized (this) {
            args = argMap.get(ai.actionMethod);
            if (args == null) {
                Map<Method, List<SetterInfo>> map = new HashMap<Method, List<SetterInfo>>(argMap);
                map.put(ai.actionMethod, args = parseArgs(ai.actionMethod));
                argMap = map;
            }
        }
    }

    if (setters.isEmpty() && args.isEmpty())
        return new Object[0];

    Map<String, Object> params;
    try {
        if (cfg.getCharset() != null) {
            request.setCharacterEncoding(cfg.getCharset());
        }
    } catch (UnsupportedEncodingException e) {
        //
    }

    if (ServletFileUpload.isMultipartContent(request)) {
        params = new HashMap<String, Object>(request.getParameterMap());
        request.setAttribute(WRPName, params);
        ServletFileUpload fileUpload = new ServletFileUpload();
        if (cfg.getCharset() != null) {
            fileUpload.setHeaderEncoding(cfg.getCharset());
        }
        if (cfg.getFileUploadSizeMax() != 0) {
            fileUpload.setSizeMax(cfg.getFileUploadSizeMax());
        }
        if (cfg.getFileUploadFileSizeMax() != 0) {
            fileUpload.setFileSizeMax(cfg.getFileUploadFileSizeMax());
        }
        boolean throwe = false;
        try {
            FileItemIterator it = fileUpload.getItemIterator(request);
            while (it.hasNext()) {
                FileItemStream fis = it.next();
                if (fis.isFormField()) {
                    String s = Streams.asString(fis.openStream(), cfg.getCharset());
                    Object o = params.get(fis.getFieldName());
                    if (o == null) {
                        params.put(fis.getFieldName(), new String[] { s });
                    } else if (o instanceof String[]) {
                        String[] ss = (String[]) o;
                        String[] nss = new String[ss.length + 1];
                        System.arraycopy(ss, 0, nss, 0, ss.length);
                        nss[ss.length] = s;
                        params.put(fis.getFieldName(), nss);
                    }
                } else if (!fis.getName().isEmpty()) {
                    File tempFile;
                    try {
                        tempFile = File.createTempFile("wfu", null);
                    } catch (IOException e) {
                        throwe = true;
                        throw e;
                    }
                    FileExImpl fileEx = new FileExImpl(tempFile);
                    Object o = params.get(fis.getFieldName());
                    if (o == null) {
                        params.put(fis.getFieldName(), new FileEx[] { fileEx });
                    } else if (o instanceof FileEx[]) {
                        FileEx[] ss = (FileEx[]) o;
                        FileEx[] nss = new FileEx[ss.length + 1];
                        System.arraycopy(ss, 0, nss, 0, ss.length);
                        nss[ss.length] = fileEx;
                        params.put(fis.getFieldName(), nss);
                    }
                    Streams.copy(fis.openStream(), new FileOutputStream(fileEx.getFile()), true);
                    fileEx.fileName = fis.getName();
                    fileEx.contentType = fis.getContentType();
                }
            }
        } catch (FileUploadException e) {
            if (action instanceof FileUploadExceptionAware) {
                ((FileUploadExceptionAware) action).setFileUploadException(e);
            }
        } catch (IOException e) {
            if (throwe) {
                throw e;
            }
        }
    } else {
        params = request.getParameterMap();
    }

    if (cfg.getSetterPolicy() == SetterPolicy.ParameterAndField
            || (cfg.getSetterPolicy() == SetterPolicy.Auto && args.isEmpty())) {
        for (SetterInfo si : setters) {
            si.setter.set(action, si.member, params, si.paramName);
        }
    }

    Object[] as = new Object[args.size()];
    for (int i = 0; i < as.length; i++) {
        SetterInfo si = args.get(i);
        as[i] = si.setter.set(action, null, params, si.paramName);
    }
    return as;
}

From source file:com.mx.nibble.middleware.web.util.FileParse.java

public String execute(ActionInvocation invocation) throws Exception {

    Iterator iterator = parameters.entrySet().iterator();
    while (iterator.hasNext()) {
        Map.Entry mapEntry = (Map.Entry) iterator.next();
        System.out.println("The key is: " + mapEntry.getKey() + ",value is :" + mapEntry.getValue());
    }//from   w w w . j a va2 s  . c om

    ActionContext ac = invocation.getInvocationContext();

    HttpServletRequest request = (HttpServletRequest) ac.get(ServletActionContext.HTTP_REQUEST);

    HttpServletResponse response = (HttpServletResponse) ac.get(ServletActionContext.HTTP_RESPONSE);
    /**
    * This pages gives a sample of java upload management. It needs the commons FileUpload library, which can be found on apache.org.
    *
    * Note:
    * - putting error=true as a parameter on the URL will generate an error. Allows test of upload error management in the applet. 
    * 
    * 
    * 
    * 
    * 
    * 
    */

    // Directory to store all the uploaded files
    String ourTempDirectory = "/opt/erp/import/obras/";

    byte[] cr = { 13 };
    byte[] lf = { 10 };
    String CR = new String(cr);
    String LF = new String(lf);
    String CRLF = CR + LF;
    System.out.println("Before a LF=chr(10)" + LF + "Before a CR=chr(13)" + CR + "Before a CRLF" + CRLF);

    //Initialization for chunk management.
    boolean bLastChunk = false;
    int numChunk = 0;

    //CAN BE OVERRIDEN BY THE postURL PARAMETER: if error=true is passed as a parameter on the URL
    boolean generateError = false;
    boolean generateWarning = false;
    boolean sendRequest = false;

    response.setContentType("text/plain");

    java.util.Enumeration<String> headers = request.getHeaderNames();
    System.out.println("[parseRequest.jsp]  ------------------------------ ");
    System.out.println("[parseRequest.jsp]  Headers of the received request:");
    while (headers.hasMoreElements()) {
        String header = headers.nextElement();
        System.out.println("[parseRequest.jsp]  " + header + ": " + request.getHeader(header));
    }
    System.out.println("[parseRequest.jsp]  ------------------------------ ");

    try {
        // Get URL Parameters.
        Enumeration paraNames = request.getParameterNames();
        System.out.println("[parseRequest.jsp]  ------------------------------ ");
        System.out.println("[parseRequest.jsp]  Parameters: ");
        String pname;
        String pvalue;
        while (paraNames.hasMoreElements()) {
            pname = (String) paraNames.nextElement();
            pvalue = request.getParameter(pname);
            System.out.println("[parseRequest.jsp] " + pname + " = " + pvalue);
            if (pname.equals("jufinal")) {
                bLastChunk = pvalue.equals("1");
            } else if (pname.equals("jupart")) {
                numChunk = Integer.parseInt(pvalue);
            }

            //For debug convenience, putting error=true as a URL parameter, will generate an error
            //in this response.
            if (pname.equals("error") && pvalue.equals("true")) {
                generateError = true;
            }

            //For debug convenience, putting warning=true as a URL parameter, will generate a warning
            //in this response.
            if (pname.equals("warning") && pvalue.equals("true")) {
                generateWarning = true;
            }

            //For debug convenience, putting readRequest=true as a URL parameter, will send back the request content
            //into the response of this page.
            if (pname.equals("sendRequest") && pvalue.equals("true")) {
                sendRequest = true;
            }

        }
        System.out.println("[parseRequest.jsp]  ------------------------------ ");

        int ourMaxMemorySize = 10000000;
        int ourMaxRequestSize = 2000000000;

        ///////////////////////////////////////////////////////////////////////////////////////////////////////
        //The code below is directly taken from the jakarta fileupload common classes
        //All informations, and download, available here : http://jakarta.apache.org/commons/fileupload/
        ///////////////////////////////////////////////////////////////////////////////////////////////////////

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

        // Set factory constraints
        factory.setSizeThreshold(ourMaxMemorySize);
        factory.setRepository(new File(ourTempDirectory));

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

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

        // Parse the request
        if (sendRequest) {
            //For debug only. Should be removed for production systems. 
            System.out.println(
                    "[parseRequest.jsp] ===========================================================================");
            System.out.println("[parseRequest.jsp] Sending the received request content: ");
            InputStream is = request.getInputStream();
            int c;
            while ((c = is.read()) >= 0) {
                out.write(c);
            } //while
            is.close();
            System.out.println(
                    "[parseRequest.jsp] ===========================================================================");
        } else if (!request.getContentType().startsWith("multipart/form-data")) {
            System.out.println("[parseRequest.jsp] No parsing of uploaded file: content type is "
                    + request.getContentType());
        } else {
            List /* FileItem */ items = upload.parseRequest(request);
            // Process the uploaded items
            Iterator iter = items.iterator();
            FileItem fileItem;
            File fout;
            System.out.println("[parseRequest.jsp]  Let's read the sent data   (" + items.size() + " items)");
            while (iter.hasNext()) {
                fileItem = (FileItem) iter.next();

                if (fileItem.isFormField()) {
                    System.out.println("[parseRequest.jsp] (form field) " + fileItem.getFieldName() + " = "
                            + fileItem.getString());

                    //If we receive the md5sum parameter, we've read finished to read the current file. It's not
                    //a very good (end of file) signal. Will be better in the future ... probably !
                    //Let's put a separator, to make output easier to read.
                    if (fileItem.getFieldName().equals("md5sum[]")) {
                        System.out.println("[parseRequest.jsp]  ------------------------------ ");
                    }
                } else {
                    //Ok, we've got a file. Let's process it.
                    //Again, for all informations of what is exactly a FileItem, please
                    //have a look to http://jakarta.apache.org/commons/fileupload/
                    //
                    System.out.println("[parseRequest.jsp] FieldName: " + fileItem.getFieldName());
                    System.out.println("[parseRequest.jsp] File Name: " + fileItem.getName());
                    System.out.println("[parseRequest.jsp] ContentType: " + fileItem.getContentType());
                    System.out.println("[parseRequest.jsp] Size (Bytes): " + fileItem.getSize());
                    //If we are in chunk mode, we add ".partN" at the end of the file, where N is the chunk number.
                    String uploadedFilename = fileItem.getName() + (numChunk > 0 ? ".part" + numChunk : "");
                    fout = new File(ourTempDirectory + (new File(uploadedFilename)).getName());
                    System.out.println("[parseRequest.jsp] File Out: " + fout.toString());
                    // write the file
                    fileItem.write(fout);

                    //////////////////////////////////////////////////////////////////////////////////////
                    //Chunk management: if it was the last chunk, let's recover the complete file
                    //by concatenating all chunk parts.
                    //
                    if (bLastChunk) {
                        System.out.println(
                                "[parseRequest.jsp]  Last chunk received: let's rebuild the complete file ("
                                        + fileItem.getName() + ")");
                        //First: construct the final filename.
                        FileInputStream fis;
                        FileOutputStream fos = new FileOutputStream(ourTempDirectory + fileItem.getName());
                        int nbBytes;
                        byte[] byteBuff = new byte[1024];
                        String filename;
                        for (int i = 1; i <= numChunk; i += 1) {
                            filename = fileItem.getName() + ".part" + i;
                            System.out.println("[parseRequest.jsp] " + "  Concatenating " + filename);
                            fis = new FileInputStream(ourTempDirectory + filename);
                            while ((nbBytes = fis.read(byteBuff)) >= 0) {
                                //System.out.println("[parseRequest.jsp] " + "     Nb bytes read: " + nbBytes);
                                fos.write(byteBuff, 0, nbBytes);
                            }
                            fis.close();
                        }
                        fos.close();
                    }

                    // End of chunk management
                    //////////////////////////////////////////////////////////////////////////////////////

                    fileItem.delete();
                }
            } //while
        }

        if (generateWarning) {
            System.out.println("WARNING: just a warning message.\\nOn two lines!");
        }

        System.out.println("[parseRequest.jsp] " + "Let's write a status, to finish the server response :");

        //Let's wait a little, to simulate the server time to manage the file.
        Thread.sleep(500);

        //Do you want to test a successful upload, or the way the applet reacts to an error ?
        if (generateError) {
            System.out.println(
                    "ERROR: this is a test error (forced in /wwwroot/pages/parseRequest.jsp).\\nHere is a second line!");
        } else {
            System.out.println("SUCCESS");
            PrintWriter out = ServletActionContext.getResponse().getWriter();
            out.write("SUCCESS");
            //System.out.println("                        <span class=\"cpg_user_message\">Il y eu une erreur lors de l'excution de la requte</span>");
        }

        System.out.println("[parseRequest.jsp] " + "End of server treatment ");

    } catch (Exception e) {
        System.out.println("");
        System.out.println("ERROR: Exception e = " + e.toString());
        System.out.println("");
    }

    return SUCCESS;

}