Example usage for org.apache.commons.fileupload.disk DiskFileItemFactory setRepository

List of usage examples for org.apache.commons.fileupload.disk DiskFileItemFactory setRepository

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.disk DiskFileItemFactory setRepository.

Prototype

public void setRepository(File repository) 

Source Link

Document

Sets the directory used to temporarily store files that are larger than the configured size threshold.

Usage

From source file:org.codelabor.system.file.web.servlet.FileUploadServlet.java

/**
 * ??  .</br> ? ? ?? ?  , (: ?) ? mapId  . ?
 *  ?? ? repositoryType ,  ?/*from   w w w.  j  av  a  2s. c o  m*/
 * org.codelabor.system.file.RepositoryType .
 * 
 * @param request
 *            
 * @param response
 *            ?
 * @throws Exception
 *             
 */
@SuppressWarnings("unchecked")
protected void upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
    WebApplicationContext ctx = WebApplicationContextUtils
            .getRequiredWebApplicationContext(this.getServletContext());
    FileManager fileManager = (FileManager) ctx.getBean("fileManager");

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    Map<String, Object> paramMap = RequestUtils.getParameterMap(request);
    logger.debug("paramMap: {}", paramMap.toString());

    String mapId = (String) paramMap.get("mapId");
    RepositoryType acceptedRepositoryType = repositoryType;
    String requestedRepositoryType = (String) paramMap.get("repositoryType");
    if (StringUtils.isNotEmpty(requestedRepositoryType)) {
        acceptedRepositoryType = RepositoryType.valueOf(requestedRepositoryType);
    }

    if (isMultipart) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(sizeThreshold);
        factory.setRepository(new File(tempRepositoryPath));
        factory.setFileCleaningTracker(FileCleanerCleanup.getFileCleaningTracker(this.getServletContext()));

        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setFileSizeMax(fileSizeMax);
        upload.setSizeMax(requestSizeMax);
        upload.setHeaderEncoding(characterEncoding);
        upload.setProgressListener(new FileUploadProgressListener());
        try {
            List<FileItem> fileItemList = upload.parseRequest(request);
            Iterator<FileItem> iter = fileItemList.iterator();

            while (iter.hasNext()) {
                FileItem fileItem = iter.next();
                logger.debug("fileItem: {}", fileItem.toString());
                FileDTO fileDTO = null;
                if (fileItem.isFormField()) {
                    paramMap.put(fileItem.getFieldName(), fileItem.getString(characterEncoding));
                } else {
                    if (fileItem.getName() == null || fileItem.getName().length() == 0)
                        continue;
                    // set DTO
                    fileDTO = new FileDTO();
                    fileDTO.setMapId(mapId);
                    fileDTO.setRealFilename(FilenameUtils.getName(fileItem.getName()));
                    if (acceptedRepositoryType == RepositoryType.FILE_SYSTEM) {
                        fileDTO.setUniqueFilename(getUniqueFilename());
                    }
                    fileDTO.setContentType(fileItem.getContentType());
                    fileDTO.setRepositoryPath(realRepositoryPath);
                    logger.debug("fileDTO: {}", fileDTO.toString());
                    UploadUtils.processFile(acceptedRepositoryType, fileItem.getInputStream(), fileDTO);
                }
                if (fileDTO != null)
                    fileManager.insertFile(fileDTO);
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            throw e;
        }
    } else {
        paramMap = RequestUtils.getParameterMap(request);
    }
    try {
        processParameters(paramMap);
    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e.getMessage());
        throw e;
    }
    dispatch(request, response, forwardPathUpload);
}

From source file:org.craftercms.cstudio.publishing.servlet.FileUploadServlet.java

/**
 * create servlet file upload //from w ww . java2 s . c  o m
 * 
 * @return
 */
protected ServletFileUpload createServletFileUpload() {
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    String tempPath = System.getProperty("java.io.tmpdir");
    if (tempPath == null) {
        tempPath = "temp";
    }
    File repoPath = new File(tempPath + File.separator + "crafter");
    if (!repoPath.exists()) {
        repoPath.mkdirs();
    }
    diskFileItemFactory.setRepository(repoPath);
    ServletFileUpload toRet = new ServletFileUpload(diskFileItemFactory);
    return toRet;
}

From source file:org.dihedron.strutlets.ActionContext.java

