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

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

Introduction

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

Prototype

InputStream getInputStream() throws IOException;

Source Link

Document

Returns an java.io.InputStream InputStream that can be used to retrieve the contents of the file.

Usage

From source file:com.wellmail.servlet.ConnectorServlet.java

/**
 * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br />
 * /*w ww .ja  va 2  s.com*/
 * The servlet accepts commands sent in the following format:<br />
 * <code>connector?Command=&lt;FileUpload&gt;&Type=&lt;ResourceType&gt;&CurrentFolder=&lt;FolderPath&gt;</code>
 * with the file in the <code>POST</code> body.<br />
 * <br>
 * It stores an uploaded file (renames a file if another exists with the
 * same name) and then returns the JavaScript callback.
 */
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("Entering Connector#doPost");

    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String commandStr = request.getParameter("Command");
    String typeStr = request.getParameter("Type");
    String currentFolderStr = request.getParameter("CurrentFolder");

    logger.debug("Parameter Command: {}", commandStr);
    logger.debug("Parameter Type: {}", typeStr);
    logger.debug("Parameter CurrentFolder: {}", currentFolderStr);

    UploadResponse ur;

    // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr'
    // are empty
    if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) {
        commandStr = "QuickUpload";
        currentFolderStr = "/";
    }

    if (!RequestCycleHandler.isEnabledForFileUpload(request))
        ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null,
                Messages.NOT_AUTHORIZED_FOR_UPLOAD);
    else if (!CommandHandler.isValidForPost(commandStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND);
    else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE);
    else if (!UtilsFile.isValidPath(currentFolderStr))
        ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
    else {
        ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr);

        String typePath = UtilsFile.constructServerSidePath(request, resourceType);
        String typeDirPath = getServletContext().getRealPath(typePath);

        File typeDir = new File(typeDirPath);
        UtilsFile.checkDirAndCreate(typeDir);

        File currentDir = new File(typeDir, currentFolderStr);

        if (!currentDir.exists())
            ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
        else {

            String newFilename = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            upload.setHeaderEncoding("UTF-8");

            try {

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

                // We upload only one file at the same time
                FileItem uplFile = items.get(0);
                String rawName = UtilsFile.sanitizeFileName(uplFile.getName());
                String filename = FilenameUtils.getName(rawName);
                String baseName = FilenameUtils.removeExtension(filename);
                String extension = FilenameUtils.getExtension(filename);

                filename = UUID.randomUUID().toString() + "." + extension;

                if (!ExtensionsHandler.isAllowed(resourceType, extension))
                    ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);

                //20k
                else if (uplFile.getSize() > 100 * 1024) {
                    ur = new UploadResponse(204);
                }

                else {

                    // construct an unique file name
                    File pathToSave = new File(currentDir, filename);
                    int counter = 1;
                    while (pathToSave.exists()) {
                        newFilename = baseName.concat("(").concat(String.valueOf(counter)).concat(")")
                                .concat(".").concat(extension);
                        pathToSave = new File(currentDir, newFilename);
                        counter++;
                    }

                    if (Utils.isEmpty(newFilename))
                        ur = new UploadResponse(UploadResponse.SC_OK,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(filename));
                    else
                        ur = new UploadResponse(UploadResponse.SC_RENAMED,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(newFilename),
                                newFilename);

                    // secure image check
                    if (resourceType.equals(ResourceTypeHandler.IMAGE)
                            && ConnectorHandler.isSecureImageUploads()) {
                        if (UtilsFile.isImage(uplFile.getInputStream()))
                            uplFile.write(pathToSave);
                        else {
                            uplFile.delete();
                            ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                        }
                    } else
                        uplFile.write(pathToSave);

                }
            } catch (Exception e) {
                ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR);
            }
        }

    }

    out.print(ur);
    out.flush();
    out.close();

    logger.debug("Exiting Connector#doPost");
}

From source file:net.fckeditor.connector.ConnectorServlet.java

/**
 * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br />
 * /*ww  w .j  ava2s  .c o m*/
 * The servlet accepts commands sent in the following format:<br />
 * <code>connector?Command=&lt;FileUpload&gt;&Type=&lt;ResourceType&gt;&CurrentFolder=&lt;FolderPath&gt;</code>
 * with the file in the <code>POST</code> body.<br />
 * <br>
 * It stores an uploaded file (renames a file if another exists with the
 * same name) and then returns the JavaScript callback.
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("Entering Connector#doPost");

    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String commandStr = request.getParameter("Command");
    String typeStr = request.getParameter("Type");
    String currentFolderStr = request.getParameter("CurrentFolder");

    logger.debug("Parameter Command: {}", commandStr);
    logger.debug("Parameter Type: {}", typeStr);
    logger.debug("Parameter CurrentFolder: {}", currentFolderStr);

    UploadResponse ur;

    // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr'
    // are empty
    if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) {
        commandStr = "QuickUpload";
        currentFolderStr = "/";
    }

    if (!RequestCycleHandler.isEnabledForFileUpload(request))
        ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null,
                Messages.NOT_AUTHORIZED_FOR_UPLOAD);
    else if (!CommandHandler.isValidForPost(commandStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND);
    else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE);
    else if (!UtilsFile.isValidPath(currentFolderStr))
        ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
    else {
        ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr);

        String typePath = UtilsFile.constructServerSidePath(request, resourceType);
        String typeDirPath = getServletContext().getRealPath(typePath);

        File typeDir = new File(typeDirPath);
        UtilsFile.checkDirAndCreate(typeDir);

        File currentDir = new File(typeDir, currentFolderStr);

        if (!currentDir.exists())
            ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
        else {

            String newFilename = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            // TODO ############???##############
            upload.setHeaderEncoding("UTF-8");

            try {

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

                // We upload only one file at the same time
                FileItem uplFile = items.get(0);
                String rawName = UtilsFile.sanitizeFileName(uplFile.getName());
                String filename = FilenameUtils.getName(rawName);
                String baseName = FilenameUtils.removeExtension(filename);
                String extension = FilenameUtils.getExtension(filename);

                // TODO ############??? ############
                filename = UUID.randomUUID().toString() + "." + extension;

                if (!ExtensionsHandler.isAllowed(resourceType, extension)) {
                    ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                } else if (uplFile.getSize() >= MAX_FILESIZE) {
                    ur = new UploadResponse(204);
                } else {

                    // construct an unique file name
                    File pathToSave = new File(currentDir, filename);
                    int counter = 1;
                    while (pathToSave.exists()) {
                        newFilename = baseName.concat("(").concat(String.valueOf(counter)).concat(")")
                                .concat(".").concat(extension);
                        pathToSave = new File(currentDir, newFilename);
                        counter++;
                    }

                    if (Utils.isEmpty(newFilename))
                        ur = new UploadResponse(UploadResponse.SC_OK,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(filename));
                    else
                        ur = new UploadResponse(UploadResponse.SC_RENAMED,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(newFilename),
                                newFilename);

                    // secure image check
                    if (resourceType.equals(ResourceTypeHandler.IMAGE)
                            && ConnectorHandler.isSecureImageUploads()) {
                        if (UtilsFile.isImage(uplFile.getInputStream()))
                            uplFile.write(pathToSave);
                        else {
                            uplFile.delete();
                            ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                        }
                    } else
                        uplFile.write(pathToSave);
                }
            } catch (Exception e) {
                ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR);
            }
        }
    }
    out.print(ur);
    out.flush();
    out.close();
    logger.debug("Exiting Connector#doPost");
}

