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:edu.umd.cs.submitServer.servlets.UploadSubmission.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    long now = System.currentTimeMillis();
    Timestamp submissionTimestamp = new Timestamp(now);

    // these are set by filters or previous servlets
    Project project = (Project) request.getAttribute(PROJECT);
    StudentRegistration studentRegistration = (StudentRegistration) request.getAttribute(STUDENT_REGISTRATION);
    MultipartRequest multipartRequest = (MultipartRequest) request.getAttribute(MULTIPART_REQUEST);
    boolean webBasedUpload = ((Boolean) request.getAttribute("webBasedUpload")).booleanValue();
    String clientTool = multipartRequest.getCheckedParameter("submitClientTool");
    String clientVersion = multipartRequest.getOptionalCheckedParameter("submitClientVersion");
    String cvsTimestamp = multipartRequest.getOptionalCheckedParameter("cvstagTimestamp");

    Collection<FileItem> files = multipartRequest.getFileItems();
    Kind kind;/*from w ww.j  av a 2  s  . co m*/

    byte[] zipOutput = null; // zipped version of bytesForUpload
    boolean fixedZip = false;
    try {

        if (files.size() > 1) {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ZipOutputStream zos = new ZipOutputStream(bos);
            for (FileItem item : files) {
                String name = item.getName();
                if (name == null || name.length() == 0)
                    continue;
                byte[] bytes = item.get();
                ZipEntry zentry = new ZipEntry(name);
                zentry.setSize(bytes.length);
                zentry.setTime(now);
                zos.putNextEntry(zentry);
                zos.write(bytes);
                zos.closeEntry();
            }
            zos.flush();
            zos.close();
            zipOutput = bos.toByteArray();
            kind = Kind.MULTIFILE_UPLOAD;

        } else {
            FileItem fileItem = multipartRequest.getFileItem();
            if (fileItem == null) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "There was a problem processing your submission. "
                                + "No files were found in your submission");
                return;
            }
            // get size in bytes
            long sizeInBytes = fileItem.getSize();
            if (sizeInBytes == 0 || sizeInBytes > Integer.MAX_VALUE) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Trying upload file of size " + sizeInBytes);
                return;
            }

            // copy the fileItem into a byte array
            byte[] bytesForUpload = fileItem.get();
            String fileName = fileItem.getName();

            boolean isSpecialSingleFile = OfficeFileName.matcher(fileName).matches();

            FormatDescription desc = FormatIdentification.identify(bytesForUpload);
            if (!isSpecialSingleFile && desc != null && desc.getMimeType().equals("application/zip")) {
                fixedZip = FixZip.hasProblem(bytesForUpload);
                kind = Kind.ZIP_UPLOAD;
                if (fixedZip) {
                    bytesForUpload = FixZip.fixProblem(bytesForUpload,
                            studentRegistration.getStudentRegistrationPK());
                    kind = Kind.FIXED_ZIP_UPLOAD;
                }
                zipOutput = bytesForUpload;

            } else {

                // ==========================================================================================
                // [NAT] [Buffer to ZIP Part]
                // Check the type of the upload and convert to zip format if
                // possible
                // NOTE: I use both MagicMatch and FormatDescription (above)
                // because MagicMatch was having
                // some trouble identifying all zips

                String mime = URLConnection.getFileNameMap().getContentTypeFor(fileName);

                if (!isSpecialSingleFile && mime == null)
                    try {
                        MagicMatch match = Magic.getMagicMatch(bytesForUpload, true);
                        if (match != null)
                            mime = match.getMimeType();
                    } catch (Exception e) {
                        // leave mime as null
                    }

                if (!isSpecialSingleFile && "application/zip".equalsIgnoreCase(mime)) {
                    zipOutput = bytesForUpload;
                    kind = Kind.ZIP_UPLOAD2;
                } else {
                    InputStream ins = new ByteArrayInputStream(bytesForUpload);
                    if ("application/x-gzip".equalsIgnoreCase(mime)) {
                        ins = new GZIPInputStream(ins);
                    }

                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    ZipOutputStream zos = new ZipOutputStream(bos);

                    if (!isSpecialSingleFile && ("application/x-gzip".equalsIgnoreCase(mime)
                            || "application/x-tar".equalsIgnoreCase(mime))) {

                        kind = Kind.TAR_UPLOAD;

                        TarInputStream tins = new TarInputStream(ins);
                        TarEntry tarEntry = null;
                        while ((tarEntry = tins.getNextEntry()) != null) {
                            zos.putNextEntry(new ZipEntry(tarEntry.getName()));
                            tins.copyEntryContents(zos);
                            zos.closeEntry();
                        }
                        tins.close();
                    } else {
                        // Non-archive file type
                        if (isSpecialSingleFile)
                            kind = Kind.SPECIAL_ZIP_FILE;
                        else
                            kind = Kind.SINGLE_FILE;
                        // Write bytes to a zip file
                        ZipEntry zentry = new ZipEntry(fileName);
                        zos.putNextEntry(zentry);
                        zos.write(bytesForUpload);
                        zos.closeEntry();
                    }
                    zos.flush();
                    zos.close();
                    zipOutput = bos.toByteArray();
                }

                // [END Buffer to ZIP Part]
                // ==========================================================================================

            }
        }

    } catch (NullPointerException e) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                "There was a problem processing your submission. "
                        + "You should submit files that are either zipped or jarred");
        return;
    } finally {
        for (FileItem fItem : files)
            fItem.delete();
    }

    if (webBasedUpload) {
        clientTool = "web";
        clientVersion = kind.toString();
    }

    Submission submission = uploadSubmission(project, studentRegistration, zipOutput, request,
            submissionTimestamp, clientTool, clientVersion, cvsTimestamp, getDatabaseProps(),
            getSubmitServerServletLog());

    request.setAttribute("submission", submission);

    if (!webBasedUpload) {

        response.setContentType("text/plain");
        PrintWriter out = response.getWriter();
        out.println("Successful submission #" + submission.getSubmissionNumber() + " received for project "
                + project.getProjectNumber());

        out.flush();
        out.close();
        return;
    }
    boolean instructorUpload = ((Boolean) request.getAttribute("instructorViewOfStudent")).booleanValue();
    // boolean
    // isCanonicalSubmission="true".equals(request.getParameter("isCanonicalSubmission"));
    // set the successful submission as a request attribute
    String redirectUrl;

    if (fixedZip) {
        redirectUrl = request.getContextPath() + "/view/fixedSubmissionUpload.jsp?submissionPK="
                + submission.getSubmissionPK();
    }
    if (project.getCanonicalStudentRegistrationPK() == studentRegistration.getStudentRegistrationPK()) {
        redirectUrl = request.getContextPath() + "/view/instructor/projectUtilities.jsp?projectPK="
                + project.getProjectPK();
    } else if (instructorUpload) {
        redirectUrl = request.getContextPath() + "/view/instructor/project.jsp?projectPK="
                + project.getProjectPK();
    } else {
        redirectUrl = request.getContextPath() + "/view/project.jsp?projectPK=" + project.getProjectPK();
    }

    response.sendRedirect(redirectUrl);

}

