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

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

Introduction

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

Prototype

public void setSizeMax(long sizeMax) 

Source Link

Document

Sets the maximum allowed upload size.

Usage

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

public static String uploadDocument(HttpServletRequest request, String fileid) throws ServiceException {
    String result = "";
    try {//w  w w. ja va2s .c  om
        String destinationDirectory = StorageHandler.GetDocStorePath() + StorageHandler.GetFileSeparator()
                + "importplans";
        org.apache.commons.fileupload.DiskFileUpload fu = new org.apache.commons.fileupload.DiskFileUpload();
        org.apache.commons.fileupload.FileItem fi = null;
        org.apache.commons.fileupload.FileItem docTmpFI = null;

        List fileItems = null;
        try {
            fileItems = fu.parseRequest(request);
        } catch (FileUploadException e) {
            KrawlerLog.op.warn("Problem While Uploading file :" + e.toString());
        }

        long size = 0;
        String Ext = "";
        String fileName = null;
        boolean fileupload = false;
        java.io.File destDir = new java.io.File(destinationDirectory);
        fu.setSizeMax(-1);
        fu.setSizeThreshold(4096);
        fu.setRepositoryPath(destinationDirectory);
        java.util.HashMap arrParam = new java.util.HashMap();
        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()) {
                size = fi.getSize();
                fileName = new String(fi.getName().getBytes(), "UTF8");

                docTmpFI = fi;
                fileupload = true;
            }
        }

        if (fileupload) {

            if (!destDir.exists()) {
                destDir.mkdirs();
            }
            if (fileName.contains(".")) {
                Ext = fileName.substring(fileName.lastIndexOf("."));
            }
            if (size != 0) {
                File uploadFile = new File(destinationDirectory + "/" + fileid + Ext);
                docTmpFI.write(uploadFile);
                //                    fildoc(fileid, fileName, fileid + Ext, AuthHandler.getUserid(request), size);
                result = fileid + Ext;
            }
        }
    } catch (ConfigurationException ex) {
        Logger.getLogger(importProjectPlanCSV.class.getName()).log(Level.SEVERE, null, ex);
        throw ServiceException.FAILURE("importProjectPlanCSV.uploadDocument", ex);
    } catch (Exception ex) {
        Logger.getLogger(importProjectPlanCSV.class.getName()).log(Level.SEVERE, null, ex);
        throw ServiceException.FAILURE("importProjectPlanCSV.uploadDocument", ex);
    }
    return result;
}

From source file:com.sun.faban.harness.webclient.CLIServlet.java

private void doSubmit(String[] reqC, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (reqC.length < 3) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                "Benchmark and profile not provided in request.");
        return;/*from   w w w .  j av a  2s .c o  m*/
    }
    // first is the bench name
    BenchmarkDescription desc = BenchmarkDescription.getDescription(reqC[1]);
    if (desc == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Benchmark " + reqC[1] + " not deployed.");
        return;
    }
    try {
        String user = null;
        String password = null;
        boolean hasPermission = true;

        ArrayList<String> runIdList = new ArrayList<String>();

        DiskFileUpload fu = new DiskFileUpload();
        // No maximum size
        fu.setSizeMax(-1);
        // maximum size that will be stored in memory
        fu.setSizeThreshold(8192);
        // the location for saving data larger than getSizeThreshold()
        fu.setRepositoryPath(Config.TMP_DIR);

        List fileItems = null;
        try {
            fileItems = fu.parseRequest(request);
        } catch (FileUploadException e) {
            throw new ServletException(e);
        }

        for (Iterator i = fileItems.iterator(); i.hasNext();) {
            FileItem item = (FileItem) i.next();
            String fieldName = item.getFieldName();
            if (item.isFormField()) {
                if ("sun".equals(fieldName)) {
                    user = item.getString();
                } else if ("sp".equals(fieldName)) {
                    password = item.getString();
                }
                continue;
            }
            if (reqC[2] == null) // No profile
                break;

            if (desc == null)
                break;

            if (!"configfile".equals(fieldName))
                continue;

            if (Config.SECURITY_ENABLED) {
                if (Config.CLI_SUBMITTER == null || Config.CLI_SUBMITTER.length() == 0
                        || !Config.CLI_SUBMITTER.equals(user)) {
                    hasPermission = false;
                    break;
                }
                if (Config.SUBMIT_PASSWORD == null || Config.SUBMIT_PASSWORD.length() == 0
                        || !Config.SUBMIT_PASSWORD.equals(password)) {
                    hasPermission = false;
                    break;
                }
            }

            String usrDir = Config.PROFILES_DIR + reqC[2];
            File dir = new File(usrDir);
            if (dir.exists()) {
                if (!dir.isDirectory()) {
                    logger.severe(usrDir + " should be a directory");
                    dir.delete();
                    logger.fine(dir + " deleted");
                } else
                    logger.fine("Saving parameter file to" + usrDir);
            } else {
                logger.fine("Creating new profile directory for " + reqC[2]);
                if (dir.mkdirs())
                    logger.fine("Created new profile directory " + usrDir);
                else
                    logger.severe("Failed to create profile " + "directory " + usrDir);
            }

            // Save the latest config file into the profile directory
            String dstFile = Config.PROFILES_DIR + reqC[2] + File.separator + desc.configFileName + "."
                    + desc.shortName;

            item.write(new File(dstFile));
            runIdList.add(RunQ.getHandle().addRun(user, reqC[2], desc));
        }

        response.setContentType("text/plain");
        Writer writer = response.getWriter();

        if (!hasPermission) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            writer.write("Permission denied!\n");
        }

        if (runIdList.size() == 0)
            writer.write("No runs submitted.\n");
        for (String newRunId : runIdList) {
            writer.write(newRunId);
        }

        writer.flush();
        writer.close();
    } catch (ServletException e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
        throw e;
    } catch (IOException e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
        throw e;
    } catch (Exception e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
        throw new ServletException(e);
    }
}

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