From source file:com.wfms.common.web.ConnectorServlet.java

/**
 * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br />
 * /*from ww w  .  j  a  va  2  s.com*/
 * The servlet accepts commands sent in the following format:<br />
 * <code>connector?Command=&lt;FileUpload&gt;&Type=&lt;ResourceType&gt;&CurrentFolder=&lt;FolderPath&gt;</code>
 * with the file in the <code>POST</code> body.<br />
 * <br>
 * It stores an uploaded file (renames a file if another exists with the
 * same name) and then returns the JavaScript callback.
 */
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("Entering Connector#doPost");

    //response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String commandStr = request.getParameter("Command");
    String typeStr = request.getParameter("Type");
    String currentFolderStr = request.getParameter("CurrentFolder");

    logger.debug("Parameter Command: {}", commandStr);
    logger.debug("Parameter Type: {}", typeStr);
    logger.debug("Parameter CurrentFolder: {}", currentFolderStr);

    UploadResponse ur;

    // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr'
    // are empty
    if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) {
        commandStr = "QuickUpload";
        currentFolderStr = "/";
    }

    if (!RequestCycleHandler.isEnabledForFileUpload(request))
        ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null,
                Messages.NOT_AUTHORIZED_FOR_UPLOAD);
    else if (!CommandHandler.isValidForPost(commandStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND);
    else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE);
    else if (!UtilsFile.isValidPath(currentFolderStr))
        ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
    else {
        ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr);

        String typePath = UtilsFile.constructServerSidePath(request, resourceType);
        String typeDirPath = getServletContext().getRealPath(typePath);

        File typeDir = new File(typeDirPath);
        UtilsFile.checkDirAndCreate(typeDir);

        File currentDir = new File(typeDir, currentFolderStr);

        if (!currentDir.exists())
            ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
        else {

            String newFilename = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            try {

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

                // We upload only one file at the same time
                FileItem uplFile = items.get(0);
                String rawName = UtilsFile.sanitizeFileName(uplFile.getName());
                String filename = FilenameUtils.getName(rawName);
                String baseName = FilenameUtils.removeExtension(filename);
                String extension = FilenameUtils.getExtension(filename);

                //add code
                filename = UUID.randomUUID().toString() + "." + extension;
                if (!ExtensionsHandler.isAllowed(resourceType, extension)) {
                    ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                }
                //add conde to validate file size
                else if (uplFile.getSize() > 1024 * 1024) {
                    ur = new UploadResponse(204);
                } else {

                    // construct an unique file name
                    File pathToSave = new File(currentDir, filename);
                    int counter = 1;
                    while (pathToSave.exists()) {
                        newFilename = baseName.concat("(").concat(String.valueOf(counter)).concat(")")
                                .concat(".").concat(extension);
                        pathToSave = new File(currentDir, newFilename);
                        counter++;
                    }

                    if (Utils.isEmpty(newFilename))
                        ur = new UploadResponse(UploadResponse.SC_OK,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(filename));
                    else
                        ur = new UploadResponse(UploadResponse.SC_RENAMED,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(newFilename),
                                newFilename);

                    // secure image check
                    if (resourceType.equals(ResourceTypeHandler.IMAGE)
                            && ConnectorHandler.isSecureImageUploads()) {
                        if (UtilsFile.isImage(uplFile.getInputStream()))
                            uplFile.write(pathToSave);
                        else {
                            uplFile.delete();
                            ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                        }
                    } else
                        uplFile.write(pathToSave);

                }
            } catch (Exception e) {
                ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR);
            }
        }

    }

    out.print(ur);
    out.flush();
    out.close();

    logger.debug("Exiting Connector#doPost");
}

From source file:azkaban.webapp.servlet.ProjectManagerServlet.java