From source file:com.adanac.module.blog.servlet.UploadImage.java

@Override
protected void service() throws ServletException, IOException {
    HttpServletRequest request = getRequest();
    String path = null;//from   w  w  w .  j av a 2  s . c o m
    DiskFileItemFactory factory = new DiskFileItemFactory(5 * 1024,
            new File(Configuration.getContextPath("temp")));
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(3 * 1024 * 1024);
    try {
        List<FileItem> items = upload.parseRequest(request);
        FileItem fileItem = null;
        if (items != null && items.size() > 0 && StringUtils.isNotBlank((fileItem = items.get(0)).getName())) {
            String fileName = fileItem.getName();
            if (!fileName.endsWith(".jpg") && !fileName.endsWith(".gif") && !fileName.endsWith(".png")) {
                writeText("format_error");
                return;
            }
            path = ImageUtil.generatePath(fileItem.getName());
            IOUtil.copy(fileItem.getInputStream(), Configuration.getContextPath(path));
            fileItem.delete();
            writeText(Configuration.getSiteUrl(path));
        }
    } catch (FileUploadException e) {
        throw new RuntimeException(e);
    }
}

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

/**
 * @param multipartRequest//from  w  w  w  .  j av a  2s .  co  m
 * @return
 */
private byte[] getfileItemDataAndDelete(MultipartRequest multipartRequest) {
    // Get the fileItem
    FileItem fileItem = multipartRequest.getFileItem();
    byte[] data = fileItem.get();
    fileItem.delete();
    return data;
}

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

