Example usage for org.apache.commons.fileupload DiskFileUpload parseRequest

List of usage examples for org.apache.commons.fileupload DiskFileUpload parseRequest

Introduction

In this page you can find the example usage for org.apache.commons.fileupload DiskFileUpload parseRequest.

Prototype

public List  parseRequest(HttpServletRequest req) throws FileUploadException 

Source Link

Document

Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a> compliant <code>multipart/form-data</code> stream.

Usage

From source file:com.syrup.ui.UploadConfigurationServlet.java

/**
 * //from   www  . j  av  a  2 s.  co  m
 * 
 * @param req
 *            basic request
 * @param resp
 *            basic resp
 * @throws ServletException
 *             basic
 * @throws IOException
 *             basic
 */
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    try {
        // Create a new file upload handler
        DiskFileUpload upload = new DiskFileUpload();

        // Parse the request
        List<FileItem> items = upload.parseRequest(req);
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (!item.isFormField()) {

                byte[] data = item.get();

                // Hmm...parse images?
                Util.saveSuccessMessage("Service definitions uploaded.", req);

            }
        }
    } catch (Exception e) {
        Util.saveErrorMessage("Unable to upload or parse file.", req);
    }

    RequestDispatcher dispatch = req.getRequestDispatcher("/upload.jsp");
    dispatch.forward(req, resp);
}

From source file:info.magnolia.cms.filters.CommonsFileUploadMultipartRequestFilter.java

/**
 * Parse the request and store it as a request attribute.
 *///from  w  w  w  .j av  a2s  .  co  m
private void parseRequest(HttpServletRequest request) throws Exception {
    MultipartForm form = new MultipartForm();

    DiskFileUpload upload = newDiskFileUpload();
    List fileItems = upload.parseRequest(request);

    for (Iterator fileItemIterator = fileItems.iterator(); fileItemIterator.hasNext();) {
        FileItem item = (FileItem) fileItemIterator.next();
        if (item.isFormField()) {
            addField(request, item, form);
        } else {
            addFile(item, form);
        }
    }

    request.setAttribute(MultipartForm.REQUEST_ATTRIBUTE_NAME, form);
}

From source file:UploadImage.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //  change the following parameters to connect to the oracle database
    String username = "wang8";
    String password = "Steelrose101";
    String drivername = "oracle.jdbc.driver.OracleDriver";
    String dbstring = "jdbc:oracle:thin:@gwynne.cs.ualberta.ca:1521:CRS";
    int pic_id;/*  ww  w . j  ava 2 s. co m*/

    try {
        //Parse the HTTP request to get the image stream
        DiskFileUpload fu = new DiskFileUpload();
        List FileItems = fu.parseRequest(request);

        // Process the uploaded items, assuming only 1 image file uploaded
        Iterator i = FileItems.iterator();
        FileItem item = (FileItem) i.next();
        while (i.hasNext() && item.isFormField()) {
            item = (FileItem) i.next();
        }

        //Get the image stream
        InputStream instream = item.getInputStream();

        // Connect to the database and create a statement
        Connection conn = getConnected(drivername, dbstring, username, password);
        Statement stmt = conn.createStatement();

        /*
         *  First, to generate a unique pic_id using an SQL sequence
         */
        ResultSet rset1 = stmt.executeQuery("SELECT pic_id_sequence.nextval from dual");
        rset1.next();
        pic_id = rset1.getInt(1);

        //Insert an empty blob into the table first. Note that you have to 
        //use the Oracle specific function empty_blob() to create an empty blob
        stmt.execute("INSERT INTO pictures VALUES(" + pic_id + ",'test',empty_blob())");

        // to retrieve the lob_locator 
        // Note that you must use "FOR UPDATE" in the select statement
        String cmd = "SELECT * FROM pictures WHERE pic_id = " + pic_id + " FOR UPDATE";
        ResultSet rset = stmt.executeQuery(cmd);
        rset.next();
        BLOB myblob = ((OracleResultSet) rset).getBLOB(3);

        //Write the image to the blob object
        OutputStream outstream = myblob.getBinaryOutputStream();
        int size = myblob.getBufferSize();
        byte[] buffer = new byte[size];
        int length = -1;
        while ((length = instream.read(buffer)) != -1)
            outstream.write(buffer, 0, length);
        instream.close();
        outstream.close();

        stmt.executeUpdate("commit");
        response_message = " Upload OK!  ";
        conn.close();

    } catch (Exception ex) {
        //System.out.println( ex.getMessage());
        response_message = ex.getMessage();
    }

    //Output response to the client
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n" + "<HTML>\n"
            + "<HEAD><TITLE>Upload Message</TITLE></HEAD>\n" + "<BODY>\n" + "<H1>" + response_message
            + "</H1>\n" + "</BODY></HTML>");
}