private void ajaxHandleUpload(HttpServletRequest req, Map<String, String> ret, Map<String, Object> multipart,
        Session session) throws ServletException, IOException {
    User user = session.getUser();/*from  w ww .  j  a  va  2 s  . c  o  m*/
    String projectName = (String) multipart.get("project");
    Project project = projectManager.getProject(projectName);
    String autoFix = (String) multipart.get("fix");
    Props props = new Props();
    if (autoFix != null && autoFix.equals("off")) {
        props.put(ValidatorConfigs.CUSTOM_AUTO_FIX_FLAG_PARAM, "false");
    } else {
        props.put(ValidatorConfigs.CUSTOM_AUTO_FIX_FLAG_PARAM, "true");
    }

    if (projectName == null || projectName.isEmpty()) {
        ret.put("error", "No project name found.");
    } else if (project == null) {
        ret.put("error", "Installation Failed. Project '" + projectName + "' doesn't exist.");
    } else if (!hasPermission(project, user, Type.WRITE)) {
        ret.put("error", "Installation Failed. User '" + user.getUserId() + "' does not have write access.");
    } else {
        ret.put("projectId", String.valueOf(project.getId()));

        FileItem item = (FileItem) multipart.get("file");
        String name = item.getName();
        String type = null;

        final String contentType = item.getContentType();
        if (contentType != null && (contentType.startsWith(APPLICATION_ZIP_MIME_TYPE)
                || contentType.startsWith("application/x-zip-compressed")
                || contentType.startsWith("application/octet-stream"))) {
            type = "zip";
        } else {
            item.delete();
            ret.put("error", "File type " + contentType + " unrecognized.");

            return;
        }

        File tempDir = Utils.createTempDir();
        OutputStream out = null;
        try {
            logger.info("Uploading file " + name);
            File archiveFile = new File(tempDir, name);
            out = new BufferedOutputStream(new FileOutputStream(archiveFile));
            IOUtils.copy(item.getInputStream(), out);
            out.close();

            Map<String, ValidationReport> reports = projectManager.uploadProject(project, archiveFile, type,
                    user, props);
            StringBuffer errorMsgs = new StringBuffer();
            StringBuffer warnMsgs = new StringBuffer();
            for (Entry<String, ValidationReport> reportEntry : reports.entrySet()) {
                ValidationReport report = reportEntry.getValue();
                if (!report.getInfoMsgs().isEmpty()) {
                    for (String msg : report.getInfoMsgs()) {
                        switch (ValidationReport.getInfoMsgLevel(msg)) {
                        case ERROR:
                            errorMsgs.append(ValidationReport.getInfoMsg(msg) + "<br/>");
                            break;
                        case WARN:
                            warnMsgs.append(ValidationReport.getInfoMsg(msg) + "<br/>");
                            break;
                        default:
                            break;
                        }
                    }
                }
                if (!report.getErrorMsgs().isEmpty()) {
                    errorMsgs.append("Validator " + reportEntry.getKey() + " reports errors:<ul>");
                    for (String msg : report.getErrorMsgs()) {
                        errorMsgs.append("<li>" + msg + "</li>");
                    }
                    errorMsgs.append("</ul>");
                }
                if (!report.getWarningMsgs().isEmpty()) {
                    warnMsgs.append("Validator " + reportEntry.getKey() + " reports warnings:<ul>");
                    for (String msg : report.getWarningMsgs()) {
                        warnMsgs.append("<li>" + msg + "</li>");
                    }
                    warnMsgs.append("</ul>");
                }
            }
            if (errorMsgs.length() > 0) {
                // If putting more than 4000 characters in the cookie, the entire
                // message
                // will somehow get discarded.
                ret.put("error",
                        errorMsgs.length() > 4000 ? errorMsgs.substring(0, 4000) : errorMsgs.toString());
            }
            if (warnMsgs.length() > 0) {
                ret.put("warn", warnMsgs.length() > 4000 ? warnMsgs.substring(0, 4000) : warnMsgs.toString());
            }
        } catch (Exception e) {
            logger.info("Installation Failed.", e);
            String error = e.getMessage();
            if (error.length() > 512) {
                error = error.substring(0, 512) + "<br>Too many errors to display.<br>";
            }
            ret.put("error", "Installation Failed.<br>" + error);
        } finally {
            if (tempDir.exists()) {
                FileUtils.deleteDirectory(tempDir);
            }
            if (out != null) {
                out.close();
            }
        }

        ret.put("version", String.valueOf(project.getVersion()));
    }
}

From source file:com.enonic.vertical.adminweb.handlers.SimpleContentHandlerServlet.java

private void fileImport(User oldUser, HttpServletRequest request, HttpServletResponse response,
        ExtendedMap formItems) throws VerticalAdminException {

    int categoryKey = formItems.getInt("cat");
    int unitKey = formItems.getInt("selectedunitkey");

    try {//from w  ww . j a v  a  2 s.  c o  m
        String importName = formItems.getString("importname");
        FileItem fileItem = formItems.getFileItem("importfile");
        Date publishFrom = null;
        Date publishTo = null;

        if (formItems.containsKey("date_pubdata_publishfrom")) {
            try {
                StringBuffer date = new StringBuffer(formItems.getString("date_pubdata_publishfrom"));
                date.append(' ');
                date.append(formItems.getString("time_pubdata_publishfrom", "00:00"));
                publishFrom = DateUtil.parseDateTime(date.toString());
                if (formItems.containsKey("date_pubdata_publishto")) {
                    date = new StringBuffer(formItems.getString("date_pubdata_publishto"));
                    date.append(' ');
                    date.append(formItems.getString("time_pubdata_publishto", "00:00"));
                    publishTo = DateUtil.parseDateTime(date.toString());
                }
            } catch (ParseException pe) {
                String message = "Failed to parse publish from or to date: %t";
                VerticalAdminLogger.errorAdmin(this.getClass(), 0, message, pe);
            }
        }

        Document doc = XMLTool.createDocument("data");
        XMLTool.mergeDocuments(doc, adminService.getSuperCategoryNames(categoryKey, true, true), true);

        Map<String, Object> xslParams = new HashMap<String, Object>();
        xslParams.put("cat", formItems.getString("cat"));
        xslParams.put("page", formItems.getString("page"));
        addCommonParameters(adminService, null, request, xslParams, unitKey, -1);

        final CategoryEntity categoryToImportTo = categoryDao.findByKey(new CategoryKey(categoryKey));
        if (categoryToImportTo == null) {
            throw new IllegalArgumentException("Category does not exist " + categoryKey);
        }

        final ImportContentCommand importContentCommand = new ImportContentCommand();
        importContentCommand.importer = this.securityService.getUser(oldUser);
        importContentCommand.categoryToImportTo = categoryToImportTo;
        importContentCommand.importName = importName;
        importContentCommand.publishFrom = publishFrom != null ? new DateTime(publishFrom) : null;
        importContentCommand.publishTo = publishTo != null ? new DateTime(publishTo) : null;
        importContentCommand.inputStream = fileItem.getInputStream();

        AssignmentDataParser assignmentDataParser = new AssignmentDataParser(formItems);

        String assigneeKeyString = assignmentDataParser.getAssigneeKey();

        if (StringUtils.isNotBlank(assigneeKeyString)) {
            UserEntity assignee = userDao.findByKey(assigneeKeyString);

            if (assignee == null) {
                throw new IllegalArgumentException("Assignee not found: " + assigneeKeyString);
            }

            String assignmentDescr = assignmentDataParser.getAssignmentDescription();
            Date assignmentDueDate = assignmentDataParser.getAssignmentDueDate();

            importContentCommand.assigneeKey = assignee.getKey();
            importContentCommand.assignmentDescription = assignmentDescr;
            importContentCommand.assignmentDueDate = assignmentDueDate;
        }

        final ImportJob importJob = importJobFactory.createImportJob(importContentCommand);
        final ImportResult report = importJob.start();

        final ImportResultXmlCreator reportCreator = new ImportResultXmlCreator();
        reportCreator.setIncludeContentInformation(false);

        final boolean sendAssignmentMail = report.getAssigned().size() > 0 && importJob.getAssignee() != null;

        if (sendAssignmentMail) {
            sendAssignmentMail(oldUser, assignmentDataParser, importJob, report);
        }

        XMLTool.mergeDocuments(doc, reportCreator.getReport(report).getAsString(), true);

        transformXML(request, response, doc, "fileimport_report.xsl", xslParams);
    } catch (IOException e) {
        VerticalAdminLogger.errorAdmin(this.getClass(), 20, "I/O error: %t", e);
    }
}