/**
 * The doPost method of the servlet. <br>
 *
 * This method is called when a form has its tag value method equals to
 * post.//from   w  ww  .jav  a 2 s  .c  o m
 *
 * @param request
 *            the request send by the client to the server
 * @param response
 *            the response send by the server to the client
 * @throws ServletException
 *             if an error occurred
 * @throws IOException
 *             if an error occurred
 */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    MultipartRequest multipartRequest = (MultipartRequest) request.getAttribute(MULTIPART_REQUEST);
    FileItem fileItem = null;
    LoggingEvent loggingEvent = null;
    ObjectInputStream in = null;
    try {
        fileItem = multipartRequest.getFileItem();
        byte[] data = fileItem.get();

        in = new ObjectInputStream(new ByteArrayInputStream(data));
        loggingEvent = (LoggingEvent) in.readObject();

        buildServerLogger.callAppenders(loggingEvent);
    } catch (ClassNotFoundException e) {
        throw new ServletException("Cannot find class: " + e.getMessage(), e);
    } finally {
        if (fileItem != null)
            fileItem.delete();
        if (in != null)
            in.close();
    }
}

From source file:fr.paris.lutece.portal.web.upload.UploadServlet.java

/**
 * {@inheritDoc}//from  w ww.  j  a va 2  s  . c o  m
 */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse response)
        throws ServletException, IOException {
    MultipartHttpServletRequest request = (MultipartHttpServletRequest) req;

    List<FileItem> listFileItems = new ArrayList<FileItem>();
    JSONObject json = new JSONObject();
    json.element(JSON_FILES, new JSONArray());

    for (Entry<String, FileItem> entry : ((Map<String, FileItem>) request.getFileMap()).entrySet()) {
        FileItem fileItem = entry.getValue();

        JSONObject jsonFile = new JSONObject();
        jsonFile.element(JSON_FILE_NAME, fileItem.getName());
        jsonFile.element(JSON_FILE_SIZE, fileItem.getSize());

        // add to existing array
        json.accumulate(JSON_FILES, jsonFile);

        listFileItems.add(fileItem);
    }

    IAsynchronousUploadHandler handler = getHandler(request);

    if (handler == null) {
        AppLogService.error("No handler found, removing temporary files");

        for (FileItem fileItem : listFileItems) {
            fileItem.delete();
        }
    } else {
        handler.process(request, response, json, listFileItems);
    }

    if (AppLogService.isDebugEnabled()) {
        AppLogService.debug("Aysnchronous upload : " + json.toString());
    }

    response.getOutputStream().print(json.toString());
}

From source file:com.adobe.epubcheck.web.EpubCheckServlet.java

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("text/plain");
    PrintWriter out = resp.getWriter();
    if (!ServletFileUpload.isMultipartContent(req)) {
        out.println("Invalid request type");
        return;/*from   w ww.  j av a  2s.c  o  m*/
    }
    try {
        DiskFileItemFactory itemFac = new DiskFileItemFactory();
        // itemFac.setSizeThreshold(20000000); // bytes
        File repositoryPath = new File("upload");
        repositoryPath.mkdir();
        itemFac.setRepository(repositoryPath);
        ServletFileUpload servletFileUpload = new ServletFileUpload(itemFac);
        List fileItemList = servletFileUpload.parseRequest(req);
        Iterator list = fileItemList.iterator();
        FileItem book = null;
        while (list.hasNext()) {
            FileItem item = (FileItem) list.next();
            String paramName = item.getFieldName();
            if (paramName.equals("file"))
                book = item;
        }
        if (book == null) {
            out.println("Invalid request: no epub uploaded");
            return;
        }
        File bookFile = File.createTempFile("work", "epub");
        book.write(bookFile);
        EpubCheck epubCheck = new EpubCheck(bookFile, out);
        if (epubCheck.validate())
            out.println("No errors or warnings detected");
        book.delete();
    } catch (Exception e) {
        out.println("Internal Server Error");
        e.printStackTrace(out);
    }
}

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