public static String insertMailMsg(Connection conn, javax.servlet.http.HttpServletRequest request,
        String companyid) 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, companyid);
    long maxsize = sizeinmb * 1024 * 1024;
    fu.setSizeMax(maxsize);
    boolean fileupload = false;
    java.util.HashMap arrParam = new java.util.HashMap();
    JSONObject jobj = new JSONObject();
    try {//from ww w. ja  v a  2 s  . c  o  m
        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();
        if (e.getClass().getSimpleName().equalsIgnoreCase("SizeLimitExceededException")) {
            jerrtemp.put("msg", "For attachments, maximum file size allowed is " + sizeinmb + "MB");
        } else {
            jerrtemp.put("msg", "Problem while uploading file.");
        }
        jerrtemp.put("Success", "Fail");
        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", "Attachment size should be upto " + sizeinmb + "MB");
                jobj.append("data", jerrtemp);
                return jobj.toString();
            }
            fileupload = true;
        }
    }
    String poster_id = request.getParameter("userId");
    String post_subject = StringUtil
            .serverHTMLStripper(java.net.URLDecoder.decode(arrParam.get("title").toString()));
    String post_text = java.net.URLDecoder.decode(arrParam.get("ptxt").toString());
    String folder = "1";
    Boolean readflag = false;
    String last_folder_id = "1";
    String reply_to = "";
    String sendflag = StringUtil.serverHTMLStripper(request.getParameter("sendflag"));
    String post_id1 = "";
    String to_id = "";
    String msgFor = "";
    String fid = "";
    String sendefolderpostid = "";
    Boolean done = false;
    String[] tos = {};
    if (sendflag.compareTo("reply") == 0) {
        post_id1 = StringUtil.serverHTMLStripper(request.getParameter("repto"));
        msgFor = getUserFromPost(conn, post_id1);
        fid = StringUtil.serverHTMLStripper(request.getParameter("fid"));
        if (fid.compareTo("3") != 0) {
            to_id = msgFor;
        }
    } else if (sendflag.compareTo("newmsg") == 0) {
        tos = request.getParameter("repto").split(";");
        fid = StringUtil.serverHTMLStripper(request.getParameter("fid"));
        msgFor = to_id;
    }
    int draft = Integer.parseInt(request.getParameter("draft"));

    String query;
    String post_id = "";
    String temp = "";
    //                JSONObject jobj = new JSONObject();
    String usr = to_id;
    DbResults rs1 = null;
    DbResults rs2 = null;
    int numRows = 0;
    boolean uploaded = false;
    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 java.sql.Timestamp(d.getTime());
    UserDAO userDao = new UserDAOImpl();
    if (sendflag.compareTo("reply") == 0) {
        if (draft == 1) {
            post_id = UUID.randomUUID().toString();
            folder = getDraftId(poster_id);//"3";
            last_folder_id = "0";
            readflag = false;
            reply_to = "";
            if (fid.compareTo("3") != 0) {
                if (StringUtil.isNullOrEmpty(to_id) || StringUtil.isNullOrEmpty(poster_id)) {
                    return KWLErrorMsgs.exSuccessFail;
                }
                query = "Insert into mailmessages (post_id, to_id, poster_id, post_subject, post_text, post_time, flag, folder, reply_to, last_folder_id, readflag) values ( ?, ?, ?, ?, ?,?,false, ?, ?, ?, ?)";
                post_id = UUID.randomUUID().toString();
                numRows = DbUtil.executeUpdate(conn, query, new Object[] { post_id, to_id, poster_id,
                        post_subject, post_text, sqlPostDate, folder, reply_to, last_folder_id, readflag });

            } else {
                if (StringUtil.isNullOrEmpty(post_id1)) {
                    return KWLErrorMsgs.exSuccessFail;
                }
                query = "Update mailmessages set post_subject=?, post_text=? where post_id=?";

                numRows = DbUtil.executeUpdate(conn, query, new Object[] { post_subject, post_text, post_id1 });
            }
        } else if (draft == 2) {
            if (StringUtil.isNullOrEmpty(post_id1)
                    || /*StringUtil.isNullOrEmpty(subdomain) || StringUtil.isNullOrEmpty(post_id) ||*/ StringUtil
                            .isNullOrEmpty(to_id)
                    || StringUtil.isNullOrEmpty(poster_id) /*|| StringUtil.isNullOrEmpty(reply_to)*/) {
                return KWLErrorMsgs.exSuccessFail;
            }

            //                query = "SELECT users.userid FROM users inner join userlogin on users.userid=userlogin.userid where username=? and users.companyid = ?;";
            //                rs2 = DbUtil.executeQuery(conn, query, new Object[]{post_id1, companyid});
            //
            //                if (rs2.next()) {
            to_id = msgFor;
            //                }
            query = "Insert into mailmessages (post_id, to_id, poster_id, post_subject, post_text, post_time, flag, folder, reply_to, last_folder_id, readflag) values ( ?, ?, ?, ?, ?, ?,false, ?, ?, ?, ?)";
            post_id = UUID.randomUUID().toString();
            numRows = DbUtil.executeUpdate(conn, query, new Object[] { post_id, to_id, poster_id, post_subject,
                    post_text, sqlPostDate, folder, reply_to, last_folder_id, readflag });

            if (fileupload) {
                forummsgcomm.doPost(conn, fileItems, post_id, sqlPostDate, poster_id, post_id);
                uploaded = true;
            }
            post_id = UUID.randomUUID().toString();
            folder = "0";
            last_folder_id = "0";
            readflag = false;
            reply_to = "";
            query = "Insert into mailmessages (post_id, to_id, poster_id, post_subject, post_text, post_time, flag, folder, reply_to, last_folder_id, readflag) values ( ?, ?, ?, ?, ?, ?,false, ?, ?, ?, ?)";

            numRows = DbUtil.executeUpdate(conn, query, new Object[] { post_id, to_id, poster_id, post_subject,
                    post_text, sqlPostDate, folder, reply_to, last_folder_id, readflag });
            if (fileupload) {
                forummsgcomm.doPost(conn, fileItems, post_id, sqlPostDate, poster_id, post_id);
            }

        } else {
            query = "SELECT poster_id FROM mailmessages where post_id=?";
            DbResults rs = DbUtil.executeQuery(conn, query, post_id1);
            while (rs.next()) {
                to_id = rs.getString(1);
            }
        }
    } else {
        if (draft != 1) {
            if (draft == 3) {
                for (int t = 0; t < tos.length; t++) {
                    to_id = StringUtil.serverHTMLStripper(tos[t]);
                    if (to_id.contains("@")) {
                        query = "SELECT userid FROM users where emailid=?;";
                        rs2 = DbUtil.executeQuery(conn, query, to_id);

                        if (rs2.next()) {
                            to_id = (rs2.getString(1));
                        } else {
                            usr = to_id;
                            to_id = "-1"; //for invalid username
                        }
                    } else {
                        query = "SELECT users.userid FROM users inner join userlogin on users.userid = userlogin.userid where userlogin.username=? and users.companyid = ?;";
                        rs2 = DbUtil.executeQuery(conn, query, new Object[] { to_id, companyid });

                        if (rs2.next()) {
                            to_id = (rs2.getString(1));
                        } else {
                            usr = AuthHandler.getUserName(conn, to_id);
                            if (StringUtil.isNullOrEmpty(usr)) {
                                usr = to_id;
                                to_id = "-1"; //for invalid username
                            }
                        }
                    }
                    if (to_id.compareTo("-1") != 0) {
                        if (StringUtil.isNullOrEmpty(to_id) || StringUtil.isNullOrEmpty(poster_id)) {
                            return KWLErrorMsgs.exSuccessFail;
                        }
                        if (fid.compareTo("3") != 0 && t == tos.length - 1) {
                            folder = "1";
                            query = "Insert into mailmessages (post_id, to_id, poster_id, post_subject, post_text, post_time, flag, folder, reply_to, last_folder_id, readflag) values ( ?, ?, ?, ?, ?, ?,false, ?, ?, ?, ?)";
                            post_id = UUID.randomUUID().toString();
                            numRows = DbUtil.executeUpdate(conn, query,
                                    new Object[] { post_id, to_id, poster_id, post_subject, post_text,
                                            sqlPostDate, folder, reply_to, last_folder_id, readflag });
                        }
                        folder = "0";
                        query = "Insert into mailmessages (post_id, to_id, poster_id, post_subject, post_text, post_time, flag, folder, reply_to, last_folder_id, readflag) values ( ?, ?, ?, ?, ?, ?,false, ?, ?, ?, ?)";
                        post_id = UUID.randomUUID().toString();
                        sendefolderpostid = post_id;
                        numRows = DbUtil.executeUpdate(conn, query,
                                new Object[] { post_id, to_id, poster_id, post_subject, post_text, sqlPostDate,
                                        folder, reply_to, last_folder_id, readflag });

                        //post_id = UUID.randomUUID().toString();
                        if (fileupload) {
                            forummsgcomm.doPost(conn, fileItems, post_id, sqlPostDate, poster_id, post_id);
                            uploaded = true;
                        }
                        last_folder_id = "0";
                        readflag = false;
                        reply_to = "";
                        done = true;
                    }
                    if (fid.compareTo("3") == 0 && done == true) {//move to this users sent mails
                        post_id = request.getParameter("postid");
                        String tempfolder = "1";
                        DbResults rstemp = null;
                        query = "select poster_id from mailmessages where post_id=?";
                        rstemp = DbUtil.executeQuery(conn, query, new Object[] { post_id });
                        if (rstemp.next()) {

                            query = "update mailmessages set to_id=?, poster_id=?, post_subject=?, post_text=?, post_time=?, flag=false, folder=?, reply_to=?, last_folder_id=?, readflag=? where post_id=?";

                            int tempnumrows = DbUtil.executeUpdate(conn, query,
                                    new Object[] { to_id, poster_id, post_subject, post_text, sqlPostDate,
                                            tempfolder, reply_to, last_folder_id, readflag, post_id });
                            if (tempnumrows == 0) {
                                if (to_id.compareTo("-1") == 0) {
                                    com.krawler.utils.json.base.JSONObject jtemp = new com.krawler.utils.json.base.JSONObject();
                                    jtemp.put("Success", "userfail");
                                    jtemp.put("Subject", usr);
                                    jobj.append("data", jtemp);
                                    return jobj.toString();
                                } else {
                                    return KWLErrorMsgs.exSuccessFail;
                                }
                            }
                        }
                    }
                }
            }
        } else {
            for (int t = 0; t < tos.length; t++) {
                to_id = StringUtil.serverHTMLStripper(tos[t]);
                post_id = request.getParameter("postid");
                folder = getDraftId(poster_id);//"3";
                last_folder_id = getDraftId(poster_id);

                readflag = false;
                reply_to = "";
                query = "SELECT users.userid FROM users inner join userlogin on users.userid = userlogin.userid where userlogin.username=? and users.companyid = ?;";
                rs2 = DbUtil.executeQuery(conn, query, new Object[] { to_id, companyid });

                if (rs2.next()) {
                    to_id = (rs2.getString(1));
                } else {
                    to_id = poster_id;
                }
                if (done == false) {
                    if (to_id.compareTo("-1") != 0) {
                        if (StringUtil.isNullOrEmpty(to_id) || StringUtil.isNullOrEmpty(poster_id)) {
                            return KWLErrorMsgs.exSuccessFail;
                        }
                        DbResults rstemp = null;
                        query = "select poster_id from mailmessages where post_id=?";
                        rstemp = DbUtil.executeQuery(conn, query, new Object[] { post_id });
                        if (rstemp.next()) {

                            query = "update mailmessages set to_id=?, poster_id=?, post_subject=?, post_text=?, post_time=?, flag=false, folder=?, reply_to=?, last_folder_id=?, readflag=? where post_id=?";

                            numRows = DbUtil.executeUpdate(conn, query,
                                    new Object[] { to_id, poster_id, post_subject, post_text, sqlPostDate,
                                            folder, reply_to, last_folder_id, readflag, post_id });

                        } else {

                            String tpost_id = UUID.randomUUID().toString();
                            folder = getDraftId(poster_id);//"3";
                            last_folder_id = "0";
                            readflag = false;
                            reply_to = "";
                            if (fid.compareTo("3") != 0) {
                                if (StringUtil.isNullOrEmpty(to_id) || StringUtil.isNullOrEmpty(poster_id)) {
                                    return KWLErrorMsgs.exSuccessFail;
                                }
                                query = "Insert into mailmessages (post_id, to_id, poster_id, post_subject, post_text, post_time, flag, folder, reply_to, last_folder_id, readflag) values ( ?, ?, ?, ?, ?,?,false, ?, ?, ?, ?)";
                                numRows = DbUtil.executeUpdate(conn, query,
                                        new Object[] { tpost_id, to_id, poster_id, post_subject, post_text,
                                                sqlPostDate, folder, reply_to, last_folder_id, readflag });
                            }
                        }
                    }
                }
            }
        }
    }
    if (fileupload && !uploaded) {
        forummsgcomm.doPost(conn, fileItems, post_id, sqlPostDate, poster_id, sendefolderpostid);
    }
    if (numRows == 0) {
        if (to_id.compareTo("-1") == 0) {
            com.krawler.utils.json.base.JSONObject jtemp = new com.krawler.utils.json.base.JSONObject();
            jtemp.put("Success", "userfail");
            jtemp.put("Subject", usr);
            jobj.append("data", jtemp);
            return jobj.toString();
        } else {
            return KWLErrorMsgs.exSuccessFail;
        }
    } else {
        String dateTime = "";
        String UserName = "";
        String Image = "";
        query = "SELECT userlogin.username,image FROM users inner join userlogin on users.userid=userlogin.userid where users.userid=?;";
        rs2 = DbUtil.executeQuery(conn, query, poster_id);

        if (rs2.next()) {
            UserName = (rs2.getString(1));
            Image = (rs2.getString(2));
        }
        if (draft == 1 && sendflag.compareTo("reply") == 0) {
            query = "SELECT post_time FROM mailmessages where post_id=?;";
            rs1 = DbUtil.executeQuery(conn, query, post_id1);

            if (rs1.next()) {
                dateTime = (rs1.getObject(1).toString());
            }
        } else {
            query = "SELECT post_time FROM mailmessages where post_id=?;";
            rs1 = DbUtil.executeQuery(conn, query, post_id);

            if (rs1.next()) {
                dateTime = (rs1.getObject(1).toString());
            }
        }
        String userTime = Timezone.toCompanyTimezone(conn, sqlPostDate.toString(), companyid);
        java.util.Date tempdate = sdf.parse(userTime);
        java.text.SimpleDateFormat sdf1 = new java.text.SimpleDateFormat("yyyy-MM-dd h:mm a");
        JSONStringer j = new JSONStringer();
        com.krawler.utils.json.base.JSONObject jtemp = new com.krawler.utils.json.base.JSONObject();
        String success = "Success";
        if (folder.compareTo("3") == 0) {
            success = "Draft";
        }
        jtemp.put("Success", success);
        jtemp.put("post_time", sdf1.format(tempdate).toString());
        jtemp.put("flag", "false");
        jtemp.put("post_id", post_id);
        jtemp.put("post_subject", post_subject);
        jtemp.put("post_text", "");
        jtemp.put("poster_id", UserName);
        jtemp.put("readflag", "0");
        jtemp.put("imgsrc", Image);
        jtemp.put("senderid", poster_id);
        jobj.append("data", jtemp);
        /*temp = j.object().key("Success").value("Success").key("post_time")
        .value(sdf1.format(tempdate).toString()).key("flag").value(
        "false").key("post_id").value(post_id).key(
        "post_subject").value(post_subject)
        .key("post_text").value("").key("poster_id")
        .value(UserName).key("readflag").value("0").key("imgsrc")
        .value(Image).key("senderid").value(poster_id).endObject()
        .toString();*/

    }
    return jobj.toString();
}