/**
 * Initialise the attributes map used to emulate the per-request attributes;
 * this map will simulate action-scoped request parameters, and will be populated 
 * with attributes that must be visible to all the render, serve resource and 
 * event handling requests coming after an action processing request. These 
 * parameters will be reset by the <code>ActionController</code>as soon as a 
 * new action processing request comes. 
 * /*from  ww w  .j a  v a 2  s. c  o  m*/
 * @param response
 *   the portlet response.
 * @param invocation
 *   the optional <code>ActionInvocation</code> object, only available in the
 *   context of an action or event processing, not in the render phase.
 * @throws StrutletsException 
 */
static void bindContext(GenericPortlet portlet, PortletRequest request, PortletResponse response,
        Properties configuration, ApplicationServer server, PortalServer portal,
        FileUploadConfiguration uploadInfo) throws StrutletsException {

    logger.debug("initialising the action context for thread {}", Thread.currentThread().getId());

    getContext().portlet = portlet;
    getContext().request = request;
    getContext().response = response;
    getContext().configuration = configuration;
    getContext().server = server;
    getContext().portal = portal;
    getContext().renderParametersChanged = false;

    // check if a map for REQUEST-scoped attributes is already available in
    // the PORTLET, if not instantiate it and load it into PORTLET scope
    PortletSession session = request.getPortletSession();
    @SuppressWarnings("unchecked")
    Map<String, Object> map = (Map<String, Object>) session.getAttribute(getRequestScopedAttributesKey(),
            PortletSession.PORTLET_SCOPE);
    if (map == null) {
        logger.trace("installing REQUEST scoped attributes map into PORTLET scope");
        session.setAttribute(getRequestScopedAttributesKey(), new HashMap<String, Object>(),
                PortletSession.PORTLET_SCOPE);
    }

    // this might be a multipart/form-data request, in which case we enable
    // support for file uploads and read them from the input stream using
    // a tweaked version of Apache Commons FileUpload facilities (in order 
    // to support file uploads in AJAX requests too!).
    if (request instanceof ClientDataRequest) {

        // this is where we try to retrieve all files (if there are any that were 
        // uploaded) and store them as temporary files on disk; these objects will
        // be accessible as ordinary values under the "FORM" scope through a 
        // custom "filename-to-file" map, which will be clened up when the context
        // is unbound
        String encoding = ((ClientDataRequest) request).getCharacterEncoding();
        getContext().encoding = Strings.isValid(encoding) ? encoding : DEFAULT_ENCODING;
        logger.trace("request encoding is: '{}'", getContext().encoding);

        try {
            RequestContext context = new ClientDataRequestContext((ClientDataRequest) request);

            // check that we have a file upload request
            if (PortletFileUpload.isMultipartContent(context)) {

                getContext().parts = new HashMap<String, FileItem>();

                logger.trace("handling multipart/form-data request");

                // create a factory for disk-based file items
                DiskFileItemFactory factory = new DiskFileItemFactory();

                // register a tracker to perform automatic file cleanup
                //                 FileCleaningTracker tracker = FileCleanerCleanup.getFileCleaningTracker(getContext().filter.getServletContext());
                //                 factory.setFileCleaningTracker(tracker);

                // configure the repository (to ensure a secure temporary location 
                // is used and the size of the )
                factory.setRepository(uploadInfo.getRepository());
                factory.setSizeThreshold(uploadInfo.getInMemorySizeThreshold());

                // create a new file upload handler
                PortletFileUpload upload = new PortletFileUpload(factory);
                upload.setSizeMax(uploadInfo.getMaxUploadableTotalSize());
                upload.setFileSizeMax(uploadInfo.getMaxUploadableFileSize());

                // parse the request & process the uploaded items
                List<FileItem> items = upload.parseRequest(context);
                logger.trace("{} items in the multipart/form-data request", items.size());
                for (FileItem item : items) {
                    // parameters would be stored with their fully-qualified 
                    // name if we didn't remove the portlet namespace
                    String fieldName = item.getFieldName().replaceFirst(getPortletNamespace(), "");
                    logger.trace("storing field '{}' (type: '{}') into parts map", fieldName,
                            item.isFormField() ? "field" : "file");
                    getContext().parts.put(fieldName, item);
                }
            } else {
                logger.trace("handling plain form request");
            }
        } catch (FileUploadException e) {
            logger.warn("error handling uploaded file", e);
            throw new StrutletsException("Error handling uploaded file", e);
        }
    }
}

From source file:org.dihedron.webmvc.ActionContext.java

