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

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

Introduction

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

Prototype

void delete();

Source Link

Document

Deletes the underlying storage for a file item, including deleting any associated temporary disk file.

Usage

From source file:net.hillsdon.reviki.web.pages.impl.DefaultPageImpl.java

public View attach(final PageReference page, final ConsumedPath path, final HttpServletRequest request,
        final HttpServletResponse response) throws Exception {
    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new InvalidInputException("multipart request expected.");
    }/*from  w w w .java  2  s  .  c  om*/
    List<FileItem> items = getFileItems(request);
    try {
        if (items.size() > 4) {
            throw new InvalidInputException("One file at a time.");
        }
        String attachmentName = null;
        Long baseRevision = null;
        String attachmentMessage = null;
        FileItem file = null;
        for (FileItem item : items) {
            if (PARAM_ATTACHMENT_NAME.equals(item.getFieldName())) {
                attachmentName = item.getString().trim();
            }
            if (PARAM_BASE_REVISION.equals(item.getFieldName())) {
                baseRevision = RequestParameterReaders.getLong(item.getString().trim(), PARAM_BASE_REVISION);
            }
            if (PARAM_ATTACHMENT_MESSAGE.equals(item.getFieldName())) {
                attachmentMessage = item.getString().trim();
                if (attachmentMessage.length() == 0) {
                    attachmentMessage = null;
                }
            }
            if (!item.isFormField()) {
                file = item;
            }
        }
        if (baseRevision == null) {
            baseRevision = VersionedPageInfo.UNCOMMITTED;
        }

        if (file == null || file.getSize() == 0) {
            request.setAttribute("flash", ERROR_NO_FILE);
            return attachments(page, path, request, response);
        } else {
            InputStream in = file.getInputStream();
            try {
                // get the page from store - needed to get content of the special
                // pages which were not saved yet
                PageInfo pageInfo = _store.get(page, -1);
                // IE sends the full file path.
                storeAttachment(pageInfo, attachmentName, baseRevision, attachmentMessage,
                        FilenameUtils.getName(file.getName()), in);
                _store.expire(pageInfo);
                return new RedirectToPageView(_wikiUrls, page, "/attachments/");
            } finally {
                IOUtils.closeQuietly(in);
            }
        }
    } finally {
        for (FileItem item : items) {
            item.delete();
        }
    }
}

From source file:edu.umd.cs.submitServer.servlets.UploadTestSetup.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // TODO sanity checks on the format of the test setup
    MultipartRequest multipartRequest = (MultipartRequest) request.getAttribute(MULTIPART_REQUEST);
    Connection conn = null;/*from   w  w w .ja v  a  2  s .  co  m*/
    FileItem fileItem = null;
    boolean transactionSuccess = false;
    try {
        conn = getConnection();

        fileItem = multipartRequest.getFileItem();
        if (fileItem == null)
            throw new ServletException("fileItem is null; this is not good");

        Project project = (Project) request.getAttribute(PROJECT);
        // could be null
        String comment = multipartRequest.getOptionalCheckedParameter("comment");

        // get size in bytes
        long sizeInBytes = fileItem.getSize();
        if (sizeInBytes == 0) {
            throw new ServletException("Trying upload file of size 0");
        }

        // copy the fileItem into a byte array
        InputStream is = fileItem.getInputStream();
        ByteArrayOutputStream bytes = new ByteArrayOutputStream((int) sizeInBytes);
        IO.copyStream(is, bytes);

        byte[] byteArray = bytes.toByteArray();

        FormatDescription desc = FormatIdentification.identify(byteArray);
        if (desc == null || !desc.getMimeType().equals("application/zip")) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "You MUST submit test-setups that are either zipped or jarred");
            return;
        }
        Submission canonicalSubmission = Submission
                .lookupMostRecent(project.getCanonicalStudentRegistrationPK(), project.getProjectPK(), conn);
        // start transaction here
        conn.setAutoCommit(false);
        conn.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
        TestSetup.submit(byteArray, project, comment, conn);
        conn.commit();
        transactionSuccess = true;
        if (canonicalSubmission != null
                && canonicalSubmission.getBuildStatus() != Submission.BuildStatus.BROKEN) {
            WaitingBuildServer.offerSubmission(project, canonicalSubmission);
        }

        String redirectUrl = request.getContextPath() + "/view/instructor/projectUtilities.jsp?projectPK="
                + project.getProjectPK();
        response.sendRedirect(redirectUrl);

    } catch (SQLException e) {
        throw new ServletException(e);
    } finally {
        rollbackIfUnsuccessfulAndAlwaysReleaseConnection(transactionSuccess, request, conn);
        releaseConnection(conn);
        if (fileItem != null)
            fileItem.delete();
    }
}

