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:com.skin.taurus.http.servlet.UploadServlet.java

public void upload(HttpRequest request, HttpResponse response) throws IOException {
    int maxFileSize = 1024 * 1024;
    String repository = System.getProperty("java.io.tmpdir");
    DiskFileItemFactory factory = new DiskFileItemFactory();

    factory.setRepository(new File(repository));
    factory.setSizeThreshold(maxFileSize * 2);
    ServletFileUpload servletFileUpload = new ServletFileUpload(factory);

    servletFileUpload.setFileSizeMax(maxFileSize);
    servletFileUpload.setSizeMax(maxFileSize);

    try {//from   w ww  .  j a  va 2 s  .  c  om
        HttpServletRequest httpRequest = new HttpServletRequestAdapter(request);
        List<?> list = servletFileUpload.parseRequest(httpRequest);

        for (Iterator<?> iterator = list.iterator(); iterator.hasNext();) {
            FileItem item = (FileItem) iterator.next();

            if (item.isFormField()) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Form Field: " + item.getFieldName() + " " + item.toString());
                }
            } else if (!item.isFormField()) {
                if (item.getFieldName() != null) {
                    String fileName = this.getFileName(item.getName());
                    String extension = this.getFileExtensionName(fileName);

                    if (this.isAllowed(extension)) {
                        try {
                            this.save(item);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    item.delete();
                } else {
                    item.delete();
                }
            }
        }
    } catch (FileUploadException e) {
        e.printStackTrace();
    }
}

From source file:com.zimbra.cs.service.FileUploadServlet.java

public static Upload saveUpload(InputStream is, String filename, String contentType, String accountId,
        long limit) throws ServiceException, IOException {
    FileItem fi = null;
    boolean success = false;
    try {/*from  w w w. jav a 2 s  .c om*/
        // store the fetched file as a normal upload
        ServletFileUpload upload = getUploader(limit);
        long sizeMax = upload.getSizeMax();
        fi = upload.getFileItemFactory().createItem("upload", contentType, false, filename);
        // sizeMax=-1 means "no limit"
        long size = ByteUtil.copy(is, true, fi.getOutputStream(), true, sizeMax < 0 ? sizeMax : sizeMax + 1);
        if (upload.getSizeMax() >= 0 && size > upload.getSizeMax()) {
            mLog.info("Exceeded maximum upload size of " + upload.getSizeMax() + " bytes");
            throw MailServiceException.UPLOAD_TOO_LARGE(filename, "upload too large");
        }

        Upload up = new Upload(accountId, fi);
        mLog.info("saveUpload(): received %s", up);
        synchronized (mPending) {
            mPending.put(up.uuid, up);
        }
        success = true;
        return up;
    } finally {
        if (!success && fi != null) {
            mLog.debug("saveUpload(): unsuccessful attempt.  Deleting %s", fi);
            fi.delete();
        }
    }
}

From source file:com.ait.tooling.server.core.servlet.FileUploadServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.info("STARTING UPLOAD");

    try {/*from   w w w .j ava 2s  .co m*/
        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();

        ServletFileUpload fileUpload = new ServletFileUpload(fileItemFactory);

        fileUpload.setSizeMax(FILE_SIZE_LIMIT);

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

        for (FileItem item : items) {
            if (item.isFormField()) {
                logger.info("Received form field");

                logger.info("Name: " + item.getFieldName());

                logger.info("Value: " + item.getString());
            } else {
                logger.info("Received file");

                logger.info("Name: " + item.getName());

                logger.info("Size: " + item.getSize());
            }
            if (false == item.isFormField()) {
                if (item.getSize() > FILE_SIZE_LIMIT) {
                    response.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE,
                            "File size exceeds limit");

                    return;
                }
                // Typically here you would process the file in some way:
                // InputStream in = item.getInputStream();
                // ...

                if (false == item.isInMemory()) {
                    item.delete();
                }
            }
        }
    } catch (Exception e) {
        logger.error("Throwing servlet exception for unhandled exception", e);

        throw new ServletException(e);
    }
}

From source file:com.alkacon.opencms.excelimport.CmsResourceExcelImport.java

/**
 * Sets content from uploaded file.<p>
 * //w w  w  .  j  a  v a 2 s .  co  m
 * @param content the parameter value is only necessary for calling this method
 */
