Example usage for org.apache.commons.fileupload FileItem getSize

List of usage examples for org.apache.commons.fileupload FileItem getSize

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItem getSize.

Prototype

long getSize();

Source Link

Document

Returns the size of the file item.

Usage

From source file:com.stratelia.silverpeas.versioningPeas.servlets.VersioningRequestRouter.java

/**
 * Process request form/*ww  w.j  a  va  2 s .  c o  m*/
 * @param request
 * @param versioningSC
 * @return
 * @throws Exception
 * @throws IOException
 */
private void saveNewDocument(HttpServletRequest request, VersioningSessionController versioningSC)
        throws Exception {
    SilverTrace.debug("versioningPeas", "VersioningRequestRooter.saveNewDocument()",
            "root.MSG_GEN_ENTER_METHOD");
    int majorNumber = 0;
    int minorNumber = 1;
    String type = "dummy";
    String physicalName = "dummy";
    String logicalName = "dummy";
    String mimeType = "dummy";
    File dir = null;
    int size = 0;
    DocumentPK docPK = new DocumentPK(-1, versioningSC.getComponentId());
    if (!StringUtil.isDefined(request.getCharacterEncoding())) {
        request.setCharacterEncoding("UTF-8");
    }
    String encoding = request.getCharacterEncoding();

    List<FileItem> items = FileUploadUtil.parseRequest(request);
    String comments = FileUploadUtil.getParameter(items, "comments", "", encoding);
    int versionType = Integer.parseInt(FileUploadUtil.getParameter(items, "versionType", "0", encoding));

    FileItem fileItem = FileUploadUtil.getFile(items, "file_upload");
    boolean runOnUnix = !FileUtil.isWindows();
    logicalName = fileItem.getName();
    if (logicalName != null) {

        if (runOnUnix) {
            logicalName = logicalName.replace('\\', File.separatorChar);
        }

        logicalName = logicalName.substring(logicalName.lastIndexOf(File.separator) + 1, logicalName.length());
        type = logicalName.substring(logicalName.lastIndexOf(".") + 1, logicalName.length());
        physicalName = new Long(new Date().getTime()).toString() + "." + type;
        mimeType = FileUtil.getMimeType(logicalName);
        if (!StringUtil.isDefined(mimeType)) {
            mimeType = "unknown";
        }
        dir = new File(versioningSC.createPath(versioningSC.getComponentId(), null) + physicalName);
        size = new Long(fileItem.getSize()).intValue();
        fileItem.write(dir);
    }

    if (versionType == VersioningSessionController.PUBLIC_VERSION) {
        majorNumber = 1;
        minorNumber = 0;
    }
    if (size == 0) {
        majorNumber = 0;
        minorNumber = 0;
    }
    DocumentVersion documentVersion = new DocumentVersion(null, docPK, majorNumber, minorNumber,
            Integer.parseInt(versioningSC.getUserId()), new Date(), comments, versionType,
            DocumentVersion.STATUS_VALIDATION_NOT_REQ, physicalName, logicalName, mimeType, size,
            versioningSC.getComponentId());

    boolean addXmlForm = !isXMLFormEmpty(versioningSC, items);
    if (addXmlForm) {
        documentVersion.setXmlForm(versioningSC.getXmlForm());
    }

    // Document
    docPK = new DocumentPK(-1, versioningSC.getComponentId());

    String name = FileUploadUtil.getParameter(items, "name", "", encoding);
    String publicationId = FileUploadUtil.getParameter(items, "publicationId", "-1", encoding);
    String description = FileUploadUtil.getParameter(items, "description", "", encoding);

    PublicationPK pubPK = new PublicationPK(publicationId, versioningSC.getComponentId());
    Document document = new Document(docPK, pubPK, name, description, Document.STATUS_CHECKINED, -1, new Date(),
            null, versioningSC.getComponentId(), null, null, 0,
            Integer.parseInt(VersioningSessionController.WRITERS_LIST_SIMPLE));

    String docId = versioningSC.createDocument(document, documentVersion).getId();

    if (addXmlForm) {
        // Save additional informations
        saveXMLData(versioningSC, documentVersion.getPk(), items);
    }

    versioningSC.setEditingDocument(document);
    versioningSC.setFileRights();
    versioningSC.updateWorkList(document);
    versioningSC.updateDocument(document);

    // Specific case: 3d file to convert by Actify Publisher
    ResourceLocator attachmentSettings = new ResourceLocator(
            "com.stratelia.webactiv.util.attachment.Attachment", "");
    boolean actifyPublisherEnable = attachmentSettings.getBoolean("ActifyPublisherEnable", false);
    if (actifyPublisherEnable) {
        versioningSC.saveFileForActify(docId, documentVersion, attachmentSettings);
    }

    SilverTrace.debug("versioningPeas", "VersioningRequestRooter.saveNewDocument()",
            "root.MSG_GEN_EXIT_METHOD");
}