From source file:com.blog.fckeditor.ConnectorServlet.java

/**
 * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br />
 * /* w w  w. java 2 s . 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.
 */
@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 {

                    // 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.zjl.oa.fckeditor.ConnectorServlet.java

/**
 * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br />
 * /*from w w w.j a  v a  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);
                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.laijie.fckeditor.ConnectorServlet.java

/**
 * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br />
 * //from   w  ww . j  a  v a  2 s.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.
 */
@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 {

                    // 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.wellmail.servlet.ConnectorServlet.java

/**
 * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br />
 * //from   w  w  w  . j  a va2 s. co  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.
 */
@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 />
 * /*from   w  w  w .  j  a va 2 s .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 www .  j a v  a  2 s.  co  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.
 */
@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:de.betterform.agent.web.servlet.HttpRequestHandler.java

protected void processUploadParameters(Map uploads, HttpServletRequest request) throws XFormsException {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("updating " + uploads.keySet().size() + " uploads(s)");
    }/*from w ww. j  av a  2  s.  c  o m*/

    try {
        // update repeat indices
        Iterator iterator = uploads.keySet().iterator();
        String id;
        FileItem item;
        byte[] data;

        while (iterator.hasNext()) {
            id = (String) iterator.next();
            item = (FileItem) uploads.get(id);

            if (item.getSize() > 0) {
                LOGGER.debug("i'm here");
                if (this.xformsProcessor.isFileUpload(id, "anyURI")) {
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("found upload type 'anyURI'");
                    }
                    String localPath = new StringBuffer().append(System.currentTimeMillis()).append('/')
                            .append(item.getName()).toString();

                    File localFile = new File(this.uploadRoot, localPath);
                    localFile.getParentFile().mkdirs();
                    item.write(localFile);

                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("saving data to path: " + localFile);
                    }

                    // todo: externalize file handling and uri generation

                    File uploadDir = new File(request.getContextPath(),
                            Config.getInstance().getProperty(WebFactory.UPLOADDIR_PROPERTY));
                    String urlEncodedPath = URLEncoder
                            .encode(new File(uploadDir.getPath(), localPath).getPath(), "UTF-8");
                    URI uploadTargetDir = new URI(urlEncodedPath);

                    data = uploadTargetDir.toString().getBytes();
                } else {
                    data = item.get();
                }

                this.xformsProcessor.setUploadValue(id, item.getContentType(), item.getName(), data);

                // After the value has been set and the RRR took place, create new UploadInfo with status set to 'done'
                request.getSession().setAttribute(WebProcessor.ADAPTER_PREFIX + sessionKey + "-uploadInfo",
                        new UploadInfo(1, 0, 0, 0, "done"));
            } else {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("ignoring empty upload " + id);
                }
                // todo: removal ?
            }

            item.delete();
        }
    } catch (Exception e) {
        throw new XFormsException(e);
    }
}

From source file:hu.sztaki.lpds.pgportal.services.asm.ASMService.java

/**
 * // www .  j  av a  2  s . co m
 * Uploads a file from the user's local machine to the *portal* server only. It won't store the file in the Storage
 * component of gUSE, and won't update database under WFS component
 * 
 * @param file
 *            - file to upload (can be get from the ActionRequest)
 * @param userID
 *            - ID of the user
 * @param filename
 *            - the file should be placed using this name
 * @return the uploaded file stored on the portal server
 * @throws Exception
 */
public File uploadFiletoPortalServer(FileItem file, String userID, String filename) throws Exception {
    // System.out.println("doUPLOADFiletoPortalServer called ...");

    File serverSideFile = null;
    try {
        String tempDir = System.getProperty("java.io.tmpdir") + "/uploads/" + userID;
        File f = new File(tempDir);
        if (!f.exists())
            f.mkdirs();
        serverSideFile = new File(tempDir, filename);
        file.write(serverSideFile);
        file.delete();

    } catch (FileUploadException fue) {
        // response.setRenderParameter("full", "error.upload");

        throw new Upload_ErrorDuringUploadException(fue.getCause(), userID);

        // context.log("[FileUploadPortlet] - failed to upload file - "+ fue.toString());

    } catch (Exception e) {

        // response.setRenderParameter("full", "error.exception");
        throw new Upload_GeneralException(e.getCause(), userID);
        // context.log("[FileUploadPortlet] - failed to upload file - "+ e.toString());

    }
    return serverSideFile;
}