From source file:com.ecyrd.jspwiki.attachment.AttachmentServlet.java

/**
 *  Uploads a specific mime multipart input set, intercepts exceptions.
 *
 *  @param req The servlet request/*from w  w  w  .  j a va  2 s  .c om*/
 *  @return The page to which we should go next.
 *  @throws RedirectException If there's an error and a redirection is needed
 *  @throws IOException If upload fails
 * @throws FileUploadException 
 */
@SuppressWarnings("unchecked")
protected String upload(HttpServletRequest req) throws RedirectException, IOException {
    String msg = "";
    String attName = "(unknown)";
    String errorPage = m_engine.getURL(WikiContext.ERROR, "", null, false); // If something bad happened, Upload should be able to take care of most stuff
    String nextPage = errorPage;

    String progressId = req.getParameter("progressid");

    // Check that we have a file upload request
    if (!ServletFileUpload.isMultipartContent(req)) {
        throw new RedirectException("Not a file upload", errorPage);
    }

    try {
        FileItemFactory factory = new DiskFileItemFactory();

        // Create the context _before_ Multipart operations, otherwise
        // strict servlet containers may fail when setting encoding.
        WikiContext context = m_engine.createContext(req, WikiContext.ATTACH);

        UploadListener pl = new UploadListener();

        m_engine.getProgressManager().startProgress(pl, progressId);

        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");
        if (!context.hasAdminPermissions()) {
            upload.setFileSizeMax(m_maxSize);
        }
        upload.setProgressListener(pl);
        List<FileItem> items = upload.parseRequest(req);

        String wikipage = null;
        String changeNote = null;
        FileItem actualFile = null;

        for (FileItem item : items) {
            if (item.isFormField()) {
                if (item.getFieldName().equals("page")) {
                    //
                    // FIXME: Kludge alert.  We must end up with the parent page name,
                    //        if this is an upload of a new revision
                    //

                    wikipage = item.getString("UTF-8");
                    int x = wikipage.indexOf("/");

                    if (x != -1)
                        wikipage = wikipage.substring(0, x);
                } else if (item.getFieldName().equals("changenote")) {
                    changeNote = item.getString("UTF-8");
                    if (changeNote != null) {
                        changeNote = TextUtil.replaceEntities(changeNote);
                    }
                } else if (item.getFieldName().equals("nextpage")) {
                    nextPage = validateNextPage(item.getString("UTF-8"), errorPage);
                }
            } else {
                actualFile = item;
            }
        }

        if (actualFile == null)
            throw new RedirectException("Broken file upload", errorPage);

        //
        // FIXME: Unfortunately, with Apache fileupload we will get the form fields in
        //        order.  This means that we have to gather all the metadata from the
        //        request prior to actually touching the uploaded file itself.  This
        //        is because the changenote appears after the file upload box, and we
        //        would not have this information when uploading.  This also means
        //        that with current structure we can only support a single file upload
        //        at a time.
        //
        String filename = actualFile.getName();
        long fileSize = actualFile.getSize();
        InputStream in = actualFile.getInputStream();

        try {
            executeUpload(context, in, filename, nextPage, wikipage, changeNote, fileSize);
        } finally {
            in.close();
        }

    } catch (ProviderException e) {
        msg = "Upload failed because the provider failed: " + e.getMessage();
        log.warn(msg + " (attachment: " + attName + ")", e);

        throw new IOException(msg);
    } catch (IOException e) {
        // Show the submit page again, but with a bit more
        // intimidating output.
        msg = "Upload failure: " + e.getMessage();
        log.warn(msg + " (attachment: " + attName + ")", e);

        throw e;
    } catch (FileUploadException e) {
        // Show the submit page again, but with a bit more
        // intimidating output.
        msg = "Upload failure: " + e.getMessage();
        log.warn(msg + " (attachment: " + attName + ")", e);

        throw new IOException(msg);
    } finally {
        m_engine.getProgressManager().stopProgress(progressId);
        // FIXME: In case of exceptions should absolutely
        //        remove the uploaded file.
    }

    return nextPage;
}