From source file:com.krawler.spring.importFunctionality.ImportUtil.java

/**
 * @param request//from  w  w w .j  av  a2 s  .c o  m
 * @param fileid
 * @return
 * @throws ServiceException
 */
private static String uploadDocument(HttpServletRequest request, String fileid) throws ServiceException {
    String result = "";
    try {
        String destinationDirectory = storageHandlerImpl.GetDocStorePath() + "importplans";
        org.apache.commons.fileupload.DiskFileUpload fu = new org.apache.commons.fileupload.DiskFileUpload();
        org.apache.commons.fileupload.FileItem fi = null;
        org.apache.commons.fileupload.FileItem docTmpFI = null;

        List fileItems = null;
        try {
            fileItems = fu.parseRequest(request);
        } catch (FileUploadException e) {
            KrawlerLog.op.warn("Problem While Uploading file :" + e.toString());
        }

        long size = 0;
        String Ext = "";
        String fileName = null;
        boolean fileupload = false;
        java.io.File destDir = new java.io.File(destinationDirectory);
        fu.setSizeMax(-1);
        fu.setSizeThreshold(4096);
        fu.setRepositoryPath(destinationDirectory);
        java.util.HashMap arrParam = new java.util.HashMap();
        for (java.util.Iterator k = fileItems.iterator(); k.hasNext();) {
            fi = (org.apache.commons.fileupload.FileItem) k.next();
            arrParam.put(fi.getFieldName(), fi.getString("UTF-8"));
            if (!fi.isFormField()) {
                size = fi.getSize();
                fileName = new String(fi.getName().getBytes(), "UTF8");

                docTmpFI = fi;
                fileupload = true;
            }
        }

        if (fileupload) {

            if (!destDir.exists()) {
                destDir.mkdirs();
            }
            if (fileName.contains(".")) {
                Ext = fileName.substring(fileName.lastIndexOf("."));
            }
            if (size != 0) {
                int startIndex = fileName.contains("\\") ? (fileName.lastIndexOf("\\") + 1) : 0;
                fileName = fileName.substring(startIndex, fileName.lastIndexOf("."));
                fileName = fileName.replaceAll(" ", "");
                fileName = fileName.replaceAll("/", "");
                result = fileName + "_" + fileid + Ext;

                File uploadFile = new File(destinationDirectory + "/" + result);
                docTmpFI.write(uploadFile);
                //                    fildoc(fileid, fileName, fileid + Ext, AuthHandler.getUserid(request), size);

            }
        }

    }
    //        catch (ConfigurationException ex) {
    //            Logger.getLogger(ExportImportContacts.class.getName()).log(Level.SEVERE, null, ex);
    //            throw ServiceException.FAILURE("ExportImportContacts.uploadDocument", ex);
    //        }
    catch (Exception ex) {
        Logger.getLogger(ImportHandler.class.getName()).log(Level.SEVERE, null, ex);
        throw ServiceException.FAILURE("ExportImportContacts.uploadDocument", ex);
    }
    return result;
}