/**
 * Binds the thread-local object to the current invocation, by setting
 * references to the various objects (web server plugin, request and
 * response objects etc.) that will be made available to the business method
 * through this context.//  w  w w. ja v a 2 s .c o m
 * 
 * @param request
 *   the servlet request object.
 * @param response
 *   the servlet response object.
 * @param configuration
 *   the configuration object, holding properties that may have been loaded at
 *   startup if the proper initialisation parameter is specified in the
 *   web.xml.
 * @param server
 *   a reference to the web server specific plugin.
 * @throws WebMVCException 
 */
static void bindContext(FilterConfig filter, HttpServletRequest request, HttpServletResponse response,
        Properties configuration, WebServer server, FileUploadConfiguration uploadInfo) throws WebMVCException {
    //      logger.trace("initialising the action context for thread {}", Thread.currentThread().getId());
    getContext().filter = filter;
    getContext().request = request;
    getContext().response = response;
    getContext().configuration = configuration;
    getContext().server = server;

    // this is where we try to retrieve all files (if there are any that were 
    // uploaded) and store them as temporary files on disk; these objects will
    // be accessible as ordinary values under the "FORM" scope through a 
    // custom "filename-to-file" map, which will be clened up when the context
    // is unbound
    //      String encoding = request.getCharacterEncoding();
    //        getContext().encoding = Strings.isValid(encoding)? encoding : DEFAULT_ENCODING;
    //        logger.trace("request encoding is: '{}'", getContext().encoding);

    try {

        // check that we have a file upload request
        if (ServletFileUpload.isMultipartContent(request)) {

            getContext().parts = new HashMap<String, FileItem>();

            logger.trace("handling multipart/form-data request");

            // create a factory for disk-based file items
            DiskFileItemFactory factory = new DiskFileItemFactory();

            // register a tracker to perform automatic file cleanup
            //              FileCleaningTracker tracker = FileCleanerCleanup.getFileCleaningTracker(getContext().filter.getServletContext());
            //              factory.setFileCleaningTracker(tracker);

            // configure the repository (to ensure a secure temporary location 
            // is used and the size of the )
            factory.setRepository(uploadInfo.getRepository());
            factory.setSizeThreshold(uploadInfo.getInMemorySizeThreshold());

            // create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setSizeMax(uploadInfo.getMaxUploadableTotalSize());
            upload.setFileSizeMax(uploadInfo.getMaxUploadableFileSize());

            // parse the request & process the uploaded items
            List<FileItem> items = upload.parseRequest(request);
            logger.trace("{} items in the multipart/form-data request", items.size());
            for (FileItem item : items) {
                logger.trace("storing field '{}' (type: '{}') into parts map", item.getFieldName(),
                        item.isFormField() ? "field" : "file");
                getContext().parts.put(item.getFieldName(), item);
            }
            //           } else {
            //              logger.trace("handling plain form request");
        }
    } catch (FileUploadException e) {
        logger.warn("error handling uploaded file", e);
        throw new WebMVCException("Error handling uploaded file", e);
    }
}

From source file:org.dspace.app.webui.util.FileUploadRequest.java

/**
 * Parse a multipart request and extracts the files
 * /*from   w w w.  j ava 2 s.c  om*/
 * @param req
 *            the original request
 */
public FileUploadRequest(HttpServletRequest req) throws IOException, FileSizeLimitExceededException {
    super(req);

    original = req;

    tempDir = ConfigurationManager.getProperty("upload.temp.dir");
    long maxSize = ConfigurationManager.getLongProperty("upload.max");

    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setRepository(new File(tempDir));

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    try {
        upload.setSizeMax(maxSize);
        List<FileItem> items = upload.parseRequest(req);
        for (FileItem item : items) {
            if (item.isFormField()) {
                parameters.put(item.getFieldName(), item.getString("UTF-8"));
            } else {
                parameters.put(item.getFieldName(), item.getName());
                fileitems.put(item.getFieldName(), item);
                filenames.add(item.getName());

                String filename = getFilename(item.getName());
                if (filename != null && !"".equals(filename)) {
                    item.write(new File(tempDir + File.separator + filename));
                }
            }
        }
    } catch (Exception e) {
        if (e.getMessage().contains("exceeds the configured maximum")) {
            // ServletFileUpload is not throwing the correct error, so this is workaround
            // the request was rejected because its size (11302) exceeds the configured maximum (536)
            int startFirstParen = e.getMessage().indexOf("(") + 1;
            int endFirstParen = e.getMessage().indexOf(")");
            String uploadedSize = e.getMessage().substring(startFirstParen, endFirstParen).trim();
            Long actualSize = Long.parseLong(uploadedSize);
            throw new FileSizeLimitExceededException(e.getMessage(), actualSize, maxSize);
        }
        throw new IOException(e.getMessage(), e);
    }
}