public void setParamExcelContent(String content) {

    // use parameter value
    if (content == null) {
        // do nothing   
    }

    // get the file item from the multipart request
    if (getMultiPartFileItems() != null) {
        Iterator i = getMultiPartFileItems().iterator();
        FileItem fi = null;
        while (i.hasNext()) {
            fi = (FileItem) i.next();
            if (fi.getFieldName().equals(PARAM_EXCEL_FILE)) {
                // found the file objectif (fi != null) {
                long size = fi.getSize();
                long maxFileSizeBytes = OpenCms.getWorkplaceManager().getFileBytesMaxUploadSize(getCms());
                // check file size
                if ((maxFileSizeBytes > 0) && (size > maxFileSizeBytes)) {
                    // file size is larger than maximum allowed file size, throw an error
                    //throw new CmsWorkplaceException();
                }
                m_excelContent = fi.get();
                m_excelName = fi.getName();
                fi.delete();
            } else {
                continue;
            }
        }
    }
}

From source file:com.hrhih.dispatcher.HrhihJakartaMultiPartRequest.java

private void processNormalFormField(FileItem item, String charset) throws UnsupportedEncodingException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Item is a normal form field");
    }/*  ww  w  . j  a va2 s.co  m*/
    List<String> values;
    if (params.get(item.getFieldName()) != null) {
        values = params.get(item.getFieldName());
    } else {
        values = new ArrayList<String>();
    }

    // note: see http://jira.opensymphony.com/browse/WW-633
    // basically, in some cases the charset may be null, so
    // we're just going to try to "other" method (no idea if this
    // will work)
    if (charset != null) {
        values.add(item.getString(charset));
    } else {
        values.add(item.getString());
    }
    params.put(item.getFieldName(), values);
    item.delete();
}

From source file:com.openmeap.admin.web.backing.AddModifyApplicationVersionBacking.java

private void fillInApplicationVersionFromParameters(Application app, ApplicationVersion version,
        List<ProcessingEvent> events, Map<Object, Object> parameterMap) {

    version.setIdentifier(firstValue("identifier", parameterMap));
    if (version.getArchive() == null) {
        version.setArchive(new ApplicationArchive());
        version.getArchive().setApplication(app);
    }/*w ww  . j a v a 2  s  . c o  m*/

    version.setApplication(app);

    version.setNotes(firstValue("notes", parameterMap));

    Boolean archiveUncreated = true;

    // if there was an uploadArchive, then attempt to auto-assemble the rest of parameters
    if (parameterMap.get("uploadArchive") != null) {

        if (!(parameterMap.get("uploadArchive") instanceof FileItem)) {

            events.add(new MessagesEvent(
                    "Uploaded file not processed!  Is the archive storage path set in settings?"));
        } else {

            FileItem item = (FileItem) parameterMap.get("uploadArchive");
            Long size = item.getSize();

            if (size > 0) {

                try {

                    File tempFile = ServletUtils.tempFileFromFileItem(
                            modelManager.getGlobalSettings().getTemporaryStoragePath(), item);
                    ApplicationArchive archive = version.getArchive();
                    archive.setNewFileUploaded(tempFile.getAbsolutePath());
                    archiveUncreated = false;
                } catch (Exception ioe) {

                    logger.error("An error transpired creating an uploadArchive temp file: {}", ioe);
                    events.add(new MessagesEvent(ioe.getMessage()));
                    return;
                } finally {
                    item.delete();
                }
            } else {

                events.add(new MessagesEvent(
                        "Uploaded file not processed!  Is the archive storage path set in settings?"));
            }
        }
    }

    // else there was no zip archive uploaded
    if (archiveUncreated) {
        ApplicationArchive archive = version.getArchive();
        archive.setHashAlgorithm(firstValue("hashType", parameterMap));
        archive.setHash(firstValue("hash", parameterMap));
        ApplicationArchive arch = modelManager.getModelService().findApplicationArchiveByHashAndAlgorithm(app,
                archive.getHash(), archive.getHashAlgorithm());
        if (arch != null) {
            version.setArchive(arch);
            archive = arch;
        }
        archive.setUrl(firstValue("url", parameterMap));
        if (notEmpty("bytesLength", parameterMap)) {
            archive.setBytesLength(Integer.valueOf(firstValue("bytesLength", parameterMap)));
        }
        if (notEmpty("bytesLengthUncompressed", parameterMap)) {
            archive.setBytesLengthUncompressed(
                    Integer.valueOf(firstValue("bytesLengthUncompressed", parameterMap)));
        }
    }
}

From source file:eu.stratuslab.storage.disk.resources.DisksResource.java