From source file:com.krawler.esp.portalmsg.Forum.java

public static String insertForumPost(Connection conn, HttpServletRequest request)
        throws ServiceException, ParseException, JSONException {
    org.apache.commons.fileupload.DiskFileUpload fu = new org.apache.commons.fileupload.DiskFileUpload();
    java.util.List fileItems = null;
    org.apache.commons.fileupload.FileItem fi = null;
    int sizeinmb = forummsgcomm.getmaxfilesize(conn, AuthHandler.getCompanyid(request, false));
    long maxsize = sizeinmb * 1024 * 1024;
    boolean fileupload = false;
    fu.setSizeMax(maxsize);//from   w w  w.  j av  a 2 s  .  c o  m
    java.util.HashMap arrParam = new java.util.HashMap();
    JSONObject jobj = new JSONObject();
    try {
        fileItems = fu.parseRequest(request);
    } catch (org.apache.commons.fileupload.FileUploadException e) {
        com.krawler.utils.json.base.JSONObject jerrtemp = new com.krawler.utils.json.base.JSONObject();
        jerrtemp.put("Success", "Fail");
        jerrtemp.put("msg", "Problem while uploading file.");
        jobj.append("data", jerrtemp);
        return jobj.toString();
    }
    for (java.util.Iterator k = fileItems.iterator(); k.hasNext();) {
        fi = (org.apache.commons.fileupload.FileItem) k.next();
        arrParam.put(fi.getFieldName(), fi.getString());
        if (!fi.isFormField()) {
            if (fi.getSize() > maxsize) {
                com.krawler.utils.json.base.JSONObject jerrtemp = new com.krawler.utils.json.base.JSONObject();
                jerrtemp.put("Success", "Fail");
                jerrtemp.put("msg", "For attachments, maximum file size allowed is " + sizeinmb + " MB");
                jobj.append("data", jerrtemp);
                return jobj.toString();
            }
            fileupload = true;
        }
    }
    //                destinationDirectory = com.krawler.esp.handlers.StorageHandler
    //               .GetDocStorePath()
    int firstReply = Integer.parseInt(request.getParameter("firstReply"));
    String ptext = java.net.URLDecoder.decode(arrParam.get("ptxt").toString());
    String repto = request.getParameter("repto");
    String title = java.net.URLDecoder.decode(arrParam.get("title").toString());
    String u_id = request.getParameter("userId");
    String group_id = request.getParameter("groupId");
    DbResults rs = null;
    DbResults rs1 = null;
    DbResults rs2 = null;
    String post_id = UUID.randomUUID().toString();
    String topic_id = "1";
    String topic_title = null;
    String dateTime = null;
    String UserName = null;
    String Image = null;
    String query = null;
    JSONStringer j = new JSONStringer();

    String temp = null;
    title = StringUtil.serverHTMLStripper(title);

    group_id = StringUtil.serverHTMLStripper(group_id);
    java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    java.util.Date d = new java.util.Date();
    java.sql.Timestamp sqlPostDate = new Timestamp(d.getTime());
    if (StringUtil.isNullOrEmpty(repto) /*|| StringUtil.isNullOrEmpty(title)*/ || StringUtil.isNullOrEmpty(u_id)
            || StringUtil.isNullOrEmpty(group_id)) {
        com.krawler.utils.json.base.JSONObject jerrtemp = new com.krawler.utils.json.base.JSONObject();
        jerrtemp.put("Success", "Fail");
        jobj.append("data", jerrtemp);
        return jobj.toString();
    }
    if (fileupload) {
        forummsgcomm.doPost(conn, fileItems, post_id, sqlPostDate, u_id, "");
    }
    if (firstReply == 0) {

        query = "INSERT INTO krawlerforum_topics(topic_id, group_id, topic_title, topic_poster, post_time, post_subject,post_text, ifread,flag) VALUES (?, ?, ?, ?, ?, ?,?, ?, ?)";
        DbUtil.executeUpdate(conn, query,
                new Object[] { post_id, group_id, title, u_id, sqlPostDate, ptext, ptext, false, false });

        post_id = "topic" + post_id;
    } else if (firstReply == 1) {
        repto = repto.substring(5);

        query = "INSERT INTO krawlerforum_posts(post_id, post_poster, topic_id, group_id, topic_title,post_time, post_subject, post_text, reply_to, flag, ifread,reply_to_post) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
        DbUtil.executeUpdate(conn, query, new Object[] { post_id, u_id, topic_id, group_id, topic_title,
                sqlPostDate, title, ptext, repto, false, false, "-999" });

        repto = "topic" + repto;
    } else if (firstReply == 2) {
        query = "INSERT INTO krawlerforum_posts(post_id, post_poster, topic_id, group_id, topic_title, post_time, post_subject, post_text, reply_to, flag, ifread,reply_to_post) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
        DbUtil.executeUpdate(conn, query, new Object[] { post_id, u_id, topic_id, group_id, topic_title,
                sqlPostDate, title, ptext, "1", false, false, repto });

    }

    query = "SELECT userlogin.username,image FROM users inner join userlogin on users.userid = userlogin.userid where users.userid=?;";
    rs2 = DbUtil.executeQuery(conn, query, u_id);

    if (rs2.next()) {
        UserName = (rs2.getString(1));
        Image = (rs2.getString(2));
    }
    String userTime = Timezone.toCompanyTimezone(conn, sqlPostDate.toString(),
            CompanyHandler.getCompanyByUser(conn, u_id));
    java.util.Date tempdate = sdf.parse(userTime);
    com.krawler.utils.json.base.JSONObject jtemp = new com.krawler.utils.json.base.JSONObject();
    jtemp.put("Success", "Success");
    jtemp.put("ID", post_id);
    jtemp.put("Subject", title);
    jtemp.put("Received", sdf.format(tempdate));
    jtemp.put("From", UserName);
    jtemp.put("Details", "");
    jtemp.put("Flag", "false");
    jtemp.put("Image", Image);
    jtemp.put("Parent", repto);
    jobj.append("data", jtemp);
    /*temp = j.object().key("Success").value("Success").key("ID").value(
    post_id).key("Subject").value(title).key("Received").value(
    sdf1.format(tempdate).toString()).key("From").value(UserName)
    .key("Details").value("").key("Flag").value("false").key(
    "Image").value(Image).key("Parent").value(repto)
    .endObject().toString();*/
    return jobj.toString();
}