From source file:com.ccsna.safetynet.NewsServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* ww w  .j  a  v  a 2s  . c o  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
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try {
        PrintWriter out = response.getWriter();
        String smallUrl = "", largeUrl = "", message = "", title = "", content = "", startDate = "",
                endDate = "", newsType = "", st = "", endTime = "", startTime = "", fileType = null;

        Date sDate = null, eDate = null;
        Time eTime = null, sTime = null;
        int action = 0, newsId = 0;
        boolean dataValid = true;
        News news = null;
        String fullPath = null;
        Member loggedInMember = UserAuthenticator.loggedInUser(request.getSession());
        if (loggedInMember != null) {
            String createdBy = String.valueOf(loggedInMember.getMemberId());
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            log.info("isMultipart :" + isMultipart);
            if (isMultipart) {
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                String appPath = request.getServletContext().getRealPath("");

                //String glassfishInstanceRootPropertyName = "com.sun.aas.instanceRoot";
                //String instanceRoot = System.getProperty(glassfishInstanceRootPropertyName) + "/applications/user-pix/";
                try {
                    List items = upload.parseRequest(request);
                    Iterator iterator = items.iterator();
                    while (iterator.hasNext()) {
                        FileItem item = (FileItem) iterator.next();
                        if (!item.isFormField()) {
                            //log.info("item is form field");
                            String fileName = item.getName();
                            //log.info("the name of the item is :" + fileName);
                            String contentType = item.getContentType();
                            //log.info("the content type is :" + contentType);
                            if (item.getContentType().equalsIgnoreCase(JPEG)
                                    || item.getContentType().equalsIgnoreCase(JPG)
                                    || item.getContentType().equalsIgnoreCase(PDF)) {
                                String root = appPath;
                                log.info("pdf content recognised");
                                log.info("root path is :" + appPath);
                                //String smallLoc = "/uploads/small";
                                String largeLoc = "/uploads/large";
                                log.info("largeLoc:" + largeLoc);
                                //File pathSmall = new File(root + smallLoc);
                                File pathLarge = new File(root + largeLoc);
                                //log.info("small image path :" + pathSmall);
                                log.info("large image path :" + pathLarge);
                                if (!pathLarge.exists()) {
                                    // boolean status = pathSmall.mkdirs();
                                    pathLarge.mkdirs();
                                }
                                if (item.getContentType().equalsIgnoreCase(PDF)) {
                                    log.info("loading pdf file");
                                    fileType = Menu.PDF;
                                    fileName = createdBy + "_" + System.currentTimeMillis() + "."
                                            + PDF_EXTENSION;

                                    //File uploadedFileSmall = new File(pathSmall + "/" + fileName);
                                    File uploadedFileLarge = new File(pathLarge + "/" + fileName);
                                    Menu.uploadPdfFile(item.getInputStream(), uploadedFileLarge);

                                } else {
                                    fileType = Menu.IMAGE;
                                    fileName = createdBy + "_" + System.currentTimeMillis() + "."
                                            + JPEG_EXTENSION;

                                    log.info("filename is : " + fileName);
                                    // File uploadedFileSmall = new File(pathSmall + "/" + fileName);
                                    File uploadedFileLarge = new File(pathLarge + "/" + fileName);
                                    //Menu.resizeImage(item.getInputStream(), 160, uploadedFileSmall);
                                    Menu.resizeImage(item.getInputStream(), 160, uploadedFileLarge);
                                }
                                //smallUrl = smallLoc + "/" + fileName + "";
                                largeUrl = largeLoc + "/" + fileName + "";
                                log.info("largeUrl image url is :" + largeUrl);

                                fullPath = request.getContextPath() + "/" + largeUrl;

                            }
                        } else {
                            if (item.getFieldName().equalsIgnoreCase("newsTitle")) {
                                title = item.getString();
                                log.info("title is :" + title);
                            }
                            if (item.getFieldName().equalsIgnoreCase("type")) {
                                newsType = item.getString();
                                log.info("newsType is :" + newsType);
                            }
                            if (item.getFieldName().equalsIgnoreCase("content")) {
                                content = item.getString();
                                log.info("content is :" + content);
                            }
                            if (item.getFieldName().equalsIgnoreCase("start_Date")) {
                                startDate = item.getString();
                                if (startDate != null && !startDate.isEmpty()) {
                                    sDate = Menu
                                            .convertDateToSqlDate(Menu.stringToDate(startDate, "yyyy-MM-dd"));
                                }
                                log.info("startDate is :" + startDate);
                            }
                            if (item.getFieldName().equalsIgnoreCase("end_Date")) {
                                endDate = item.getString();
                                if (endDate != null && !endDate.isEmpty()) {
                                    eDate = Menu.convertDateToSqlDate(Menu.stringToDate(endDate, "yyyy-MM-dd"));
                                }
                                log.info("endDate is :" + endDate);
                            }
                            if (item.getFieldName().equalsIgnoreCase("action")) {
                                action = Integer.parseInt(item.getString());
                                log.info("the action is :" + action);
                            }
                            if (item.getFieldName().equalsIgnoreCase("newsId")) {
                                newsId = Integer.parseInt(item.getString());
                                log.info("the newsid is :" + newsId);
                            }
                            if (item.getFieldName().equalsIgnoreCase("status")) {
                                st = item.getString();
                                log.info("the status is :" + st);
                            }
                            if (item.getFieldName().equalsIgnoreCase("end_Time")) {
                                endTime = item.getString();
                                if (endTime != null && !endTime.isEmpty()) {
                                    eTime = Menu.convertStringToSqlTime(endTime);
                                }
                                log.info("eTime is :" + eTime);

                            }

                            if (item.getFieldName().equalsIgnoreCase("start_Time")) {
                                startTime = item.getString();
                                if (startTime != null && !startTime.isEmpty()) {
                                    sTime = Menu.convertStringToSqlTime(startTime);
                                }
                                log.info("sTime is :" + sTime);

                            }
                        }
                    }
                } catch (FileUploadException e) {
                    e.printStackTrace();
                }
            }
            switch (Validation.Actions.values()[action]) {
            case CREATE:
                log.info("creating new serlvet ................"); {

                news = new NewsModel().addNews(title, newsType, content, sDate, eDate, new Date(), createdBy,
                        Menu.ACTIVE, largeUrl, fileType, fullPath);
            }
                if (news != null) {
                    log.info("news successfully created...");
                    message += "News item has been successfully added";
                    Validation.setAttributes(request, Validation.SUCCESS, message);
                    response.sendRedirect(request.getContextPath() + "/admin/management.jsp");
                } else {
                    log.info("news creating failed...");
                    message += "Unable to add news item";
                    Validation.setAttributes(request, Validation.ERROR, message);
                    response.sendRedirect(request.getContextPath() + "/admin/management.jsp");
                }
                break;
            case UPDATE:
                log.info("updating news ...");
                if (title != null && !title.isEmpty()) {
                    news = new NewsModel().findByParameter("title", title);
                }

                if (news != null && (news.getNewsId() == newsId)) {
                    log.info("news is :" + news.getNewsId());
                    dataValid = true;
                } else {
                    dataValid = false;
                }
                if (news == null) {
                    dataValid = true;
                }

                log.info("dataValid is :" + dataValid);

                if (dataValid) {
                    boolean newsUpdated = new NewsModel().updateNews(newsId, title, newsType, content, sDate,
                            eDate, createdBy, st, largeUrl, smallUrl, sTime, eTime);
                    if (newsUpdated) {
                        message += "News/Alert has been successfully updated";
                        Validation.setAttributes(request, Validation.SUCCESS, message);
                        response.sendRedirect(request.getContextPath() + "/admin/management.jsp");

                    } else {
                        message += "Unable to update news item";
                        Validation.setAttributes(request, Validation.ERROR, message);
                        response.sendRedirect(request.getContextPath() + "/admin/newsEdit.jsp?id=" + newsId);
                    }
                } else {
                    message += "News with same title already exist, Enter a different title";
                    Validation.setAttributes(request, Validation.ERROR, message);
                    response.sendRedirect(request.getContextPath() + "/admin/newsEdit.jsp?id=" + newsId);
                }
                break;
            }
        } else {
            message += "Session expired, Kindly login with username and password";
            Validation.setAttributes(request, Validation.ERROR, message);
            response.sendRedirect(request.getContextPath() + "/index.jsp");
        }
    } catch (Exception e) {

    }
}