From source file:org.eclipse.equinox.http.servlet.internal.multipart.MultipartSupportImpl.java

public MultipartSupportImpl(ExtendedServletDTO servletDTO, ServletContext servletContext) {
    this.servletDTO = servletDTO;

    // Must return non-null File. See Servlet 3.1 4.8.1
    File baseStorage = (File) servletContext.getAttribute(ServletContext.TEMPDIR);

    if (servletDTO.multipartLocation.length() > 0) {
        File storage = new File(servletDTO.multipartLocation);

        if (!storage.isAbsolute()) {
            storage = new File(baseStorage, storage.getPath());
        }//w  w w.  j  a v  a  2 s. c  o m

        baseStorage = storage;
    }

    checkPermission(baseStorage, servletContext);

    baseStorage.mkdirs();

    DiskFileItemFactory factory = new DiskFileItemFactory();

    factory.setRepository(baseStorage);

    if (servletDTO.multipartFileSizeThreshold > 0) {
        factory.setSizeThreshold(servletDTO.multipartFileSizeThreshold);
    }

    upload = new ServletFileUpload(factory);

    if (servletDTO.multipartMaxFileSize > -1L) {
        upload.setFileSizeMax(servletDTO.multipartMaxFileSize);
    }

    if (servletDTO.multipartMaxRequestSize > -1L) {
        upload.setSizeMax(servletDTO.multipartMaxRequestSize);
    }
}

From source file:org.eclipse.equinox.http.servlet.tests.ServletTest.java

public void test_commonsFileUpload() throws Exception {
    Servlet servlet = new HttpServlet() {
        private static final long serialVersionUID = 1L;

        @Override/*  w  w  w  . j ava2s.  co m*/
        protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws IOException, ServletException {

            boolean isMultipart = ServletFileUpload.isMultipartContent(req);
            Assert.assertTrue(isMultipart);

            DiskFileItemFactory factory = new DiskFileItemFactory();

            ServletContext servletContext = this.getServletConfig().getServletContext();
            File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
            factory.setRepository(repository);
            ServletFileUpload upload = new ServletFileUpload(factory);

            List<FileItem> items = null;
            try {
                @SuppressWarnings("unchecked")
                List<FileItem> parseRequest = upload.parseRequest(req);
                items = parseRequest;
            } catch (FileUploadException e) {
                e.printStackTrace();
            }

            Assert.assertNotNull(items);
            Assert.assertFalse(items.isEmpty());

            FileItem fileItem = items.get(0);

            String submittedFileName = fileItem.getName();
            String contentType = fileItem.getContentType();
            long size = fileItem.getSize();

            PrintWriter writer = resp.getWriter();

            writer.write(submittedFileName);
            writer.write("|");
            writer.write(contentType);
            writer.write("|" + size);
        }
    };

    Dictionary<String, Object> props = new Hashtable<String, Object>();
    props.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_NAME, "S16");
    props.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_PATTERN, "/Servlet16/*");
    registrations.add(getBundleContext().registerService(Servlet.class, servlet, props));

    Map<String, List<Object>> map = new HashMap<String, List<Object>>();

    map.put("file", Arrays.<Object>asList(getClass().getResource("blue.png")));

    Map<String, List<String>> result = requestAdvisor.upload("Servlet16/do", map);

    Assert.assertEquals("200", result.get("responseCode").get(0));
    Assert.assertEquals("blue.png|image/png|292", result.get("responseBody").get(0));
}

From source file:org.exoplatform.document.upload.handle.UploadMultipartHandler.java