From source file:com.stratelia.webactiv.survey.control.SurveySessionController.java

public void saveSynthesisFile(FileItem fileSynthesis) throws SurveyException {
    SilverTrace.info("Survey", "SurveySessionController.saveSynthesisFile", "Survey.MSG_ENTRY_METHOD");
    QuestionContainerDetail survey = this.getSessionSurvey();
    try {/*from   w ww.j a  v a 2 s.  c om*/
        Date creationDate = new Date();
        String filename = fileSynthesis.getName();
        SimpleAttachment file = new SimpleAttachment(FileUtil.getFilename(filename), I18NHelper.defaultLanguage,
                filename, "", fileSynthesis.getSize(), FileUtil.getMimeType(filename), this.getUserId(),
                creationDate, null);
        SimpleDocument document = new SimpleDocument(
                new SimpleDocumentPK(null, survey.getComponentInstanceId()), survey.getId(), 0, false, file);
        AttachmentServiceFactory.getAttachmentService().createAttachment(document,
                fileSynthesis.getInputStream(), true);
    } catch (IOException e) {
        throw new SurveyException("SurveySessionController.saveSynthesisFile", SurveyException.WARNING,
                "Survey.EX_PROBLEM_TO_UPDATE_SURVEY", "id = " + survey.getId(), e);
    }
}

From source file:it.infn.ct.code_rade_portlet.java

/**
 * This method manages the user input fields managing two cases
 * distinguished by the type of the input <form ... statement
 * The use of upload file controls needs the use of "multipart/form-data"
 * while the else condition of the isMultipartContent check manages the
 * standard input case. The multipart content needs a manual processing of
 * all <form items//from w w w.j  av  a2 s . com
 * All form' input items are identified by the 'name' input property
 * inside the jsp file
 *
 * @param request   ActionRequest instance (processAction)
 * @param appInput  AppInput instance storing the jobSubmission data
 */
void getInputForm(ActionRequest request, AppInput appInput) {
    if (PortletFileUpload.isMultipartContent(request))
        try {
            FileItemFactory factory = new DiskFileItemFactory();
            PortletFileUpload upload = new PortletFileUpload(factory);
            List items = upload.parseRequest(request);
            File repositoryPath = new File("/tmp");
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            diskFileItemFactory.setRepository(repositoryPath);
            Iterator iter = items.iterator();
            String logstring = "";
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                String fieldName = item.getFieldName();
                String fileName = item.getName();
                String contentType = item.getContentType();
                boolean isInMemory = item.isInMemory();
                long sizeInBytes = item.getSize();
                // Prepare a log string with field list
                logstring += LS + "field name: '" + fieldName + "' - '" + item.getString() + "'";
                switch (inputControlsIds.valueOf(fieldName)) {
                case file_inputFile:
                    appInput.inputFileName = item.getString();
                    processInputFile(item, appInput);
                    break;
                case inputFile:
                    appInput.inputFileText = item.getString();
                    break;
                case JobIdentifier:
                    appInput.jobIdentifier = item.getString();
                    break;
                default:
                    _log.warn("Unhandled input field: '" + fieldName + "' - '" + item.getString() + "'");
                } // switch fieldName
            } // while iter.hasNext()
            _log.info(LS + "Reporting" + LS + "---------" + LS + logstring + LS);
        } // try
        catch (Exception e) {
            _log.info("Caught exception while processing files to upload: '" + e.toString() + "'");
        }
    // The input form do not use the "multipart/form-data"
    else {
        // Retrieve from the input form the given application values
        appInput.inputFileName = (String) request.getParameter("file_inputFile");
        appInput.inputFileText = (String) request.getParameter("inputFile");
        appInput.jobIdentifier = (String) request.getParameter("JobIdentifier");
    } // ! isMultipartContent

    // Show into the log the taken inputs
    _log.info(LS + "Taken input parameters:" + LS + "-----------------------" + LS + "inputFileName: '"
            + appInput.inputFileName + "'" + LS + "inputFileText: '" + appInput.inputFileText + "'" + LS
            + "jobIdentifier: '" + appInput.jobIdentifier + "'" + LS);
}