From source file:UploadImage.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // change the following parameters to connect to the oracle database
    String username = "patzelt";
    String password = "Chocolate1";
    String drivername = "oracle.jdbc.driver.OracleDriver";
    String dbstring = "jdbc:oracle:thin:@gwynne.cs.ualberta.ca:1521:CRS";
    int photo_id;

    try {/*  w  ww. j  a  v  a  2  s . c  om*/
        // Parse the HTTP request to get the image stream
        DiskFileUpload fu = new DiskFileUpload();
        List FileItems = fu.parseRequest(request);

        // Process the uploaded items, assuming only 1 image file uploaded
        Iterator i = FileItems.iterator();
        FileItem item = (FileItem) i.next();
        while (i.hasNext() && item.isFormField()) {
            item = (FileItem) i.next();
        }
        long size = item.getSize();

        // Get the image stream
        InputStream instream = item.getInputStream();

        // Connect to the database and create a statement
        Connection conn = getConnected(drivername, dbstring, username, password);
        Statement stmt = conn.createStatement();

        /*
         * First, to generate a unique pic_id using an SQL sequence
         */
        ResultSet rset1 = stmt.executeQuery("SELECT pic_id_sequence.nextval from dual"); // good
        rset1.next();
        photo_id = rset1.getInt(1);
        /**
        // Insert an empty blob into the table first. Note that you have to
        // use the Oracle specific function empty_blob() to create an empty
        // blob
        stmt.execute("INSERT INTO pictures (photo_id, pic_des, pic) VALUES(" + photo_id + ",'test',empty_blob())");
                
        // to retrieve the lob_locator
        // Note that you must use "FOR UPDATE" in the select statement
        String cmd = "SELECT * FROM pictures WHERE photo_id = " + photo_id + " FOR UPDATE";
        ResultSet rset = stmt.executeQuery(cmd);
        rset.next();
        BLOB myblob = ((OracleResultSet) rset).getBLOB(3);
                
        **/

        stmt.execute("INSERT INTO pictures VALUES(" + photo_id + ",'test',empty_blob())");

        PreparedStatement stmt1 = conn
                .prepareStatement("UPDATE pictures SET pic = ? WHERE photo_id = + " + photo_id);
        stmt1.setBinaryStream(1, instream);
        stmt1.executeUpdate();

        /**
        // Write the image to the blob object
        OutputStream outstream = myblob.setBinaryStream(size);
        //int bufferSize = myblob.getBufferSize();
        //byte[] buffer = new byte[bufferSize];
        //int length = -1;
        //while ((length = instream.read(buffer)) != -1)
           //outstream.write(buffer, 0, length);
        outstream.write(pic);
        instream.close();
        outstream.close();
                
        //String update = "UPDATE pictures SET pic = " + myblob + " WHERE photo_id = " + photo_id;
        //stmt.execute(update);
        **/

        response_message = "YAHHOOOOOO";
        conn.close();

    } catch (Exception ex) {
        // System.out.println( ex.getMessage());
        response_message = ex.getMessage();
    }

    // Output response to the client
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n" + "<HTML>\n"
            + "<HEAD><TITLE>Upload Message</TITLE></HEAD>\n" + "<BODY>\n" + "<H1>" + response_message
            + "</H1>\n" + "</BODY></HTML>");
}