protected Disk inflateAndProcessImage(FileItem fi) {

    File cachedDiskFile = null;//  w  ww .  java  2 s . c  o m

    try {

        Disk disk = initializeDisk();

        cachedDiskFile = FileUtils.getCachedDiskFile(disk.getUuid());

        try {
            long size = inflateFile(fi.getInputStream(), cachedDiskFile);
            disk.setSize(size);
        } catch (IOException e) {
            throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "no valid file uploaded");
        }

        try {
            disk.setIdentifier(DiskUtils.calculateHash(cachedDiskFile));
        } catch (FileNotFoundException e) {
            throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, e.getMessage());
        }
        validateNewDisk(disk);
        return disk;

    } catch (RuntimeException e) {
        if (cachedDiskFile != null) {
            if (!cachedDiskFile.delete()) {
                getLogger().warning("could not delete file: " + cachedDiskFile.getAbsolutePath());
            }
        }
        throw e;
    } finally {
        fi.delete();
    }
}

From source file:com.zimbra.cs.service.FileUploadServlet.java

/**
 * This is used when handling a POST request generated by {@link ZMailbox#uploadContentAsStream}
 *
 * @param req/*  ww  w .  j av a 2s  . c om*/
 * @param resp
 * @param fmt
 * @param acct
 * @param limitByFileUploadMaxSize
 * @return
 * @throws IOException
 * @throws ServiceException
 */
List<Upload> handlePlainUpload(HttpServletRequest req, HttpServletResponse resp, String fmt, Account acct,
        boolean limitByFileUploadMaxSize) throws IOException, ServiceException {
    // metadata is encoded in the response's HTTP headers
    ContentType ctype = new ContentType(req.getContentType());
    String contentType = ctype.getContentType(), filename = ctype.getParameter("name");
    if (filename == null) {
        filename = new ContentDisposition(req.getHeader("Content-Disposition")).getParameter("filename");
    }

    if (filename == null || filename.trim().equals("")) {
        mLog.info("Rejecting upload with no name.");
        drainRequestStream(req);
        sendResponse(resp, HttpServletResponse.SC_NO_CONTENT, fmt, null, null, null);
        return Collections.emptyList();
    }

    // Unescape the filename so it actually displays correctly
    filename = StringEscapeUtils.unescapeHtml(filename);

    // store the fetched file as a normal upload
    ServletFileUpload upload = getUploader2(limitByFileUploadMaxSize);
    FileItem fi = upload.getFileItemFactory().createItem("upload", contentType, false, filename);
    try {
        // write the upload to disk, but make sure not to exceed the permitted max upload size
        long size = ByteUtil.copy(req.getInputStream(), false, fi.getOutputStream(), true,
                upload.getSizeMax() * 3);
        if ((upload.getSizeMax() >= 0 /* -1 would mean "no limit" */) && (size > upload.getSizeMax())) {
            mLog.debug("handlePlainUpload(): deleting %s", fi);
            fi.delete();
            mLog.info("Exceeded maximum upload size of " + upload.getSizeMax() + " bytes: " + acct.getId());
            drainRequestStream(req);
            sendResponse(resp, HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, fmt, null, null, null);
            return Collections.emptyList();
        }
    } catch (IOException ioe) {
        mLog.warn("Unable to store upload.  Deleting %s", fi, ioe);
        fi.delete();
        drainRequestStream(req);
        sendResponse(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, fmt, null, null, null);
        return Collections.emptyList();
    }
    List<FileItem> items = new ArrayList<FileItem>(1);
    items.add(fi);

    Upload up = new Upload(acct.getId(), fi, filename);
    mLog.info("Received plain: %s", up);
    synchronized (mPending) {
        mPending.put(up.uuid, up);
    }

    List<Upload> uploads = Arrays.asList(up);
    sendResponse(resp, HttpServletResponse.SC_OK, fmt, null, uploads, items);
    return uploads;
}

From source file:com.meetme.plugins.jira.gerrit.adminui.AdminServlet.java