From source file:forseti.JUtil.java

@SuppressWarnings("rawtypes")
public static synchronized boolean procesaFicheros(HttpServletRequest req, String dir) {
    boolean res = true;

    try {/*from   w  ww  . jav  a2s  .  c o m*/
        // construimos el objeto que es capaz de parsear la pericin
        DiskFileUpload fu = new DiskFileUpload();

        // maximo numero de bytes
        fu.setSizeMax(1024 * 512); // 512 K

        //System.out.println("Ponemos el tamao mximo");
        // tamao por encima del cual los ficheros son escritos directamente en disco
        fu.setSizeThreshold(4096);

        // directorio en el que se escribirn los ficheros con tamao superior al soportado en memoria
        fu.setRepositoryPath("/tmp");

        // ordenamos procesar los ficheros
        List fileItems = fu.parseRequest(req);

        if (fileItems == null) {
            //System.out.println("La lista es nula");
            return false;
        }

        //System.out.println("El nmero de ficheros subidos es: " +  fileItems.size());

        // Iteramos por cada fichero

        Iterator i = fileItems.iterator();
        FileItem actual = null;
        //System.out.println("estamos en la iteracin");

        while (i.hasNext()) {
            actual = (FileItem) i.next();
            String fileName = actual.getName();
            //System.out.println("Nos han subido el fichero" + fileName);

            // construimos un objeto file para recuperar el trayecto completo
            File fichero = new File(fileName);
            //System.out.println("El nombre del fichero es " + fichero.getName());

            // nos quedamos solo con el nombre y descartamos el path
            fichero = new File(dir + fichero.getName());

            // escribimos el fichero colgando del nuevo path
            actual.write(fichero);
        }

    } catch (Exception e) {
        System.out.println("Error de Fichero: " + e.getMessage());
        res = false;
    }

    return res;
}