@Override
public List<Document> parseHttpRequest(HttpServletRequest request)
        throws SizeLimitExceededException, FileUploadException {
    if (logger.isDebugEnabled()) {
        logger.info("Parse file item form HTTP servlet request.");
    }/*from w  ww . j ava  2s  .  c om*/

    Document document = null;
    List<Document> documents = new ArrayList<Document>();
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart)
        return documents;

    File repository = FileUtils.forceMkdir(FilePathUtils.REPOSITORY_PATH);
    if (repository != null)
        logger.info("The" + FilePathUtils.REPOSITORY_PATH + " Directory is created");

    if (FileUtils.forceMkdir(FilePathUtils.RESOURCE_PATH) != null)
        logger.info("To create specified sub-folder under " + FilePathUtils.ROOT_PATH + " top-level folder");

    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(MEMORY_CACHE_SIZE);
    factory.setRepository(repository);

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(MAXIMUM_FILE_SIZE);
    try {
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> iterator = items.iterator();
        while (iterator.hasNext()) {
            FileItem fileItem = iterator.next();
            if (!fileItem.isFormField()) {
                // Write file items to disk-based
                String absolutePath = writeFiles(fileItem, fileItem.getName());
                document = Document.getInstance();
                document.setFilename(fileItem.getName());
                document.setContentType(fileItem.getContentType());
                document.setSize(fileItem.getSize());
                document.setUrl(absolutePath);
                document.setReadOnly(false);
                document.setArchive(false);
                document.setDirectory(false);
                document.setHidden(false);
                document.setSystem(false);
                document.setOther(false);
                document.setRegularFile(false);

                Date time = Calendar.getInstance().getTime();
                document.setCreationTime(time);
                document.setLastAccessTime(time);
                document.setLastModifiedTime(time);
                documents.add(document);
                logger.info("File(s) " + document.getFilename() + " was/were uploaded successfully");
            }
        }
    } catch (SizeLimitExceededException slee) {
        throw new SizeLimitExceededException(
                "The request was rejected because its size exceeds (" + slee.getActualSize()
                        + "bytes) the configured maximum (" + slee.getPermittedSize() + "bytes)");
    } catch (FileUploadException fue) {
        throw new FileUploadException("Upload file stream was been cancelled", fue.getCause());
    } finally {
        try {
            FileUtils.cleanDirectory(factory.getRepository());
            logger.info("Cleans a directory without deleting it");
        } catch (IOException ex) {
            logger.warn(ex.getMessage(), ex);
        }
    }

    return documents;
}

From source file:org.exoplatform.upload.UploadService.java

private ServletFileUpload makeServletFileUpload(final UploadResource upResource) {
    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // Set factory constraints
    factory.setSizeThreshold(0);//from   w ww .ja v a2  s  .  co  m
    factory.setRepository(new File(uploadLocation_));

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    ProgressListener listener = new ProgressListener() {
        public void update(long pBytesRead, long pContentLength, int pItems) {
            if (pBytesRead == upResource.getUploadedSize())
                return;
            upResource.addUploadedBytes(pBytesRead - upResource.getUploadedSize());
        }
    };
    upload.setProgressListener(listener);
    return upload;
}

From source file:org.flowerplatform.core.file.upload.UploadServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart) {
        return;//from w ww .j a va2 s.co m
    }
    // entire URL displayed after servlet name ("servlet/upload") -> /uploadId/file_to_upload_name         
    String uploadId = request.getPathInfo().substring(1, request.getPathInfo().lastIndexOf("/"));
    UploadService uploadService = ((UploadService) CorePlugin.getInstance().getServiceRegistry()
            .getService("uploadService"));

    UploadInfo uploadInfo = uploadService.getUploadInfo(uploadId);
    if (uploadInfo.getTmpLocation() == null) {
        return;
    }

    logger.trace("Uploading {}", uploadInfo);

    // create temporary upload location file for archive that needs to be unzipped after
    File file = new File(uploadInfo.getTmpLocation());
    if (!file.exists() && uploadInfo.unzipFile()) {
        file.createNewFile();
    }

    // Create a factory for disk-based file items

    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setRepository(uploadService.getTemporaryUploadDirectory());
    factory.setFileCleaningTracker(FileCleanerCleanup.getFileCleaningTracker(request.getServletContext()));

    // Create a new file upload handler
    ServletFileUpload uploadHandler = new ServletFileUpload(factory);

    File uploadedFile = null;
    try {
        // Parse the request
        List<FileItem> items = uploadHandler.parseRequest(request);
        // Process the uploaded items
        Iterator<FileItem> it = items.iterator();
        while (it.hasNext()) {
            FileItem item = it.next();
            if (!item.isFormField()) { // uploaded file
                uploadedFile = new File(uploadInfo.unzipFile() ? uploadInfo.getTmpLocation()
                        : (uploadInfo.getTmpLocation() + "/" + item.getName()));
                item.write(uploadedFile);
            }
        }
        if (uploadInfo.unzipFile()) { // unzip file if requested
            CoreUtils.unzipArchive(uploadedFile, new File(uploadInfo.getLocation()));
        }
    } catch (Exception e) { // something happened or user cancelled the upload while in progress
        if (uploadedFile != null) {
            CoreUtils.delete(uploadedFile);
        }
    }

}