From source file:com.globalsight.everest.webapp.pagehandler.administration.vendors.VendorHelper.java

/**
 * Save the request parameters from the CV/Resume page
 *//*w ww  . jav a  2 s. c  o  m*/
public static void saveCV(Vendor vendor, HttpServletRequest request) throws EnvoyServletException {
    // Create a new file upload handler
    DiskFileUpload upload = new DiskFileUpload();

    String radioValue = null;
    String resumeText = null;
    boolean doUpload = false;
    byte[] data = null;
    String filename = null;
    // Parse the request
    try {
        List /* FileItem */ items = upload.parseRequest(request);
        // Process the uploaded items
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField()) {
                String name = item.getFieldName();
                String value = EditUtil.utf8ToUnicode(item.getString());
                if (name.equals("radioBtn")) {
                    radioValue = value;
                } else if (name.equals("resumeText")) {
                    resumeText = value;
                }
            } else {
                filename = item.getName();
                if (filename == null || filename.equals("")) {
                    // user hit done button but didn't modify the page
                    continue;
                } else {
                    doUpload = true;
                    data = item.get();
                }
            }
        }
        if (radioValue != null) {
            if (radioValue.equals("doc") && doUpload) {
                vendor.setResume(filename, data);
                try {
                    ServerProxy.getVendorManagement().saveResumeFile(vendor);
                } catch (Exception e) {
                    throw new EnvoyServletException(e);
                }
            } else if (radioValue.equals("text")) {
                vendor.setResume(resumeText);
            }
        }
    } catch (FileUploadException fe) {
        throw new EnvoyServletException(fe);
    }
}