From source file:com.ccsna.safetynet.AdminNewsServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from w  w w.j a  v  a2s.  c  o  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
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try {
        PrintWriter out = response.getWriter();
        String smallUrl = "", largeUrl = "", message = "", title = "", content = "", startDate = "",
                endDate = "", newsType = "", st = "", endTime = "", startTime = "", fileType = null;
        Date sDate = null, eDate = null;
        Time eTime = null, sTime = null;
        String fullPath = null;
        int action = 0, newsId = 0;
        boolean dataValid = true;
        News news = null;
        Member loggedInMember = UserAuthenticator.loggedInUser(request.getSession());
        if (loggedInMember != null) {
            String home = "";
            String alertPage = "";
            if (loggedInMember.getRole().equals(Menu.MEMBER)) {
                home = "/pages/member.jsp";
                alertPage = "/pages/memberAlert.jsp";

            } else {
                home = "/pages/agencyAdmin.jsp";
                alertPage = "/pages/editAlert.jsp";

            }
            log.info("home page is : " + home);
            log.info("alert page is : " + alertPage);

            String createdBy = String.valueOf(loggedInMember.getMemberId());
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            log.info("isMultipart :" + isMultipart);
            if (isMultipart) {
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                String appPath = request.getServletContext().getRealPath("");

                //String glassfishInstanceRootPropertyName = "com.sun.aas.instanceRoot";
                //String instanceRoot = System.getProperty(glassfishInstanceRootPropertyName) + "/applications/user-pix/";
                try {
                    List items = upload.parseRequest(request);
                    Iterator iterator = items.iterator();
                    while (iterator.hasNext()) {
                        FileItem item = (FileItem) iterator.next();
                        if (!item.isFormField()) {
                            //log.info("item is form field");
                            String fileName = item.getName();
                            //log.info("the name of the item is :" + fileName);
                            String contentType = item.getContentType();
                            //log.info("the content type is :" + contentType);
                            if (item.getContentType().equalsIgnoreCase(JPEG)
                                    || item.getContentType().equalsIgnoreCase(JPG)
                                    || item.getContentType().equalsIgnoreCase(PDF)) {
                                String root = appPath;
                                log.info("pdf content recognised");
                                log.info("root path is :" + appPath);
                                //String smallLoc = "/uploads/small";
                                String largeLoc = "/uploads/large";
                                log.info("largeLoc:" + largeLoc);
                                //File pathSmall = new File(root + smallLoc);
                                File pathLarge = new File(root + largeLoc);
                                //log.info("small image path :" + pathSmall);
                                log.info("large image path :" + pathLarge);
                                if (!pathLarge.exists()) {
                                    // boolean status = pathSmall.mkdirs();
                                    pathLarge.mkdirs();
                                }
                                if (item.getContentType().equalsIgnoreCase(PDF)) {
                                    log.info("loading pdf file");
                                    fileType = Menu.PDF;
                                    fileName = createdBy + "_" + System.currentTimeMillis() + "."
                                            + PDF_EXTENSION;

                                    //File uploadedFileSmall = new File(pathSmall + "/" + fileName);
                                    File uploadedFileLarge = new File(pathLarge + "/" + fileName);
                                    Menu.uploadPdfFile(item.getInputStream(), uploadedFileLarge);

                                } else {
                                    fileType = Menu.IMAGE;
                                    fileName = createdBy + "_" + System.currentTimeMillis() + "."
                                            + JPEG_EXTENSION;

                                    log.info("filename is : " + fileName);
                                    // File uploadedFileSmall = new File(pathSmall + "/" + fileName);
                                    File uploadedFileLarge = new File(pathLarge + "/" + fileName);
                                    //Menu.resizeImage(item.getInputStream(), 160, uploadedFileSmall);
                                    Menu.resizeImage(item.getInputStream(), 160, uploadedFileLarge);
                                }
                                //smallUrl = smallLoc + "/" + fileName + "";
                                largeUrl = largeLoc + "/" + fileName + "";
                                log.info("largeUrl image url is :" + largeUrl);
                                fullPath = request.getContextPath() + "/" + largeUrl;

                            }
                        } else {
                            if (item.getFieldName().equalsIgnoreCase("newsTitle")) {
                                title = item.getString();
                                log.info("title is :" + title);
                            }
                            if (item.getFieldName().equalsIgnoreCase("type")) {
                                newsType = item.getString();
                                log.info("newsType is :" + newsType);
                            }
                            if (item.getFieldName().equalsIgnoreCase("content")) {
                                content = item.getString();
                                log.info("content is :" + content);
                            }
                            if (item.getFieldName().equalsIgnoreCase("start_Date")) {
                                startDate = item.getString();
                                if (startDate != null && !startDate.isEmpty()) {
                                    sDate = Menu
                                            .convertDateToSqlDate(Menu.stringToDate(startDate, "yyyy-MM-dd"));
                                }
                                log.info("startDate is :" + startDate);
                            }
                            if (item.getFieldName().equalsIgnoreCase("end_Date")) {
                                endDate = item.getString();
                                if (endDate != null && !endDate.isEmpty()) {
                                    eDate = Menu.convertDateToSqlDate(Menu.stringToDate(endDate, "yyyy-MM-dd"));
                                }
                                log.info("endDate is :" + endDate);
                            }
                            if (item.getFieldName().equalsIgnoreCase("action")) {
                                action = Integer.parseInt(item.getString());
                                log.info("the action is :" + action);
                            }
                            if (item.getFieldName().equalsIgnoreCase("newsId")) {
                                newsId = Integer.parseInt(item.getString());
                                log.info("the newsid is :" + newsId);
                            }
                            if (item.getFieldName().equalsIgnoreCase("status")) {
                                st = item.getString();
                                log.info("the status is :" + st);
                            }
                            if (item.getFieldName().equalsIgnoreCase("end_Time")) {
                                endTime = item.getString();
                                if (endTime != null && !endTime.isEmpty()) {
                                    eTime = Menu.convertStringToSqlTime(endTime);
                                }
                                log.info("eTime is :" + eTime);

                            }

                            if (item.getFieldName().equalsIgnoreCase("start_Time")) {
                                startTime = item.getString();
                                if (startTime != null && !startTime.isEmpty()) {
                                    sTime = Menu.convertStringToSqlTime(startTime);
                                }
                                log.info("sTime is :" + sTime);

                            }
                        }
                    }
                } catch (FileUploadException e) {
                    e.printStackTrace();
                }
            }
            switch (Validation.Actions.values()[action]) {
            case CREATE:
                log.info("creating new serlvet ................");
                news = new NewsModel().addNews(title, newsType, content, sDate, eDate, new Date(), createdBy,
                        Menu.ACTIVE, largeUrl, fileType, fullPath);
                if (news != null) {
                    log.info("news successfully created...");
                    message += "News item has been successfully added";
                    Validation.setAttributes(request, Validation.SUCCESS, message);
                    response.sendRedirect(request.getContextPath() + home);
                } else {
                    log.info("news creating failed...");
                    message += "Unable to add news item";
                    Validation.setAttributes(request, Validation.ERROR, message);
                    response.sendRedirect(request.getContextPath() + home);
                }
                break;
            case UPDATE:
                log.info("updating news ...");
                if (title != null && !title.isEmpty()) {
                    news = new NewsModel().findByParameter("title", title);
                }

                if (news != null && (news.getNewsId() == newsId)) {
                    log.info("news is :" + news.getNewsId());
                    dataValid = true;
                } else {
                    dataValid = false;
                }
                if (news == null) {
                    dataValid = true;
                }

                log.info("dataValid is :" + dataValid);

                if (dataValid) {
                    boolean newsUpdated = new NewsModel().updateNews(newsId, title, newsType, content, sDate,
                            eDate, createdBy, st, largeUrl, smallUrl, sTime, eTime);
                    if (newsUpdated) {
                        message += "News/Alert has been successfully updated";
                        Validation.setAttributes(request, Validation.SUCCESS, message);
                        response.sendRedirect(request.getContextPath() + home);

                    } else {
                        message += "Unable to update news item";
                        Validation.setAttributes(request, Validation.ERROR, message);
                        response.sendRedirect(request.getContextPath() + alertPage + "?id=" + newsId);
                    }
                } else {
                    message += "News with same title already exist, Enter a different title";
                    Validation.setAttributes(request, Validation.ERROR, message);
                    response.sendRedirect(request.getContextPath() + alertPage + "?id=" + newsId);
                }
                break;
            }
        } else {
            message += "Session expired, Kindly login with username and password";
            Validation.setAttributes(request, Validation.ERROR, message);
            response.sendRedirect(request.getContextPath() + "/index.jsp");
        }
    } catch (Exception e) {

    }

}