From source file:nextapp.echo2.webcontainer.filetransfer.JakartaCommonsFileUploadProvider.java

/**
 * @see nextapp.echo2.webcontainer.filetransfer.MultipartUploadSPI#updateComponent(nextapp.echo2.webrender.Connection,
 *      nextapp.echo2.app.filetransfer.UploadSelect)
 *//*from  ww w.ja v a2 s .co m*/
public void updateComponent(Connection conn, UploadSelect uploadSelect) throws IOException, ServletException {

    DiskFileUpload handler = null;
    HttpServletRequest request = null;
    List items = null;
    Iterator it = null;
    FileItem item = null;
    boolean searching = true;
    InputStream in = null;
    int size = 0;
    String contentType = null;
    String name = null;

    try {
        handler = new DiskFileUpload();
        handler.setSizeMax(getFileUploadSizeLimit());
        handler.setSizeThreshold(getMemoryCacheThreshold());
        handler.setRepositoryPath(getDiskCacheLocation().getCanonicalPath());

        request = conn.getRequest();
        items = handler.parseRequest(request);

        searching = true;
        it = items.iterator();
        while (it.hasNext() && searching) {
            item = (FileItem) it.next();
            if (UploadFormService.FILE_PARAMETER_NAME.equals(item.getFieldName())) {
                in = item.getInputStream();
                size = (int) item.getSize();
                contentType = item.getContentType();
                name = item.getName();

                File tempFile = writeTempFile(in, uploadSelect);
                UploadEvent uploadEvent = new UploadEvent(tempFile, size, contentType, name);
                UploadSelectPeer.activateUploadSelect(uploadSelect, uploadEvent);

                searching = false;
            }
        }
    } catch (FileUploadException e) {
        throw new IOException(e.getMessage());
    }
}