From source file:UploadImage.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //  change the following parameters to connect to the oracle database
    String username = "lingbo";
    String password = "TlboSci1994";
    String drivername = "oracle.jdbc.driver.OracleDriver";
    String dbstring = "jdbc:oracle:thin:@gwynne.cs.ualberta.ca:1521:CRS";
    int pic_id;/*from  w  ww.j a  v  a2  s  .  c om*/

    try {
        //Parse the HTTP request to get the image stream
        DiskFileUpload fu = new DiskFileUpload();
        List FileItems = fu.parseRequest(request);

        // Process the uploaded items, assuming only 1 image file uploaded
        Iterator i = FileItems.iterator();
        FileItem item = (FileItem) i.next();
        while (i.hasNext() && item.isFormField()) {
            item = (FileItem) i.next();
        }

        //Get the image stream
        InputStream instream = item.getInputStream();

        BufferedImage img = ImageIO.read(instream);
        BufferedImage thumbNail = shrink(img, 10);

        // Connect to the database and create a statement
        Connection conn = getConnected(drivername, dbstring, username, password);
        Statement stmt = conn.createStatement();

        /*
         *  First, to generate a unique pic_id using an SQL sequence
         */
        ResultSet rset1 = stmt.executeQuery("SELECT pic_id_sequence.nextval from dual");
        rset1.next();
        pic_id = rset1.getInt(1);

        //Insert an empty blob into the table first. Note that you have to 
        //use the Oracle specific function empty_blob() to create an empty blob
        stmt.execute("INSERT INTO pictures VALUES(" + pic_id + ",'test',empty_blob())");

        // to retrieve the lob_locator 
        // Note that you must use "FOR UPDATE" in the select statement
        String cmd = "SELECT * FROM pictures WHERE pic_id = " + pic_id + " FOR UPDATE";
        ResultSet rset = stmt.executeQuery(cmd);
        rset.next();
        BLOB myblob = ((OracleResultSet) rset).getBLOB(3);

        //Write the image to the blob object
        OutputStream outstream = myblob.setBinaryStream(1);
        ImageIO.write(thumbNail, "jpg", outstream);

        /*
        int size = myblob.getBufferSize();
        byte[] buffer = new byte[size];
        int length = -1;
        while ((length = instream.read(buffer)) != -1)
        outstream.write(buffer, 0, length);
        */
        instream.close();
        outstream.close();

        stmt.executeUpdate("commit");
        response_message = " Upload OK!  ";
        conn.close();

    } catch (Exception ex) {
        //System.out.println( ex.getMessage());
        response_message = ex.getMessage();
    }

    //Output response to the client
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n" + "<HTML>\n"
            + "<HEAD><TITLE>Upload Message</TITLE></HEAD>\n" + "<BODY>\n" + "<H1>" + response_message
            + "</H1>\n" + "</BODY></HTML>");
}

From source file:com.krawler.esp.servlets.deskeramob.java