From source file:com.glaf.base.utils.upload.FileUploadBackGroundServlet.java

/**
 * ?/*from   w w w.jav a2s.  co m*/
 */
private void processFileUpload(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String serviceKey = request.getParameter("serviceKey");
    if (serviceKey == null) {
        serviceKey = "global";
    }

    int maxUploadSize = conf.getInt(serviceKey + ".maxUploadSize", 0);
    if (maxUploadSize == 0) {
        maxUploadSize = conf.getInt("upload.maxUploadSize", 10);// 10MB
    }
    maxUploadSize = maxUploadSize * FileUtils.MB_SIZE;
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // ?
    factory.setSizeThreshold(204800);
    File tempDir = new File(getUploadDir() + "/temp");
    if (!tempDir.exists()) {
        tempDir.mkdir();
    }

    // ?
    factory.setRepository(tempDir);
    ServletFileUpload upload = new ServletFileUpload(factory);
    // ?
    upload.setFileSizeMax(maxUploadSize);
    // request
    upload.setSizeMax(maxUploadSize);
    upload.setProgressListener(new FileUploadListener(request));
    upload.setHeaderEncoding("UTF-8");
    // ???FileUploadStatus Bean
    FileMgmtFactory.saveStatusBean(request, initStatusBean(request));

    try {
        List<?> items = upload.parseRequest(request);
        // url
        for (int i = 0; i < items.size(); i++) {
            FileItem item = (FileItem) items.get(i);
            if (item.isFormField()) {

                break;
            }
        }
        // 
        String uploadDir = com.glaf.base.utils.StringUtil.createDir(getUploadDir());
        // ?
        for (int i = 0; i < items.size(); i++) {
            FileItem item = (FileItem) items.get(i);
            // ?
            if (FileMgmtFactory.getStatusBean(request).getCancel()) {
                deleteUploadedFile(request);
                break;
            } else if (!item.isFormField() && item.getName().length() > 0) {
                logger.debug("" + item.getName());
                // ?
                String fileId = UUID32.getUUID();
                String path = uploadDir + FileUtils.sp + fileId;
                File uploadedFile = new File(new File(getUploadDir(), uploadDir), fileId);
                item.write(uploadedFile);
                // 
                FileUploadStatus satusBean = FileMgmtFactory.getStatusBean(request);
                FileInfo fileInfo = new FileInfo();
                fileInfo.setCreateDate(new Date());
                fileInfo.setFileId(fileId);
                fileInfo.setFile(uploadedFile);
                fileInfo.setFilename(FileUtils.getFilename(item.getName()));
                fileInfo.setSize(item.getSize());
                fileInfo.setPath(path);
                satusBean.getUploadFileUrlList().add(fileInfo);
                FileMgmtFactory.saveStatusBean(request, satusBean);
                Thread.sleep(500);
            }
        }

    } catch (FileUploadException ex) {
        uploadExceptionHandle(request, "?:" + ex.getMessage());
    } catch (Exception ex) {
        uploadExceptionHandle(request, "??:" + ex.getMessage());
    }
    String forwardURL = request.getParameter("forwardURL");
    if (StringUtils.isEmpty(forwardURL)) {
        forwardURL = "/others/attachment.do?method=showResult";
    }
    request.getRequestDispatcher(forwardURL).forward(request, response);
}

From source file:it.infn.ct.R_portlet.java