From source file:org.apache.catalina.manager.HTMLManagerServlet.java

/**
 * Process a POST request for the specified resource.
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are creating
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet-specified error occurs
 *///from  w w  w.j av a2  s . c  o m
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    // Identify the request parameters that we need
    String command = request.getPathInfo();

    if (command == null || !command.equals("/upload")) {
        doGet(request, response);
        return;
    }

    // Prepare our output writer to generate the response message
    response.setContentType("text/html; charset=" + Constants.CHARSET);

    String message = "";

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

    // Get the tempdir
    File tempdir = (File) getServletContext().getAttribute("javax.servlet.context.tempdir");
    // Set upload parameters
    upload.setSizeMax(-1);
    upload.setRepositoryPath(tempdir.getCanonicalPath());

    // Parse the request
    String basename = null;
    File appBaseDir = null;
    String war = null;
    FileItem warUpload = null;
    try {
        List items = upload.parseRequest(request);

        // Process the uploaded fields
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (!item.isFormField()) {
                if (item.getFieldName().equals("deployWar") && warUpload == null) {
                    warUpload = item;
                } else {
                    item.delete();
                }
            }
        }
        while (true) {
            if (warUpload == null) {
                message = sm.getString("htmlManagerServlet.deployUploadNoFile");
                break;
            }
            war = warUpload.getName();
            if (!war.toLowerCase().endsWith(".war")) {
                message = sm.getString("htmlManagerServlet.deployUploadNotWar", war);
                break;
            }
            // Get the filename if uploaded name includes a path
            if (war.lastIndexOf('\\') >= 0) {
                war = war.substring(war.lastIndexOf('\\') + 1);
            }
            if (war.lastIndexOf('/') >= 0) {
                war = war.substring(war.lastIndexOf('/') + 1);
            }
            // Identify the appBase of the owning Host of this Context
            // (if any)
            String appBase = null;
            appBase = ((Host) context.getParent()).getAppBase();
            appBaseDir = new File(appBase);
            if (!appBaseDir.isAbsolute()) {
                appBaseDir = new File(System.getProperty("catalina.base"), appBase);
            }
            basename = war.substring(0, war.indexOf(".war"));
            File file = new File(appBaseDir, war);
            if (file.exists()) {
                message = sm.getString("htmlManagerServlet.deployUploadWarExists", war);
                break;
            }
            warUpload.write(file);
            try {
                URL url = file.toURL();
                war = url.toString();
                war = "jar:" + war + "!/";
            } catch (MalformedURLException e) {
                file.delete();
                throw e;
            }
            break;
        }
    } catch (Exception e) {
        message = sm.getString("htmlManagerServlet.deployUploadFail", e.getMessage());
        log(message, e);
    } finally {
        if (warUpload != null) {
            warUpload.delete();
        }
        warUpload = null;
    }

    // Extract the nested context deployment file (if any)
    File localWar = new File(appBaseDir, basename + ".war");
    File localXml = new File(configBase, basename + ".xml");
    try {
        extractXml(localWar, localXml);
    } catch (IOException e) {
        log("managerServlet.extract[" + localWar + "]", e);
        return;
    }
    String config = null;
    try {
        if (localXml.exists()) {
            URL url = localXml.toURL();
            config = url.toString();
        }
    } catch (MalformedURLException e) {
        throw e;
    }

    // If there were no errors, deploy the WAR
    if (message.length() == 0) {
        message = deployInternal(config, null, war);
    }

    list(request, response, message);
}