private File doUploadPrivateKey(final List<FileItem> items, final String sshHostname) throws IOException {
    File privateKeyPath = null;/*  w ww.  j a  v a  2  s  . c o  m*/

    for (FileItem item : items) {
        if (item.getFieldName().equals(GerritConfiguration.FIELD_SSH_PRIVATE_KEY) && item.getSize() > 0) {
            File dataDir = new File(jiraHome.getDataDirectory(),
                    StringUtils.join(PACKAGE_PARTS, File.separatorChar));

            if (!dataDir.exists()) {
                dataDir.mkdirs();
            }

            String tempFilePrefix = configurationManager.getSshHostname();
            String tempFileSuffix = ".key";

            try {
                privateKeyPath = File.createTempFile(tempFilePrefix, tempFileSuffix, dataDir);
            } catch (IOException e) {
                log.info("---- Cannot create temporary file: " + e.getMessage() + ": " + dataDir.toString()
                        + tempFilePrefix + tempFileSuffix + " ----");
                break;
            }

            privateKeyPath.setReadable(false, false);
            privateKeyPath.setReadable(true, true);

            InputStream is = item.getInputStream();
            FileOutputStream fos = new FileOutputStream(privateKeyPath);
            IOUtils.copy(is, fos);
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(fos);

            item.delete();
            break;
        }
    }

    return privateKeyPath;
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.harvester.FileHarvestController.java

/**
 * This is for when the user clicks the "Upload" button on the form, sending a file to the server.  An HTTP post is
 * redirected here when it is determined that the request was multipart (as this will identify the post as a file
 * upload click)./*from  www  . ja v  a2  s  .c o m*/
 * @param request the HTTP request
 * @param response the HTTP response
 * @throws IOException if an IO error occurs
 * @throws ServletException if a servlet error occurs
 */
private void doFileUploadPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    JSONObject json = generateJson(false);
    try {
        VitroRequest vreq = new VitroRequest(request);

        //parse request for uploaded file
        int maxFileSize = 1024 * 1024;
        FileUploadServletRequest req = FileUploadServletRequest.parseRequest(vreq, maxFileSize);
        if (req.hasFileUploadException()) {
            Exception e = req.getFileUploadException();
            new ExceptionVisibleToUser(e);
        }

        //get the job parameter
        String jobParameter = req.getParameter(PARAMETER_JOB);

        //get the location where we want to save the files (it will end in a slash), then create a File object out of it
        String path = getUploadPath(vreq);
        File directory = new File(path);

        //if this is a page refresh, we do not want to save stale files that the user doesn't want anymore, but we
        //  still have the same session ID and therefore the upload directory is unchanged.  Thus we must clear the
        //  upload directory if it exists (a "first upload" parameter, initialized to "true" but which gets set to
        //  "false" once the user starts uploading stuff is used for this).
        String firstUpload = req.getParameter(PARAMETER_FIRST_UPLOAD); //clear directory on first upload
        if (firstUpload.toLowerCase().equals("true")) {
            if (directory.exists()) {
                File[] children = directory.listFiles();
                for (File child : children) {
                    child.delete();
                }
            }
        }

        //if the upload directory does not exist then create it
        if (!directory.exists())
            directory.mkdirs();

        //get the file harvest job for this request (this will determine what type of harvest is run)
        FileHarvestJob job = getJob(vreq, jobParameter);

        //get the files out of the parsed request (there should only be one)
        Map<String, List<FileItem>> fileStreams = req.getFiles();
        if (fileStreams.get(PARAMETER_UPLOADED_FILE) != null
                && fileStreams.get(PARAMETER_UPLOADED_FILE).size() > 0) {

            //get the individual file data from the request
            FileItem csvStream = fileStreams.get(PARAMETER_UPLOADED_FILE).get(0);
            String name = csvStream.getName();

            //if another uploaded file exists with the same name, alter the name so that it is unique
            name = handleNameCollision(name, directory);

            //write the file from the request to the upload directory
            File file = new File(path + name);
            try {
                csvStream.write(file);
            } finally {
                csvStream.delete();
            }

            //ask the file harvest job to validate that it's okay with what was uploaded; if not delete the file
            String errorMessage = job.validateUpload(file);
            boolean success;
            if (errorMessage != null) {
                success = false;
                file.delete();
            } else {
                success = true;
                errorMessage = "success";
            }

            //prepare the results which will be sent back to the browser for display
            try {
                json.put("success", success);
                json.put("fileName", name);
                json.put("errorMessage", errorMessage);
            } catch (JSONException e) {
                log.error(e, e);
                return;
            }

        } else {

            //if for some reason no file was included with the request, send an error back
            try {
                json.put("success", false);
                json.put("fileName", "(none)");
                json.put("errorMessage", "No file uploaded");
            } catch (JSONException e) {
                log.error(e, e);
                return;
            }

        }
    } catch (ExceptionVisibleToUser e) {
        log.error(e, e);

        //handle exceptions whose message is for the user
        try {
            json.put("success", false);
            json.put("filename", "(none)");
            json.put("errorMessage", e.getMessage());
        } catch (JSONException f) {
            log.error(f, f);
            return;
        }
    } catch (Exception e) {
        log.error(e, e);
        json = generateJson(true);
    }

    //write the prepared response
    response.getWriter().write(json.toString());
}