void getInputForm(ActionRequest request, App_Input appInput) {
    if (PortletFileUpload.isMultipartContent(request))
        try {/*from  w  w  w. ja  v a 2  s  . co  m*/
            FileItemFactory factory = new DiskFileItemFactory();
            PortletFileUpload upload = new PortletFileUpload(factory);
            List items = upload.parseRequest(request);
            File repositoryPath = new File("/tmp");
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            diskFileItemFactory.setRepository(repositoryPath);
            Iterator iter = items.iterator();
            String logstring = "";
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                String fieldName = item.getFieldName();
                String fileName = item.getName();
                String contentType = item.getContentType();
                boolean isInMemory = item.isInMemory();
                long sizeInBytes = item.getSize();
                // Prepare a log string with field list
                logstring += LS + "field name: '" + fieldName + "' - '" + item.getString() + "'";
                switch (inputControlsIds.valueOf(fieldName)) {
                case file_inputFile:
                    appInput.inputFileName = item.getString();
                    processInputFile(item, appInput);
                    break;
                case inputFile:
                    appInput.inputFileText = item.getString();
                    break;
                case JobIdentifier:
                    appInput.jobIdentifier = item.getString();
                    break;
                default:
                    _log.warn("Unhandled input field: '" + fieldName + "' - '" + item.getString() + "'");
                } // switch fieldName                                                   
            } // while iter.hasNext()   
            _log.info(LS + "Reporting" + LS + "---------" + LS + logstring + LS);
        } // try
        catch (Exception e) {
            _log.info("Caught exception while processing files to upload: '" + e.toString() + "'");
        }
    // The input form do not use the "multipart/form-data" 
    else {
        // Retrieve from the input form the given application values
        appInput.inputFileName = (String) request.getParameter("file_inputFile");
        appInput.inputFileText = (String) request.getParameter("inputFile");
        appInput.jobIdentifier = (String) request.getParameter("JobIdentifier");
    } // ! isMultipartContent

    // Show into the log the taken inputs
    _log.info(LS + "Taken input parameters:" + LS + "-----------------------" + LS + "inputFileName: '"
            + appInput.inputFileName + "'" + LS + "inputFileText: '" + appInput.inputFileText + "'" + LS
            + "jobIdentifier: '" + appInput.jobIdentifier + "'" + LS);
}