From source file:cn.edu.hbcit.servlets.ConnectorServlet.java

/**
 * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br />
 * //ww w.  j  av  a  2s . c om
 * The servlet accepts commands sent in the following format:<br />
 * <code>connector?Command=&lt;FileUpload&gt;&Type=&lt;ResourceType&gt;&CurrentFolder=&lt;FolderPath&gt;</code>
 * with the file in the <code>POST</code> body.<br />
 * <br>
 * It stores an uploaded file (renames a file if another exists with the
 * same name) and then returns the JavaScript callback.
 */
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("Entering Connector#doPost");

    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String commandStr = request.getParameter("Command");
    String typeStr = request.getParameter("Type");
    String currentFolderStr = request.getParameter("CurrentFolder");

    logger.debug("Parameter Command: {}", commandStr);
    logger.debug("Parameter Type: {}", typeStr);
    logger.debug("Parameter CurrentFolder: {}", currentFolderStr);

    UploadResponse ur;

    // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr'
    // are empty
    if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) {
        commandStr = "QuickUpload";
        currentFolderStr = "/";
    }

    if (!RequestCycleHandler.isEnabledForFileUpload(request))
        ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null,
                Messages.NOT_AUTHORIZED_FOR_UPLOAD);
    else if (!CommandHandler.isValidForPost(commandStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND);
    else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE);
    else if (!UtilsFile.isValidPath(currentFolderStr))
        ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
    else {
        ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr);

        String typePath = UtilsFile.constructServerSidePath(request, resourceType);
        String typeDirPath = getServletContext().getRealPath(typePath);

        File typeDir = new File(typeDirPath);
        UtilsFile.checkDirAndCreate(typeDir);

        File currentDir = new File(typeDir, currentFolderStr);

        if (!currentDir.exists())
            ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
        else {

            String newFilename = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            FileOperate fo = new FileOperate();//liwei (+ )
            upload.setHeaderEncoding("UTF-8");//liwei 
            try {

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

                // We upload only one file at the same time
                FileItem uplFile = items.get(0);
                String rawName = UtilsFile.sanitizeFileName(uplFile.getName());
                String filename = FilenameUtils.getName(rawName);
                String oldName = FilenameUtils.getName(rawName);
                String baseName = FilenameUtils.removeExtension(filename);
                String extension = FilenameUtils.getExtension(filename);
                filename = fo.generateRandomFilename() + extension;//liwei (+ )
                //filename = UUID.randomUUID().toString()+"."+extension;//liwei (UUID)
                logger.warn("" + oldName + "" + filename + "");
                if (!ExtensionsHandler.isAllowed(resourceType, extension))
                    ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                else {

                    // construct an unique file name
                    File pathToSave = new File(currentDir, filename);
                    int counter = 1;
                    while (pathToSave.exists()) {
                        newFilename = baseName.concat("(").concat(String.valueOf(counter)).concat(")")
                                .concat(".").concat(extension);
                        pathToSave = new File(currentDir, newFilename);
                        counter++;
                    }

                    if (Utils.isEmpty(newFilename))
                        ur = new UploadResponse(UploadResponse.SC_OK,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(filename));
                    else
                        ur = new UploadResponse(UploadResponse.SC_RENAMED,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(newFilename),
                                newFilename);

                    // secure image check
                    if (resourceType.equals(ResourceTypeHandler.IMAGE)
                            && ConnectorHandler.isSecureImageUploads()) {
                        if (UtilsFile.isImage(uplFile.getInputStream()))
                            uplFile.write(pathToSave);
                        else {
                            uplFile.delete();
                            ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                        }
                    } else
                        uplFile.write(pathToSave);

                }
            } catch (Exception e) {
                ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR);
            }
        }

    }

    out.print(ur);
    out.flush();
    out.close();

    logger.debug("Exiting Connector#doPost");
}