public void cleanUp() {
    Set<String> names = files.keySet();
    for (String name : names) {
        List<FileItem> items = files.get(name);
        for (FileItem item : items) {
            if (LOG.isDebugEnabled()) {
                String msg = LocalizedTextUtil.findText(this.getClass(), "struts.messages.removing.file",
                        Locale.ENGLISH, "no.message.found", new Object[] { name, item });
                LOG.debug(msg);/*from   w  w w  . j  a  v a 2s .c o  m*/
            }
            if (!item.isInMemory()) {
                item.delete();
            }
        }
    }
}

From source file:com.es.keyassistant.resolvers.Resolver0004.java

@Override
public ServiceResult execute() throws Exception {
    File dir = new File(getRequest().getServletContext().getRealPath(TMP_PATH));
    dir.mkdirs();/*from   ww  w.j  av  a 2 s  . c om*/

    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(5 * 1024);
    factory.setRepository(dir);
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("UTF-8");
    upload.setSizeMax(5 * 1024 * 1024);
    List<FileItem> formItems = upload.parseRequest(getRequest());

    DetectionInfo info = new DetectionInfo();
    assignPropertiesTo(formItems, info);

    for (FileItem formItem : formItems) {
        if (!formItem.isFormField()) {
            String fileName = formItem.getName();
            String targetFileName = generateDectionFileName(fileName, info);
            info.setDetectionFileName(targetFileName);
            info.setDetectionFilePath(String.format("%s/%s", STORE_PATH, targetFileName));

            File storeDir = new File(getRequest().getServletContext().getRealPath(STORE_PATH));
            storeDir.mkdirs();
            File detectionFile = new File(storeDir, targetFileName);

            formItem.write(detectionFile);

            formItem.delete();
            break;
        }
    }

    if (info.getDetectionSN() == null) {
        throw new ClientException(ClientException.REQUEST_ERROR, "");
    }

    ContentService service = new ContentService();
    if (service.addDetectionInfo(info) < 0) {
        throw new ClientException(ClientException.REQUEST_ERROR, "??");
    }

    ServiceResult result = new ServiceResult();
    result.getData().add(makeMapByKeyAndValues("receiptNumber", info.getDetectionSN()));

    return result;
}

From source file:hudson.PluginManager.java

/**
 * Uploads a plugin./* w  ww .j a  v  a2  s .c  o  m*/
 */
public HttpResponse doUploadPlugin(StaplerRequest req) throws IOException, ServletException {
    try {
        Hudson.getInstance().checkPermission(Hudson.ADMINISTER);

        ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());

        // Parse the request
        FileItem fileItem = (FileItem) upload.parseRequest(req).get(0);
        String fileName = Util.getFileName(fileItem.getName());
        if (!fileName.endsWith(".hpi"))
            throw new Failure(hudson.model.Messages.Hudson_NotAPlugin(fileName));
        fileItem.write(new File(rootDir, fileName));
        fileItem.delete();

        pluginUploaded = true;

        return new HttpRedirect(".");
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {// grrr. fileItem.write throws this
        throw new ServletException(e);
    }
}

From source file:filter.MultipartRequestFilter.java

/**
 * Process multipart request item as file field. The name and FileItem object of each file field
 * will be added as attribute of the given HttpServletRequest. If a FileUploadException has
 * occurred when the file size has exceeded the maximum file size, then the FileUploadException
 * will be added as attribute value instead of the FileItem object.
 * @param fileField The file field to be processed.
 * @param request The involved HttpServletRequest.
 *//*  ww  w. ja  va2 s.com*/
private void processFileField(FileItem fileField, HttpServletRequest request) {
    if (fileField.getName().length() <= 0) {
        // No file uploaded.
        addAttributeValue(request, fileField.getFieldName(), null);
    } else if (maxFileSize > 0 && fileField.getSize() > maxFileSize) {
        // File size exceeds maximum file size.
        addAttributeValue(request, fileField.getFieldName(),
                new FileUploadException("File size exceeds maximum file size of " + maxFileSize + " bytes."));
        // Immediately delete temporary file to free up memory and/or disk space.
        fileField.delete();
    } else {
        // File uploaded with good size.
        addAttributeValue(request, fileField.getFieldName(), fileField);
    }
}