From source file:com.trsst.ui.AppServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // FLAG: limit access only to local clients
    if (restricted && !request.getRemoteAddr().equals(request.getLocalAddr())) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, "Non-local clients are not allowed.");
        return;//from w  ww . ja v  a2  s  .  c  o  m
    }

    // in case of any posted files
    InputStream inStream = null;

    // determine if supported command: pull, push, post
    String path = request.getPathInfo();
    System.err.println(new Date().toString() + " " + path);
    if (path != null) {
        // FLAG: limit only to pull and post
        if (path.startsWith("/pull/") || path.startsWith("/post")) {
            // FLAG: we're sending the user's keystore
            // password over the wire (over SSL)
            List<String> args = new LinkedList<String>();
            if (path.startsWith("/pull/")) {
                path = path.substring("/pull/".length());
                response.setContentType("application/atom+xml; type=feed; charset=utf-8");
                // System.out.println("doPull: " +
                // request.getParameterMap());
                args.add("pull");
                if (request.getParameterMap().size() > 0) {
                    boolean first = true;
                    for (Object name : request.getParameterMap().keySet()) {
                        // FLAG: don't allow "home" (server-abuse)
                        // FLAG: don't allow "attach" (file-system access)
                        if ("decrypt".equals(name) || "pass".equals(name)) {
                            for (String value : request.getParameterValues(name.toString())) {
                                args.add("--" + name.toString());
                                args.add(value);
                            }
                        } else {
                            for (String value : request.getParameterValues(name.toString())) {
                                if (first) {
                                    path = path + '?';
                                    first = false;
                                } else {
                                    path = path + '&';
                                }
                                path = path + name + '=' + value;
                            }
                        }
                    }
                }
                args.add(path);

            } else if (path.startsWith("/post")) {
                // System.out.println("doPost: " +
                // request.getParameterMap());
                args.add("post");

                try { // h/t http://stackoverflow.com/questions/2422468
                    List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory())
                            .parseRequest(request);
                    for (FileItem item : items) {
                        if (item.isFormField()) {
                            // process regular form field
                            String name = item.getFieldName();
                            String value = item.getString("UTF-8").trim();
                            // System.out.println("AppServlet: " + name
                            // + " : " + value);
                            if (value.length() > 0) {
                                // FLAG: don't allow "home" (server-abuse)
                                // FLAG: don't allow "attach" (file-system
                                // access)
                                if ("id".equals(name)) {
                                    if (value.startsWith("urn:feed:")) {
                                        value = value.substring("urn:feed:".length());
                                    }
                                    args.add(value);
                                } else if (!"home".equals(name) && !"attach".equals(name)) {
                                    args.add("--" + name);
                                    args.add(value);
                                }
                            } else {
                                log.debug("Empty form value for name: " + name);
                            }
                        } else if (item.getSize() > 0) {
                            // process form file field (input type="file").
                            // String filename = FilenameUtils.getName(item
                            // .getName());
                            if (item.getSize() > 1024 * 1024 * 10) {
                                throw new FileUploadException("Current maximum upload size is 10MB");
                            }
                            String name = item.getFieldName();
                            if ("icon".equals(name) || "logo".equals(name)) {
                                args.add("--" + name);
                                args.add("-");
                            }
                            inStream = item.getInputStream();
                            // NOTE: only handles one file!
                        } else {
                            log.debug("Ignored form field: " + item.getFieldName());
                        }
                    }
                } catch (FileUploadException e) {
                    response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                            "Could not parse multipart request: " + e);
                    return;
                }
            }

            // send post data if any to command input stream
            if (inStream != null) {
                args.add("--attach");
            }
            //System.out.println(args);

            // make sure we don't create another local server
            args.add("--host");
            args.add(request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                    + "/feed");

            PrintStream outStream = new PrintStream(response.getOutputStream(), false, "UTF-8");
            int result = new Command().doBegin(args.toArray(new String[0]), outStream, inStream);
            if (result != 0) {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Internal error code: " + result);
            } else {
                outStream.flush();
            }
            return;
        }

        // otherwise: determine if static resource request
        if (path.startsWith("/")) {
            path = path.substring(1);
        }

        byte[] result = resources.get(path);
        String mimetype = null;
        if (result == null) {
            // if ("".equals(path) || path.endsWith(".html")) {
            // treat all html requests with index doc
            result = resources.get("index.html");
            mimetype = "text/html";
            // }
        }
        if (result != null) {
            if (mimetype == null) {
                if (path.endsWith(".html")) {
                    mimetype = "text/html";
                } else if (path.endsWith(".css")) {
                    mimetype = "text/css";
                } else if (path.endsWith(".js")) {
                    mimetype = "application/javascript";
                } else if (path.endsWith(".png")) {
                    mimetype = "image/png";
                } else if (path.endsWith(".jpg")) {
                    mimetype = "image/jpeg";
                } else if (path.endsWith(".jpeg")) {
                    mimetype = "image/jpeg";
                } else if (path.endsWith(".gif")) {
                    mimetype = "image/gif";
                } else {
                    mimetype = new Tika().detect(result);
                }
            }
            if (request.getHeader("If-None-Match:") != null) {
                // client should always use cached version
                log.info("sending 304");
                response.setStatus(304); // Not Modified
                return;
            }
            // otherwise allow ETag/If-None-Match
            response.setHeader("ETag", Long.toHexString(path.hashCode()));
            if (mimetype != null) {
                response.setContentType(mimetype);
            }
            response.setContentLength(result.length);
            response.getOutputStream().write(result);
            return;
        }

    }

    // // otherwise: 404 Not Found
    // response.sendError(HttpServletResponse.SC_NOT_FOUND);
}

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);/*from   w  w  w  . ja v  a2 s  . c om*/
    boolean fileupload = false;
    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();
        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:it.infn.ct.corsika_portlet.java

/**
 * This method manages the user input fields managing two cases
 * distinguished by the type of the input <form ... statement The use of
 * upload file controls needs the use of "multipart/form-data" while the
 * else condition of the isMultipartContent check manages the standard input
 * case. The multipart content needs a manual processing of all <form items
 * All form' input items are identified by the 'name' input property inside
 * the jsp file//from   w  w w  .  j  av a  2 s. c  o  m
 * @param request ActionRequest instance (processAction)
 * @param appInput AppInput instance storing the jobSubmission data
 */

