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:se.unlogic.fileuploadutils.SafeDiskFileItemFactory.java

public void deleteFiles() {
    if (!this.itemList.isEmpty()) {

        Iterator<FileItem> iterator = this.itemList.iterator();

        while (iterator.hasNext()) {
            FileItem item = iterator.next();
            item.delete();
            iterator.remove();/*  w  w  w .  j a  v a  2 s.c o  m*/
        }
    }
}

From source file:servlets.File_servlets.java

private void add_new_file_handler(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {/*from www .  j a  v  a  2 s.c  om*/
        DAO daoInstance;
        File uploadedFile;
        Experiment experiment;
        String parent_dir;
        String file_name;

        try {

            if (!ServletFileUpload.isMultipartContent(request)) {
                throw new Exception("Erroneus request.");
            }

            /**
             * *******************************************************
             * STEP 1 CHECK IF THE USER IS LOGGED CORRECTLY IN THE APP. IF
             * ERROR --> throws exception if not valid session, GO TO STEP
             * 5b ELSE --> GO TO STEP 2
             * *******************************************************
             */
            Map<String, Cookie> cookies = this.getCookies(request);

            String loggedUser, loggedUserID = null, sessionToken;
            if (cookies != null) {
                loggedUser = cookies.get("loggedUser").getValue();
                sessionToken = cookies.get("sessionToken").getValue();
                loggedUserID = cookies.get("loggedUserID").getValue();
            } else {
                String apicode = request.getParameter("apicode");
                apicode = new String(Base64.decodeBase64(apicode));

                loggedUser = apicode.split(":")[0];
                sessionToken = apicode.split(":")[1];
            }

            if (!checkAccessPermissions(loggedUser, sessionToken)) {
                throw new AccessControlException("Your session is invalid. User or session token not allowed.");
            }

            if (loggedUserID == null) {
                daoInstance = DAOProvider.getDAOByName("User");
                loggedUserID = ((User) daoInstance.findByID(loggedUser, new Object[] { null, false, true }))
                        .getUserID();
            }

            /**
             * *******************************************************
             * STEP 2 Get the Experiment Object from DB. IF ERROR --> throws
             * MySQL exception, GO TO STEP 3b ELSE --> GO TO STEP 3
             * *******************************************************
             */
            String experiment_id;
            if (request.getParameter("experiment_id") != null) {
                experiment_id = request.getParameter("experiment_id");
            } else {
                experiment_id = cookies.get("currentExperimentID").getValue();
            }

            parent_dir = "";
            if (request.getParameter("parent_dir") != null) {
                parent_dir = request.getParameter("parent_dir");
            }

            file_name = "";
            if (request.getParameter("file_name") != null) {
                file_name = request.getParameter("file_name");
            }
            /**
             * *******************************************************
             * STEP 3 Check that the user is a valid owner for the
             * experiment.
             * *******************************************************
             */
            daoInstance = DAOProvider.getDAOByName("Experiment");
            experiment = (Experiment) daoInstance.findByID(experiment_id, null);

            if (!experiment.isOwner(loggedUserID) && !experiment.isMember(loggedUserID)
                    && !isValidAdminUser(loggedUser)) {
                throw new AccessControlException(
                        "Cannot add files to selected study. Current user is not a valid member for study "
                                + experiment_id + ".");
            }

            /**
             * *******************************************************
             * STEP 4 Read the uploaded file and store in a temporal dir.
             * *******************************************************
             */
            FileItem tmpUploadedFile = null;
            final String CACHE_PATH = "/tmp/";
            final int CACHE_SIZE = 500 * (int) Math.pow(10, 6);
            final int MAX_REQUEST_SIZE = 600 * (int) Math.pow(10, 6);
            final int MAX_FILE_SIZE = 500 * (int) Math.pow(10, 6); //TODO: READ FROM SETTINGS

            // Create a factory for disk-based file items
            DiskFileItemFactory factory = new DiskFileItemFactory();
            // Set factory constraints
            factory.setRepository(new File(CACHE_PATH));
            factory.setSizeThreshold(CACHE_SIZE);

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // Set overall request size constraint
            upload.setSizeMax(MAX_REQUEST_SIZE);
            upload.setFileSizeMax(MAX_FILE_SIZE);

            // Parse the request
            List<FileItem> items = upload.parseRequest(request);
            for (FileItem item : items) {
                if (!item.isFormField()) {
                    if (!item.getName().equals("")) {
                        tmpUploadedFile = item;
                    }
                }
            }

            if (tmpUploadedFile == null) {
                throw new Exception("The file was not uploaded correctly.");
            }

            /**
             * *******************************************************
             * STEP 5 SAVE THE FILE IN THE SERVER.
             * *******************************************************
             */
            //First check if the file already exists -> error, probably a previous treatmente exists with the same treatment_id
            Path tmpDir = Files.createTempDirectory(null);
            file_name = (file_name.isEmpty() ? tmpUploadedFile.getName() : file_name);
            uploadedFile = new File(tmpDir.toString(), file_name);

            try {
                tmpUploadedFile.write(uploadedFile);

                if (request.getParameter("credentials") != null) {
                    byte[] decoded = Base64.decodeBase64(request.getParameter("credentials"));
                    String[] credentials = new String(decoded).split(":", 2);
                    experiment.setDataDirectoryUser(credentials[0]);
                    experiment.setDataDirectoryPass(credentials[1]);
                } else if (request.getParameter("apikey") != null) {
                    experiment.setDataDirectoryApiKey(request.getParameter("apikey"));
                }

                FileManager.getFileManager(DATA_LOCATION).saveFiles(new File[] { uploadedFile },
                        experiment.getDataDirectoryInformation(), parent_dir);
            } catch (IOException e) {
                // Directory creation failed
                throw new Exception(
                        "Unable to save the uploded file. Please check if the Tomcat user has read/write permissions over the data application directory.");
            } finally {
                tmpUploadedFile.delete();
                uploadedFile.delete();
                Files.delete(tmpDir);
            }
        } catch (Exception e) {
            ServerErrorManager.handleException(e, File_servlets.class.getName(), "add_new_file_handler",
                    e.getMessage());
        } finally {
            /**
             * *******************************************************
             * STEP 5b CATCH ERROR, CLEAN CHANGES. throws SQLException
             * *******************************************************
             */
            if (ServerErrorManager.errorStatus()) {
                response.setStatus(400);
                response.getWriter().print(ServerErrorManager.getErrorResponse());
            } else {
                JsonObject obj = new JsonObject();
                obj.add("success", new JsonPrimitive(true));
                response.getWriter().print(obj.toString());
            }
        }
    } catch (Exception e) {
        ServerErrorManager.handleException(e, File_servlets.class.getName(), "add_new_file_handler",
                e.getMessage());
        response.setStatus(400);
        response.getWriter().print(ServerErrorManager.getErrorResponse());
    }
}