public static String createProject(Connection conn, HttpServletRequest request, String companyid,
        String subdomain, String userid) throws ServiceException {
    String status = "";
    DiskFileUpload fu = new DiskFileUpload();
    java.util.List fileItems = null;
    PreparedStatement pstmt = null;
    String imageName = "";
    try {/*from   w w w.  j a  v a  2 s. c om*/
        fileItems = fu.parseRequest(request);
    } catch (FileUploadException e) {
        throw ServiceException.FAILURE("Admin.createProject", e);
    }

    java.util.HashMap arrParam = new java.util.HashMap();
    java.util.Iterator k = null;
    for (k = fileItems.iterator(); k.hasNext();) {
        FileItem fi1 = (FileItem) k.next();
        arrParam.put(fi1.getFieldName(), fi1.getString());
    }
    try {
        pstmt = conn
                .prepareStatement("select count(projectid) from project where companyid =? AND archived = 0");
        pstmt.setString(1, companyid);
        ResultSet rs = pstmt.executeQuery();
        int noProjects = 0;
        int maxProjects = 0;
        if (rs.next()) {
            noProjects = rs.getInt(1);
        }
        pstmt = conn.prepareStatement("select maxprojects from company where companyid =?");
        pstmt.setString(1, companyid);
        rs = pstmt.executeQuery();
        if (rs.next()) {
            maxProjects = rs.getInt(1);
        }
        if (noProjects == maxProjects) {
            return "The maximum limit for projects for this company has already reached";
        }
    } catch (SQLException e) {
        throw ServiceException.FAILURE("ProfileHandler.getPersonalInfo", e);
    }
    try {
        String projectid = UUID.randomUUID().toString();
        String projName = StringUtil.serverHTMLStripper(arrParam.get("projectname").toString()
                .replaceAll("[^\\w|\\s|'|\\-|\\[|\\]|\\(|\\)]", "").trim());
        String nickName = AdminServlet.makeNickName(conn, projName, 1);
        if (StringUtil.isNullOrEmpty(projName)) {
            status = "failure";
        } else {
            String qry = "INSERT INTO project (projectid,projectname,description,image,companyid, nickname) VALUES (?,?,?,?,?,?)";
            pstmt = conn.prepareStatement(qry);
            pstmt.setString(1, projectid);
            pstmt.setString(2, projName);
            pstmt.setString(3, arrParam.get("aboutproject").toString());
            pstmt.setString(4, imageName);
            pstmt.setString(5, companyid);
            pstmt.setString(6, nickName);
            int df = pstmt.executeUpdate();
            if (df != 0) {
                pstmt = conn.prepareStatement(
                        "INSERT INTO projectmembers (projectid, userid, status, inuseflag, planpermission) "
                                + "VALUES (?, ?, ?, ?, ?)");
                pstmt.setString(1, projectid);
                pstmt.setString(2, userid);
                pstmt.setInt(3, 4);
                pstmt.setBoolean(4, true);
                pstmt.setInt(5, 0);
                pstmt.executeUpdate();
            }
            //                        /DbUtil.executeUpdate(conn,qry,new Object[] { projectid,projName,arrParam.get("aboutproject"), imageName,companyid, nickName});
            if (arrParam.get("image").toString().length() != 0) {
                genericFileUpload uploader = new genericFileUpload();
                uploader.doPost(fileItems, projectid, StorageHandler.GetProfileImgStorePath());
                if (uploader.isUploaded()) {
                    pstmt = null;
                    //                                        DbUtil.executeUpdate(conn,
                    //                                                        "update project set image=? where projectid = ?",
                    //                                                        new Object[] {
                    //                                                                        ProfileImageServlet.ImgBasePath + projectid
                    //                                                                                        + uploader.getExt(), projectid });

                    pstmt = conn.prepareStatement("update project set image=? where projectid = ?");
                    pstmt.setString(1, ProfileImageServlet.ImgBasePath + projectid + uploader.getExt());
                    pstmt.setString(2, projectid);
                    pstmt.executeUpdate();
                    imageName = projectid + uploader.getExt();
                }
            }
            com.krawler.esp.handlers.Forum.setStatusProject(conn, userid, projectid, 4, 0, "", subdomain);
            status = "success";
            AdminServlet.setDefaultWorkWeek(conn, projectid);
            conn.commit();
        }
    } catch (ConfigurationException e) {
        status = "failure";
        throw ServiceException.FAILURE("Admin.createProject", e);
    } catch (SQLException e) {
        status = "failure";
        throw ServiceException.FAILURE("Admin.createProject", e);
    }
    return status;
}