void getInputForm(ActionRequest request, corsika_portlet.AppInput appInput) {

    if (PortletFileUpload.isMultipartContent(request)) {
        try {
            FileItemFactory factory = new DiskFileItemFactory();
            PortletFileUpload upload = new PortletFileUpload(factory);
            List items = upload.parseRequest(request);
            File repositoryPath = new File("/tmp");
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            diskFileItemFactory.setRepository(repositoryPath);
            Iterator iter = items.iterator();
            String logstring = "";
            int i = 0;
            int j = 0;
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                String fieldName = item.getFieldName();

                String fileName = item.getName();
                String contentType = item.getContentType();
                boolean isInMemory = item.isInMemory();
                long sizeInBytes = item.getSize();
                // Prepare a log string with field list
                switch (corsika_portlet.inputControlsIds.valueOf(fieldName)) {

                case jobPID:
                    logstring += LS + "FIELD IS A JOB PID  WITH NAME : '" + item.getString() + "'";
                    appInput.jobPID = item.getString();
                    break;
                case JobIdentifier:
                    logstring += LS + "FIELD IS A JOB IDENTIFIER  WITH NAME : '" + item.getString() + "'";
                    appInput.jobIdentifier = item.getString();
                    break;
                case file_inputFile:
                    if (fileName == "")
                        break;
                    logstring += LS + "FIELD IS A FILE WITH NAME : '" + fileName + "'";
                    appInput.inputFile = appInput.path + "/" + fileName;
                    logstring += LS + "COPYING IT TO PATH : '" + appInput.path + "'";
                    copyFile(item, appInput.inputFile);
                    break;
                case corsikaVersion:
                    appInput.corsikaVersion = item.getString();
                    logstring += LS + "FIELD IS A CORSIKA VERSION WITH NAME : '" + appInput.corsikaVersion
                            + "'";
                    break;
                case parametricJob:
                    if (item.getString().trim().equals("yes"))
                        appInput.parametricJob = true;
                    else
                        appInput.parametricJob = false;
                    logstring += LS + "FIELD IS A PARAMETRIC JOB SPECIFICATION : '"
                            + appInput.parametricJob.toString() + "'";
                    break;
                case emailWhenFinished:
                    if (item.getString().trim().equals("yes"))
                        appInput.emailWhenFinished = true;
                    else
                        appInput.emailWhenFinished = false;
                    logstring += LS + "FIELD IS A EMAIL WHEN FINISHED SPECIFICATION : '"
                            + appInput.emailWhenFinished.toString() + "'";
                    break;
                case useStorageElement:
                    if (item.getString().trim().equals("yes"))
                        appInput.useStorageElement = true;
                    else
                        appInput.useStorageElement = false;
                    logstring += LS + "FIELD IS A STORAGE ELEMENT SPECIFICATION : '"
                            + appInput.useStorageElement.toString() + "'";
                    break;
                default:
                    _log.warn("Unhandled input field: '" + fieldName + "' - '" + item.getString() + "'");
                } // switch fieldName
            } // while iter.hasNext()   
            _log.info(LS + "Reporting" + LS + "---------" + LS + logstring + LS);
        } // try
        catch (Exception e) {
            _log.info("Caught exception while processing files to upload: '" + e.toString() + "'");
        }
    } // The input form do not use the "multipart/form-data" 
    else {
        // Retrieve from the input form the given application values
        //            appInput.inputFileName = (String) request.getParameter("file_inputFile");
        //            appInput.inputFileText = (String) request.getParameter("inputFile");
        appInput.jobIdentifier = (String) request.getParameter("JobIdentifier");

    } // ! isMultipartContent

    // Show into the log the taken inputs
    _log.info(LS + "Taken input parameters:" + LS + "-----------------------"
    //                + LS + "inputFileName: '" + appInput.inputFileName + "'"
    //                + LS + "inputFileText: '" + appInput.inputFileText + "'"
            + LS + "jobIdentifier: '" + appInput.jobIdentifier + "'" + LS + "jobPID: '" + appInput.jobPID + "'"
            + LS + "inputFile: '" + appInput.inputFile + "'" + LS);

}