From source file:com.jl.common.ConnectorServlet.java

/**
 * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br />
 * //from   w w w . j  av  a  2  s . c  om
 * The servlet accepts commands sent in the following format:<br />
 * <code>connector?Command=&lt;FileUpload&gt;&Type=&lt;ResourceType&gt;&CurrentFolder=&lt;FolderPath&gt;</code>
 * with the file in the <code>POST</code> body.<br />
 * <br>
 * It stores an uploaded file (renames a file if another exists with the
 * same name) and then returns the JavaScript callback.
 */
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("Entering Connector#doPost");

    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String commandStr = request.getParameter("Command");
    String typeStr = request.getParameter("Type");
    String currentFolderStr = request.getParameter("CurrentFolder");

    logger.debug("Parameter Command: {}", commandStr);
    logger.debug("Parameter Type: {}", typeStr);
    logger.debug("Parameter CurrentFolder: {}", currentFolderStr);

    UploadResponse ur;

    // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr'
    // are empty
    if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) {
        commandStr = "QuickUpload";
        currentFolderStr = "/";
    }

    if (!RequestCycleHandler.isEnabledForFileUpload(request))
        ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null,
                Messages.NOT_AUTHORIZED_FOR_UPLOAD);
    else if (!CommandHandler.isValidForPost(commandStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND);
    else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE);
    else if (!UtilsFile.isValidPath(currentFolderStr))
        ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
    else {
        ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr);

        String typePath = UtilsFile.constructServerSidePath(request, resourceType);
        String typeDirPath = getServletContext().getRealPath(typePath);

        File typeDir = new File(typeDirPath);
        UtilsFile.checkDirAndCreate(typeDir);

        File currentDir = new File(typeDir, currentFolderStr);

        if (!currentDir.exists())
            ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
        else {

            String newFilename = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            upload.setHeaderEncoding("UTF-8");//

            try {

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

                // We upload only one file at the same time
                FileItem uplFile = items.get(0);
                String rawName = UtilsFile.sanitizeFileName(uplFile.getName());
                String filename = FilenameUtils.getName(rawName);
                String baseName = FilenameUtils.removeExtension(filename);
                String extension = FilenameUtils.getExtension(filename);

                filename = UUID.randomUUID().toString() + "." + extension;//

                //
                if (!ExtensionsHandler.isAllowed(resourceType, extension)) {
                    ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                }

                //
                else if (uplFile.getSize() > 50 * 1024) {
                    //
                    ur = new UploadResponse(204);
                }
                // 
                else {

                    // construct an unique file name
                    File pathToSave = new File(currentDir, filename);
                    int counter = 1;
                    while (pathToSave.exists()) {
                        newFilename = baseName.concat("(").concat(String.valueOf(counter)).concat(")")
                                .concat(".").concat(extension);
                        pathToSave = new File(currentDir, newFilename);
                        counter++;
                    }

                    if (Utils.isEmpty(newFilename))
                        ur = new UploadResponse(UploadResponse.SC_OK,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(filename));
                    else
                        ur = new UploadResponse(UploadResponse.SC_RENAMED,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(newFilename),
                                newFilename);

                    // secure image check
                    if (resourceType.equals(ResourceTypeHandler.IMAGE)
                            && ConnectorHandler.isSecureImageUploads()) {
                        if (UtilsFile.isImage(uplFile.getInputStream()))
                            uplFile.write(pathToSave);
                        else {
                            uplFile.delete();
                            ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                        }
                    } else
                        uplFile.write(pathToSave);

                }
            } catch (Exception e) {
                ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR);
            }
        }

    }
    out.print(ur);
    out.flush();
    out.close();

    logger.debug("Exiting Connector#doPost");
}