From source file:com.fdt.sdl.admin.ui.action.UploadAction.java

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws IOException, ServletException {
    if (!SecurityUtil.isAdminUser(request))
        return (mapping.findForward("welcome"));

    ActionMessages messages = new ActionMessages();
    ActionMessages errors = new ActionMessages();

    if (FileUpload.isMultipartContent(request)) {
        try {/*w  w  w  . ja  va 2  s.  c o  m*/
            //read old dataset values
            ServerConfiguration sc = ServerConfiguration.getServerConfiguration();
            ArrayList<DatasetConfiguration> old_dcs = ServerConfiguration.getDatasetConfigurations();
            Map<String, Long> oldModifiedTimes = new HashMap<String, Long>(old_dcs.size());
            for (DatasetConfiguration old_dc : old_dcs) {
                oldModifiedTimes.put(old_dc.getName(), old_dc.getConfigFile().lastModified());
            }

            DiskFileUpload upload = new DiskFileUpload();
            upload.setSizeMax(10 * 1024 * 1024);
            List items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField()) {
                } else {
                    String fileName = (new File(item.getName())).getName();
                    if (fileName.endsWith(".zip")) {
                        try {
                            extractZip(item.getInputStream());
                        } catch (Exception ee) {
                            logger.error("exception for zip:" + ee);
                            ee.printStackTrace();
                        }
                    }
                }
            }
            messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("action.uploadFiles.success"));
            saveMessages(request, messages);

            //merge old values into the new data set
            if (sc.getIsMergingOldDatasetValues()) {
                ArrayList<DatasetConfiguration> new_dcs = ServerConfiguration.getDatasetConfigurations();
                for (DatasetConfiguration new_dc : new_dcs) {
                    if (oldModifiedTimes.get(new_dc.getName()) != null
                            && new_dc.getConfigFile().lastModified() > oldModifiedTimes.get(new_dc.getName())) {
                        for (DatasetConfiguration old_dc : old_dcs) {
                            if (new_dc.getName() == old_dc.getName()) {
                                new_dc.merge(old_dc);
                                new_dc.save();
                                break;
                            }
                        }
                    }
                }
            }

            if (sc.getAllowedLicenseLevel() > 0) {
                //reload from the disk
                ArrayList<DatasetConfiguration> dcs = ServerConfiguration.getDatasetConfigurations();
                for (DatasetConfiguration dc : dcs) {
                    try {
                        SchedulerTool.scheduleIndexingJob(dc);
                    } catch (Throwable t) {
                        logger.info("Failed to schedule for " + dc.getName() + ": " + t.toString());
                    }
                }
            }

            return mapping.findForward("continue");
        } catch (Exception e) {
            errors.add("error", new ActionMessage("action.uploadFiles.error"));
            saveErrors(request, errors);
            return mapping.findForward("continue");
        }
    } else { // from other page
        //
    }

    return mapping.findForward("continue");
}

From source file:com.w4t.engine.requests.FileUploadRequest.java

public FileUploadRequest(final HttpServletRequest request) throws ServletException {
    super(request);
    IConfiguration configuration = ConfigurationReader.getConfiguration();
    IFileUpload fileUpload = configuration.getFileUpload();
    UploadRequestFileItemFactory factory = new UploadRequestFileItemFactory();
    DiskFileUpload upload = new DiskFileUpload(factory);
    upload.setSizeThreshold(fileUpload.getMaxMemorySize());
    upload.setSizeMax(fileUpload.getMaxMemorySize());
    upload.setRepositoryPath(FileUploadRequest.SYSTEM_TEMP_DIR);
    try {/*from w ww . j  a v  a 2 s. c o  m*/
        List items = upload.parseRequest(request);
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            parameters.put(item.getFieldName(), item);
        }

    } catch (FileUploadException e) {
        throw new ServletExceptionAdapter(e);
    }
}