From source file:admin.controller.ServletEditCategories.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  w  w w .  java  2 s .co  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.processRequest(request, response);
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    try {

        upload_path = AppConstants.ORG_CATEGORIES_HOME;

        // Verify the content type
        String contentType = request.getContentType();
        if ((contentType.indexOf("multipart/form-data") >= 0)) {

            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(AppConstants.TMP_FOLDER));

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

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

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

            out.println("<html>");
            out.println("<head>");
            out.println("<title>JSP File upload</title>");
            out.println("</head>");
            out.println("<body>");
            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (fi.isFormField()) {
                    // Get the uploaded file parameters
                    field_name = fi.getFieldName();
                    if (field_name.equals("category_name")) {
                        category_name = fi.getString();
                    }
                    if (field_name.equals("category_id")) {
                        category_id = fi.getString();
                    }
                    if (field_name.equals("organization")) {
                        organization_id = fi.getString();
                        upload_path = upload_path + File.separator + organization_id;
                    }

                } else {
                    field_name = fi.getFieldName();
                    file_name = fi.getName();

                    if (file_name != "") {
                        File uploadDir = new File(upload_path);
                        if (!uploadDir.exists()) {
                            uploadDir.mkdirs();
                        }

                        //                            int inStr = file_name.indexOf(".");
                        //                            String Str = file_name.substring(0, inStr);
                        //
                        //                            file_name = category_name + "_" + Str + ".jpeg";
                        file_name = category_name + "_" + file_name;
                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();

                        String filePath = upload_path + File.separator + file_name;
                        File storeFile = new File(filePath);

                        fi.write(storeFile);

                        out.println("Uploaded Filename: " + filePath + "<br>");
                    }
                }
            }
            categories.editCategories(Integer.parseInt(category_id), Integer.parseInt(organization_id),
                    category_name, file_name);
            response.sendRedirect(request.getContextPath() + "/admin/categories.jsp");
            out.println("</body>");
            out.println("</html>");
        } else {
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet upload</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<p>No file uploaded</p>");
            out.println("</body>");
            out.println("</html>");
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Exception while editing categories", ex);
    } finally {
        try {
            out.close();
        } catch (Exception e) {
        }
    }

}

From source file:com.krawler.spring.documents.documentDAOImpl.java

public KwlReturnObject uploadFile(FileItem fi, String userid, String companyId, ServletContext servletContext)
        throws ServiceException {
    Docs docObj = new Docs();
    List ll = new ArrayList();
    int dl = 0;//from w  ww .jav a  2  s  .c o m
    try {
        String fileName = new String(fi.getName().getBytes(), "UTF8");
        String Ext = "";
        String a = "";
        int index = fileName.lastIndexOf(".");
        if (index >= 0) {
            String dupExt = fileName.substring(fileName.lastIndexOf("."));
            Ext = fileName.substring(index + 1);
            a = Ext.toUpperCase();
            Ext = dupExt;
        }

        User userObj;
        if (userid != null) {
            userObj = (User) get(User.class, userid);
            docObj.setUserid(userObj);
        }
        docObj.setDocname(fileName);
        docObj.setStorename("");
        docObj.setDoctype(a + " " + "File");
        docObj.setUploadedon(new Date());
        docObj.setStorageindex(1);
        docObj.setDocsize(fi.getSize() + "");

        save(docObj);

        String fileid = docObj.getDocid();
        if (Ext.length() > 0) {
            fileid = fileid + Ext;
        }
        docObj.setStorename(fileid);

        saveOrUpdate(docObj);

        ll.add(docObj);

        //            String temp = "/home/trainee";
        String temp = storageHandlerImpl.GetDocStorePath();
        uploadFile(fi, temp, fileid);
        indexDocument(temp + fileid, docObj, companyId, servletContext);
    } catch (Exception e) {
        throw ServiceException.FAILURE(e.getMessage(), e);
    }
    return new KwlReturnObject(true, KWLErrorMsgs.S01, "", ll, dl);
}