From source file:org.apache.catalina.servlets.HTMLManagerServlet.java

/**
 * Process a POST request for the specified resource.
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are creating
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet-specified error occurs
 *//*from w  w w . j av  a 2s .c o  m*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    // Identify the request parameters that we need
    String command = request.getPathInfo();

    if (command == null || !command.equals("/upload")) {
        doGet(request, response);
        return;
    }

    // Prepare our output writer to generate the response message
    Locale locale = Locale.getDefault();
    String charset = context.getCharsetMapper().getCharset(locale);
    response.setLocale(locale);
    response.setContentType("text/html; charset=" + charset);

    String message = "";

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

    // Get the tempdir
    File tempdir = (File) getServletContext().getAttribute("javax.servlet.context.tempdir");
    // Set upload parameters
    upload.setSizeMax(-1);
    upload.setRepositoryPath(tempdir.getCanonicalPath());

    // Parse the request
    String war = null;
    FileItem warUpload = null;
    try {
        List items = upload.parseRequest(request);

        // Process the uploaded fields
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (!item.isFormField()) {
                if (item.getFieldName().equals("installWar") && warUpload == null) {
                    warUpload = item;
                } else {
                    item.delete();
                }
            }
        }
        while (true) {
            if (warUpload == null) {
                message = sm.getString("htmlManagerServlet.installUploadNoFile");
                break;
            }
            war = warUpload.getName();
            if (!war.toLowerCase().endsWith(".war")) {
                message = sm.getString("htmlManagerServlet.installUploadNotWar", war);
                break;
            }
            // Get the filename if uploaded name includes a path
            if (war.lastIndexOf('\\') >= 0) {
                war = war.substring(war.lastIndexOf('\\') + 1);
            }
            if (war.lastIndexOf('/') >= 0) {
                war = war.substring(war.lastIndexOf('/') + 1);
            }
            // Identify the appBase of the owning Host of this Context
            // (if any)
            String appBase = null;
            File appBaseDir = null;
            appBase = ((Host) context.getParent()).getAppBase();
            appBaseDir = new File(appBase);
            if (!appBaseDir.isAbsolute()) {
                appBaseDir = new File(System.getProperty("catalina.base"), appBase);
            }
            File file = new File(appBaseDir, war);
            if (file.exists()) {
                message = sm.getString("htmlManagerServlet.installUploadWarExists", war);
                break;
            }
            warUpload.write(file);
            try {
                URL url = file.toURL();
                war = url.toString();
                war = "jar:" + war + "!/";
            } catch (MalformedURLException e) {
                file.delete();
                throw e;
            }
            break;
        }
    } catch (Exception e) {
        message = sm.getString("htmlManagerServlet.installUploadFail", e.getMessage());
        log(message, e);
    } finally {
        if (warUpload != null) {
            warUpload.delete();
        }
        warUpload = null;
    }

    // If there were no errors, install the WAR
    if (message.length() == 0) {
        message = install(null, null, war);
    }

    list(request, response, message);
}

From source file:org.apache.struts.upload.CommonsMultipartRequestHandler.java

/**
 * <p> Parses the input stream and partitions the parsed items into a set
 * of form fields and a set of file items. In the process, the parsed
 * items are translated from Commons FileUpload <code>FileItem</code>
 * instances to Struts <code>FormFile</code> instances. </p>
 *
 * @param request The multipart request to be processed.
 * @throws ServletException if an unrecoverable error occurs.
 *///  ww  w .  j  av a  2  s.c  om