From source file:stroom.servlet.ImportFileServlet.java

@Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/plain;charset=UTF-8");

    final PropertyMap propertyMap = new PropertyMap();
    propertyMap.setSuccess(false);//from  ww  w . j a  va 2  s .  c o  m

    try {
        // Parse the request and populate a map of file items.
        final Map<String, FileItem> items = getFileItems(request);
        if (items.size() == 0) {
            response.getWriter().write(propertyMap.toArgLine());
            return;
        }

        final FileItem fileItem = items.get("fileUpload");
        final InputStream inputStream = fileItem.getInputStream();

        final ResourceKey uuid = sessionResourceStore.createTempFile(fileItem.getName());
        final File file = sessionResourceStore.getTempFile(uuid);
        streamEventLog.importStream(new Date(), "Import", file.getAbsolutePath(), null);

        StreamUtil.streamToStream(inputStream, new FileOutputStream(file));

        propertyMap.setSuccess(true);
        uuid.write(propertyMap);
        fileItem.delete();

    } catch (final Throwable th) {
        streamEventLog.importStream(new Date(), "Import", null, th);
        LOGGER.error("doPost() - Error on DataStreamHandler.create()", th);
        propertyMap.put("exception", th.getMessage());
        // response.getWriter().write("FAILED - " + th.getMessage());
    }

    response.getWriter().write(propertyMap.toArgLine());
}

From source file:v7db.files.buckets.BucketsServlet.java

private void doFormPost(HttpServletRequest request, HttpServletResponse response, BSONObject bucket)
        throws IOException {
    ObjectId uploadId = new ObjectId();

    BSONObject parameters = new BasicBSONObject();
    List<FileItem> files = new ArrayList<FileItem>();

    if (ServletFileUpload.isMultipartContent(request)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {/*w w w . j a  v a 2s  . co m*/
            for (Object _file : upload.parseRequest(request)) {
                FileItem file = (FileItem) _file;
                if (file.isFormField()) {
                    String v = file.getString();
                    parameters.put(file.getFieldName(), v);
                } else {
                    files.add(file);
                }
            }
        } catch (FileUploadException e) {
            throw new IOException(e);
        }

    } else {
        for (Entry<String, String[]> param : request.getParameterMap().entrySet()) {
            String[] v = param.getValue();
            if (v.length == 1)
                parameters.put(param.getKey(), v[0]);
            else
                parameters.put(param.getKey(), v);

        }
    }

    BSONObject result = new BasicBSONObject("_id", uploadId);
    BSONObject uploads = new BasicBSONObject();
    for (FileItem file : files) {
        DiskFileItem f = (DiskFileItem) file;
        // inline until 10KB
        if (f.isInMemory()) {
            uploads.put(f.getFieldName(), storage.inlineOrInsertContentsAndBackRefs(10240, f.get(), uploadId,
                    f.getName(), f.getContentType()));
        } else {
            uploads.put(f.getFieldName(), storage.inlineOrInsertContentsAndBackRefs(10240, f.getStoreLocation(),
                    uploadId, f.getName(), f.getContentType()));
        }
        file.delete();
    }
    result.put("files", uploads);
    result.put("parameters", parameters);

    bucketCollection.update(new BasicDBObject("_id", bucket.get("_id")),
            new BasicDBObject("$push", new BasicDBObject("FormPost.data", result)));

    String redirect = BSONUtils.getString(bucket, "FormPost.redirect");
    // redirect mode
    if (StringUtils.isNotBlank(redirect)) {
        response.sendRedirect(redirect + "?v7_formpost_id=" + uploadId);
        return;
    }
    // echo mode

    // JSON does not work, see https://jira.mongodb.org/browse/JAVA-332
    // response.setContentType("application/json");
    // response.getWriter().write(JSON.serialize(result));
    byte[] bson = BSON.encode(result);
    response.getOutputStream().write(bson);
}