public void handleRequest(HttpServletRequest request) throws ServletException {
    // Get the app config for the current request.
    ModuleConfig ac = (ModuleConfig) request.getAttribute(Globals.MODULE_KEY);

    // Create and configure a DIskFileUpload instance.
    DiskFileUpload upload = new DiskFileUpload();

    // The following line is to support an "EncodingFilter"
    // see http://issues.apache.org/bugzilla/show_bug.cgi?id=23255
    upload.setHeaderEncoding(request.getCharacterEncoding());

    // Set the maximum size before a FileUploadException will be thrown.
    upload.setSizeMax(getSizeMax(ac));

    // Set the maximum size that will be stored in memory.
    upload.setSizeThreshold((int) getSizeThreshold(ac));

    // Set the the location for saving data on disk.
    upload.setRepositoryPath(getRepositoryPath(ac));

    // Create the hash tables to be populated.
    elementsText = new Hashtable();
    elementsFile = new Hashtable();
    elementsAll = new Hashtable();

    // Parse the request into file items.
    List items = null;

    try {
        items = upload.parseRequest(request);
    } catch (DiskFileUpload.SizeLimitExceededException e) {
        // Special handling for uploads that are too big.
        request.setAttribute(MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED, Boolean.TRUE);

        return;
    } catch (FileUploadException e) {
        log.error("Failed to parse multipart request", e);
        throw new ServletException(e);
    }

    // Partition the items into form fields and files.
    Iterator iter = items.iterator();

    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();

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

From source file:org.araneaframework.servlet.filter.StandardServletFileUploadFilterService.java

protected void action(Path path, InputData input, OutputData output) throws Exception {
    HttpServletRequest request = ((ServletInputData) input).getRequest();

    if (FileUpload.isMultipartContent(request)) {
        Map fileItems = new HashMap();
        Map parameterLists = new HashMap();

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

        if (useRequestEncoding)
            upload.setHeaderEncoding(request.getCharacterEncoding());
        else if (multipartEncoding != null)
            upload.setHeaderEncoding(multipartEncoding);

        // Set upload parameters
        if (maximumCachedSize != null)
            upload.setSizeThreshold(maximumCachedSize.intValue());
        if (maximumSize != null)
            upload.setSizeMax(maximumSize.longValue());
        if (tempDirectory != null)
            upload.setRepositoryPath(tempDirectory);

        // Parse the request
        List items = upload.parseRequest(request);

        // Process the uploaded items
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (!item.isFormField()) {
                fileItems.put(item.getFieldName(), item);
            } else {
                List parameterValues = (List) parameterLists.get(item.getFieldName());

                if (parameterValues == null) {
                    parameterValues = new ArrayList();
                    parameterLists.put(item.getFieldName(), parameterValues);
                }//w ww  .ja  va  2s  . com

                parameterValues.add(item.getString());
            }
        }

        log.debug("Parsed multipart request, found '" + fileItems.size() + "' file items and '"
                + parameterLists.size() + "' request parameters");

        output.extend(ServletFileUploadInputExtension.class,
                new StandardServletFileUploadInputExtension(fileItems));

        request = new MultipartWrapper(request, parameterLists);
        ((ServletOverridableInputData) input).setRequest(request);
    }

    super.action(path, input, output);
}