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

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

Introduction

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

Prototype

public void setSizeThreshold(int sizeThreshold) 

Source Link

Document

Sets the size threshold beyond which files are written directly to disk.

Usage

From source file:org.footware.server.services.TrackUploadServlet.java

@SuppressWarnings("unchecked")
@Override// w  w w . j ava  2s.  co m
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    logger = LoggerFactory.getLogger(TrackUploadServlet.class);

    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(req);

    // Init fields of form
    String extension = "";
    File uploadedFile = null;
    String notes = "";
    String name = "";
    int privacy = 0;
    Boolean comments = false;
    String fileName = null;
    String email = null;
    FileItem file = null;

    if (isMultipart) {

        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setRepository(new File("tmp"));
        factory.setSizeThreshold(10000000);

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

        // Create a progress listener
        ProgressListener progressListener = new ProgressListener() {
            public void update(long pBytesRead, long pContentLength, int pItems) {
                logger.info("We are currently reading item " + pItems);
                if (pContentLength == -1) {
                    logger.info("So far, " + pBytesRead + " bytes have been read.");
                } else {
                    logger.info("So far, " + pBytesRead + " of " + pContentLength + " bytes have been read.");
                }
            }
        };
        upload.setProgressListener(progressListener);

        // Parse the request
        List<FileItem> items;
        try {
            items = upload.parseRequest(req);

            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = iter.next();

                // Process a file upload
                if (!item.isFormField() && item.getFieldName().equals("file")) {

                    // Get file name
                    fileName = item.getName();

                    // If file is not set, we cancel import
                    if (fileName == null) {
                        logger.info("empty file name");
                        break;
                    }

                    // We have to parse the filename because of IE again
                    else {
                        logger.info("received file:" + fileName);
                        fileName = FilenameUtils.getName(fileName);

                        file = item;

                    }

                    // Read notes field
                } else if (item.isFormField() && item.getFieldName().equals("notes")) {
                    notes = item.getString();
                    logger.debug("notes" + ": " + item.getString());

                    // Read comments field
                } else if (item.isFormField() && item.getFieldName().equals("comments")) {

                    // Value can either be on or off
                    if (item.getString().equals("on")) {
                        comments = true;
                    } else {
                        comments = false;
                    }
                    logger.debug("comments" + ": " + item.getString());

                    // Read privacy field
                } else if (item.isFormField() && item.getFieldName().equals("privacy")) {
                    String priv = item.getString();

                    // Currently values can be either public or private.
                    // Default is private
                    if (priv.equals("public")) {
                        privacy = 5;
                    } else if (priv.equals("private")) {
                        privacy = 0;
                    } else {
                        privacy = 0;
                    }
                    logger.debug("privacy" + ": " + item.getString());

                    // Read name file
                } else if (item.isFormField() && item.getFieldName().equals("name")) {
                    name = item.getString();
                    logger.debug("name" + ": " + item.getString());
                } else if (item.isFormField() && item.getFieldName().equals("email")) {
                    email = item.getString();
                    logger.debug("email" + ": " + item.getString());
                }
            }
            User user = UserUtil.getByEmail(email);

            // If we read all fields, we can start the import
            if (file != null) {

                // Get UserDTO
                // User user = (User) req.getSession().getAttribute("user");

                // UserUtil.getByEmail(email);
                logger.info("User: " + user.getFullName() + " " + user.getEmail());
                String userDirectoryString = user.getEmail().replace("@", "_at_");

                File baseDirectory = initFileStructure(userDirectoryString);

                // If already a file exist with the same name, we have
                // to search for a new name
                extension = fileName.substring(fileName.length() - 3, fileName.length());
                uploadedFile = getSavePath(baseDirectory.getAbsolutePath(), fileName);
                logger.debug(uploadedFile.getAbsolutePath());

                // Finally write the file to disk
                try {
                    file.write(uploadedFile);
                } catch (Exception e) {
                    logger.error("File upload unsucessful", e);
                    e.printStackTrace();
                    return;
                }

                TrackImporter importer = importerMap.get(extension);
                importer.importTrack(uploadedFile);
                TrackVisualizationFactoryImpl speedFactory = new TrackVisualizationFactoryImpl(
                        new TrackVisualizationSpeedStrategy());
                TrackVisualizationFactoryImpl elevationFactory = new TrackVisualizationFactoryImpl(
                        new TrackVisualizationElevationStrategy());

                // Add meta information to track
                for (Track dbTrack : importer.getTracks()) {
                    dbTrack.setCommentsEnabled(comments);
                    dbTrack.setNotes(notes);
                    dbTrack.setPublicity(privacy);
                    dbTrack.setFilename(fileName);
                    dbTrack.setPath(uploadedFile.getAbsolutePath());

                    dbTrack.setUser(user);
                    //persist
                    dbTrack.store();

                    TrackVisualization ele = new TrackVisualization(speedFactory.create(dbTrack));
                    ele.store();
                    TrackVisualization spd = new TrackVisualization(elevationFactory.create(dbTrack));
                    spd.store();
                }

            } else {
                logger.error("error: file: " + (file != null));
            }
        } catch (FileUploadException e1) {
            logger.error("File upload unsucessful", e1);
            e1.printStackTrace();
        } catch (Exception e) {
            logger.error("File upload unsucessful", e);
            e.printStackTrace();
        }
    }
}

From source file:org.geosdi.geoplatform.gui.server.UploadServlet.java

@SuppressWarnings("unchecked")
@Override//from w  w w.j av  a2 s .  c o  m
public void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException, GeoPlatformException {
    //        logger.info("Query String: " + req.getQueryString());
    //        while (req.getParameterMap().keySet().iterator().hasNext()) {
    //            logger.info("Parameter next: " + req.getParameterMap().keySet().iterator().next());
    //        }
    //        while (req.getParameterNames().hasMoreElements()) {
    //            logger.info("Parameter name: " + req.getParameterNames().nextElement());
    //        }
    //        while (req.getAttributeNames().hasMoreElements()) {
    //            logger.info("Attribute name: " + req.getAttributeNames().nextElement());
    //        }
    String workspace = null;
    HttpSession session = req.getSession();
    Object accountObj = session.getAttribute(SessionProperty.LOGGED_ACCOUNT.toString());
    GPAccount account;
    if (accountObj != null && accountObj instanceof GPAccount) {
        account = (GPAccount) accountObj;
    } else {
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Session Timeout");
        return;
    }
    receivedAssertion = (AssertionImpl) session.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);
    // process only multipart requests
    if (ServletFileUpload.isMultipartContent(req)) {
        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // Create a new file upload handler
        /*
          * Set the size threshold, above which content will be stored on
          * disk.
          */
        factory.setSizeThreshold(1 * 1024 * 1024); //1 MB

        ServletFileUpload upload = new ServletFileUpload(factory);
        File uploadedFile = null;
        // Parse the request
        try {
            List<FileItem> items = upload.parseRequest(req);
            for (FileItem item : items) {
                // process only file upload - discard other form item types
                if (item.isFormField()) {
                    logger.debug("Analyzing item field name: " + item.getFieldName());
                    logger.debug("Analyzing item string: " + item.getString());
                    //Ricevo parametro
                    if (item.getFieldName().equals("workspace")) {
                        workspace = item.getString();
                        logger.debug("Found workspace in request param: " + workspace);
                    }
                } else {
                    String fileName = item.getName();
                    // get only the file name not whole path
                    if (fileName != null) {
                        fileName = FilenameUtils.getName(fileName);
                    }

                    try {
                        uploadedFile = this.publisherFileUtils.createFileWithUniqueName(fileName);
                        item.write(uploadedFile);
                    } catch (Exception ex) {
                        logger.info("ERRORE : " + ex);
                        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "An error occurred writing the file: " + ex.getMessage());
                        throw new GeoPlatformException("Error on uploading shape.");
                    }
                    resp.setStatus(HttpServletResponse.SC_CREATED);
                    resp.flushBuffer();
                }
            }
            List<InfoPreview> infoPreviews = this.manageUploadedFilePreview(uploadedFile, session.getId(),
                    account.getNaturalID(), workspace);
            resp.setContentType("text/x-json;charset=UTF-8");
            resp.setHeader("Cache-Control", "no-cache");
            String result = PublisherFileUtils.generateJSONObjects(infoPreviews);
            resp.getWriter().write(result);
            //geoPlatformPublishClient.publish("previews", "dataTest", infoPreview.getDataStoreName());
        } catch (FileUploadException ex) {
            logger.info("ERRORE : " + ex);
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred creating the file: " + ex.getMessage());
            throw new GeoPlatformException("Error on uploading shape.");
        } finally {
            uploadedFile.delete();
            resp.getWriter().close();
        }
    } else {
        resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                "Request contents type is not supported by the servlet.");
    }
}

From source file:org.infoglue.calendar.actions.CreateResourceAction.java

/**
 * This is the entry point for the main listing.
 *///from   w  w w  .  ja v a 2  s .com

public String execute() throws Exception {
    log.debug("-------------Uploading file.....");

    File uploadedFile = null;
    String maxUploadSize = "";
    String uploadSize = "";

    try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(2000000);
        //factory.setRepository(yourTempDirectory);

        PortletFileUpload upload = new PortletFileUpload(factory);

        String maxSize = getSetting("AssetUploadMaxFileSize");
        log.debug("maxSize:" + maxSize);
        if (maxSize != null && !maxSize.equals("") && !maxSize.equals("@AssetUploadMaxFileSize@")) {
            try {
                maxUploadSize = maxSize;
                upload.setSizeMax((new Long(maxSize) * 1000));
            } catch (Exception e) {
                log.warn("Faulty max size parameter sent from portlet component:" + maxSize);
            }
        } else {
            maxSize = "" + (10 * 1024);
            maxUploadSize = maxSize;
            upload.setSizeMax((new Long(maxSize) * 1000));
        }

        List fileItems = upload.parseRequest(ServletActionContext.getRequest());
        log.debug("fileItems:" + fileItems.size());
        Iterator i = fileItems.iterator();
        while (i.hasNext()) {
            Object o = i.next();
            DiskFileItem dfi = (DiskFileItem) o;
            log.debug("dfi:" + dfi.getFieldName());
            log.debug("dfi:" + dfi);

            if (dfi.isFormField()) {
                String name = dfi.getFieldName();
                String value = dfi.getString();
                uploadSize = "" + (dfi.getSize() / 1000);

                log.debug("name:" + name);
                log.debug("value:" + value);
                if (name.equals("assetKey")) {
                    this.assetKey = value;
                } else if (name.equals("eventId")) {
                    this.eventId = new Long(value);
                    ServletActionContext.getRequest().setAttribute("eventId", this.eventId);
                } else if (name.equals("calendarId")) {
                    this.calendarId = new Long(value);
                    ServletActionContext.getRequest().setAttribute("calendarId", this.calendarId);
                } else if (name.equals("mode"))
                    this.mode = value;
            } else {
                String fieldName = dfi.getFieldName();
                String fileName = dfi.getName();
                uploadSize = "" + (dfi.getSize() / 1000);

                this.fileName = fileName;
                log.debug("FileName:" + this.fileName);
                uploadedFile = new File(getTempFilePath() + File.separator + fileName);
                dfi.write(uploadedFile);
            }

        }
    } catch (Exception e) {
        ServletActionContext.getRequest().getSession().setAttribute("errorMessage",
                "Exception uploading resource. " + e.getMessage() + ".<br/>Max upload size: " + maxUploadSize
                        + " KB"); // + "<br/>Attempted upload size (in KB):" + uploadSize);
        ActionContext.getContext().getValueStack().getContext().put("errorMessage",
                "Exception uploading resource. " + e.getMessage() + ".<br/>Max upload size: " + maxUploadSize
                        + " KB"); // + "<br/>Attempted upload size (in KB):" + uploadSize);
        log.error("Exception uploading resource. " + e.getMessage());
        return Action.ERROR;
    }

    try {
        log.debug("Creating resources.....:" + this.eventId + ":"
                + ServletActionContext.getRequest().getParameter("eventId") + ":"
                + ServletActionContext.getRequest().getParameter("calendarId"));
        ResourceController.getController().createResource(this.eventId, this.getAssetKey(),
                this.getFileContentType(), this.getFileName(), uploadedFile, getSession());
    } catch (Exception e) {
        ServletActionContext.getRequest().getSession().setAttribute("errorMessage",
                "Exception saving resource to database: " + e.getMessage());
        ActionContext.getContext().getValueStack().getContext().put("errorMessage",
                "Exception saving resource to database: " + e.getMessage());
        log.error("Exception saving resource to database. " + e.getMessage());
        return Action.ERROR;
    }

    return Action.SUCCESS;
}

From source file:org.infoglue.deliver.taglib.common.ParseMultipartTag.java

/**
 * Process the end tag. Sets a cookie.  
 * /*from ww  w  . j  a  va  2  s . c o m*/
 * @return indication of whether to continue evaluating the JSP page.
 * @throws JspException if an error occurred while processing this tag.
 */
public int doEndTag() throws JspException {
    Map parameters = new HashMap();

    try {
        //Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        //Set factory constraints
        factory.setSizeThreshold(maxSize.intValue());
        //factory.setRepository(new File(CmsPropertyHandler.getDigitalAssetPath()));

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

        //Set overall request size constraint
        upload.setSizeMax(this.maxSize.intValue());

        if (upload.isMultipartContent(this.getController().getHttpServletRequest())) {
            //Parse the request
            List items = upload.parseRequest(this.getController().getHttpServletRequest());

            List files = new ArrayList();

            //Process the uploaded items
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();

                if (!item.isFormField()) {
                    String fieldName = item.getFieldName();
                    String fileName = item.getName();
                    String contentType = item.getContentType();
                    boolean isInMemory = item.isInMemory();
                    long sizeInBytes = item.getSize();

                    if (isValidContentType(contentType)) {
                        files.add(item);
                    } else {
                        if ((item.getName() == null || item.getName().equals("")) && this.ignoreEmpty) {
                            logger.warn("Empty file but that was ok..");
                        } else {
                            pageContext.setAttribute("status", "nok");
                            pageContext.setAttribute("upload_error",
                                    "A field did not have a valid content type");
                            pageContext.setAttribute(fieldName + "_error", "Not a valid content type");
                            //throw new JspException("Not a valid content type");
                        }
                    }
                } else {
                    String name = item.getFieldName();
                    String value = item.getString();
                    String oldValue = (String) parameters.get(name);
                    if (oldValue != null)
                        value = oldValue + "," + value;

                    if (value != null) {
                        try {
                            String fromEncoding = "iso-8859-1";
                            String toEncoding = "utf-8";

                            String testValue = new String(value.getBytes(fromEncoding), toEncoding);

                            if (testValue.indexOf((char) 65533) == -1)
                                value = testValue;
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    parameters.put(name, value);
                }

            }

            parameters.put("files", files);

            setResultAttribute(parameters);
        } else {
            setResultAttribute(null);
        }
    } catch (Exception e) {
        logger.warn("Error doing an upload" + e.getMessage(), e);
        //pageContext.setAttribute("fieldName_exception", "contentType_MAX");
        //throw new JspException("File upload failed: " + e.getMessage());
        pageContext.setAttribute("status", "nok");
        pageContext.setAttribute("upload_error", "" + e.getMessage());
    }

    return EVAL_PAGE;
}

From source file:org.infoscoop.admin.web.UploadGadgetServlet.java

private UploadFileInfo extractUploadFileInfo(HttpServletRequest req) {
    UploadFileInfo info = new UploadFileInfo();
    try {/*from  w  w  w . ja va 2s  .com*/
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        //set the standard value that needs when it upload.
        factory.setSizeThreshold(1024);
        upload.setSizeMax(-1);

        List<FileItem> items = upload.parseRequest(req);

        //get the FileItem object
        for (FileItem fItem : items) {
            if ("data".equals(fItem.getFieldName())) {
                info.fileItem = fItem;
            } else if ("type".equals(fItem.getFieldName())) {
                info.type = fItem.getString();
            } else if ("mode".equals(fItem.getFieldName())) {
                info.mode = fItem.getString();
            } else if ("path".equals(fItem.getFieldName())) {
                info.path = fItem.getString();
            } else if ("name".equals(fItem.getFieldName())) {
                info.name = fItem.getString();
            } else if ("create".equals(fItem.getFieldName())) {
                try {
                    info.create = Boolean.valueOf(fItem.getString());
                } catch (Exception ex) {
                    // ignore
                }
            }
        }
    } catch (FileUploadException ex) {
        throw new GadgetResourceException("Unexpected error occurred while getting uplaod file.",
                "ams_gadgetResourceUnexceptedUploadFailed", ex);
    } catch (Exception ex) {
        throw new GadgetResourceException(ex);
    }

    // check the file(for FireFox)
    if (info.fileItem == null || info.fileItem.getName().length() == 0)
        throw new GadgetResourceException("Upload file not found.", "ams_gadgetResourceUploadFileNotFound");

    // check the file(for IE)
    if (info.fileItem.getSize() == 0)
        throw new GadgetResourceException("The upload file is not found or the file is empty.",
                "ams_gadgetResourceUploadFileNotFoundOrEmpty");

    if (!info.isModuleMode()) {
        if (info.type == null || info.path == null || info.name == null)
            throw new GadgetResourceException();
    }

    return info;
}

From source file:org.integratedmodelling.thinklab.rest.resources.FileReceiveService.java

@Post
public Representation service(Representation entity) throws Exception {

    ISession session = getSession();// w w w  .  ja va  2 s  .c  om

    if (entity != null) {
        if (MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) {

            // 1/ Create a factory for disk-based file items
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(1000240);

            // 2/ Create a new file upload handler based on the Restlet
            // FileUpload extension that will parse Restlet requests and
            // generates FileItems.
            RestletFileUpload upload = new RestletFileUpload(factory);
            List<FileItem> items;

            // 3/ Request is parsed by the handler which generates a
            // list of FileItems
            items = upload.parseRequest(getRequest());

            // save each file
            ArrayList<String> done = new ArrayList<String>();
            for (final Iterator<FileItem> it = items.iterator(); it.hasNext();) {
                FileItem fi = it.next();
                Pair<File, String> filename = getFileName(fi.getName(), session);
                fi.write(filename.getFirst());
                done.add(filename.getSecond());
            }

            if (done.size() > 0) {
                setResult(done.toArray(new String[done.size()]));
            } else {
                fail("file upload failed: no file received");
            }
        }
    } else {
        fail("file upload: not a multipart request");
    }

    return wrap();
}

From source file:org.j2eeframework.commons.struts2.multipart.JakartaMultiPartRequest.java

/**
 * Creates a new request wrapper to handle multi-part data using methods adapted from Jason Pell's
 * multipart classes (see class description).
 *
 * @param saveDir        the directory to save off the file
 * @param servletRequest the request containing the multipart
 * @throws java.io.IOException  is thrown if encoding fails.
 *//*from www.  j  a v a2  s. c  o  m*/
public void parse(HttpServletRequest servletRequest, String saveDir) throws IOException {
    DiskFileItemFactory fac = new DiskFileItemFactory();
    // Make sure that the data is written to file
    fac.setSizeThreshold(0);
    if (saveDir != null) {
        fac.setRepository(new File(saveDir));
    }

    // Parse the request
    try {
        ServletFileUpload upload = new ServletFileUpload(fac);
        upload.setSizeMax(maxSize);

        @SuppressWarnings("unchecked")
        List<FileItem> items = upload.parseRequest(createRequestContext(servletRequest));

        for (Object item1 : items) {
            FileItem item = (FileItem) item1;
            if (LOG.isDebugEnabled())
                LOG.debug("Found item " + item.getFieldName());
            if (item.isFormField()) {
                LOG.debug("Item is a normal form field");
                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)
                String charset = servletRequest.getCharacterEncoding();
                if (charset != null) {
                    values.add(item.getString(charset));
                } else {
                    values.add(item.getString());
                }
                params.put(item.getFieldName(), values);
            } else {
                LOG.debug("Item is a file upload");

                // Skip file uploads that don't have a file name - meaning that no file was selected.
                if (item.getName() == null || item.getName().trim().length() < 1) {
                    LOG.debug("No file has been uploaded for the field: " + item.getFieldName());
                    continue;
                }

                List<FileItem> values;
                if (files.get(item.getFieldName()) != null) {
                    values = files.get(item.getFieldName());
                } else {
                    values = new ArrayList<FileItem>();
                }

                values.add(item);
                files.put(item.getFieldName(), values);
            }
        }
    } catch (SizeLimitExceededException e) {
        ArrayList<String> values = new ArrayList<String>();
        values.add("SizeLimitExceededException");
        params.put("exception", values);//?
    } catch (FileUploadException e) {
        LOG.error("Unable to parse request", e);
        ArrayList<String> values = new ArrayList<String>();
        values.add("FileUploadException");
        params.put("exception", values);
        errors.add(e.getMessage());
    }
}

From source file:org.jahia.tools.files.FileUpload.java

/**
 * Init the MultiPartReq object if it's actually null
 *
 * @exception IOException/*from  w ww.java 2s  . c o  m*/
 */
protected void init() throws IOException {

    params = new HashMap<String, List<String>>();
    paramsContentType = new HashMap<String, String>();
    files = new HashMap<String, DiskFileItem>();
    filesByFieldName = new HashMap<String, DiskFileItem>();

    parseQueryString();

    if (checkSavePath(savePath)) {
        try {
            final ServletFileUpload upload = new ServletFileUpload();
            FileItemIterator iter = upload.getItemIterator(req);
            DiskFileItemFactory factory = null;
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                InputStream stream = item.openStream();
                if (item.isFormField()) {
                    final String name = item.getFieldName();
                    final List<String> v;
                    if (params.containsKey(name)) {
                        v = params.get(name);
                    } else {
                        v = new ArrayList<String>();
                        params.put(name, v);
                    }
                    v.add(Streams.asString(stream, encoding));
                    paramsContentType.put(name, item.getContentType());
                } else {
                    if (factory == null) {
                        factory = new DiskFileItemFactory();
                        factory.setSizeThreshold(1);
                        factory.setRepository(new File(savePath));
                    }
                    DiskFileItem fileItem = (DiskFileItem) factory.createItem(item.getFieldName(),
                            item.getContentType(), item.isFormField(), item.getName());
                    try {
                        Streams.copy(item.openStream(), fileItem.getOutputStream(), true);
                    } catch (FileUploadIOException e) {
                        throw (FileUploadException) e.getCause();
                    } catch (IOException e) {
                        throw new IOFileUploadException("Processing of " + FileUploadBase.MULTIPART_FORM_DATA
                                + " request failed. " + e.getMessage(), e);
                    }
                    final FileItemHeaders fih = item.getHeaders();
                    fileItem.setHeaders(fih);
                    if (fileItem.getSize() > 0) {
                        files.put(fileItem.getStoreLocation().getName(), fileItem);
                        filesByFieldName.put(fileItem.getFieldName(), fileItem);
                    }
                }
            }
        } catch (FileUploadException ioe) {
            logger.error("Error while initializing FileUpload class:", ioe);
            throw new IOException(ioe.getMessage());
        }
    } else {
        logger.error("FileUpload::init storage path does not exists or can write");
        throw new IOException("FileUpload::init storage path does not exists or cannot write");
    }
}

From source file:org.javalite.activeweb.HttpSupport.java

/**
 * Returns a collection of uploaded files and form fields from a multi-part request.
 * This method uses <a href="http://commons.apache.org/proper/commons-fileupload/apidocs/org/apache/commons/fileupload/disk/DiskFileItemFactory.html">DiskFileItemFactory</a>.
 * As a result, it is recommended to add the following to your web.xml file:
 *
 * <pre>//w ww  .  j  a va  2s.c o m
 *   &lt;listener&gt;
 *      &lt;listener-class&gt;
 *         org.apache.commons.fileupload.servlet.FileCleanerCleanup
 *      &lt;/listener-class&gt;
 *   &lt;/listener&gt;
 *</pre>
 *
 * For more information, see: <a href="http://commons.apache.org/proper/commons-fileupload/using.html">Using FileUpload</a>
 *
 * The size of upload defaults to max of 20mb. Files greater than that will be rejected. If you want to accept files
 * smaller of larger, create a file called <code>activeweb.properties</code>, add it to your classpath and
 * place this property to the file:
 *
 * <pre>
 * #max upload size
 * maxUploadSize = 20000000
 * </pre>
 *
 * @param encoding specifies the character encoding to be used when reading the headers of individual part.
 * When not specified, or null, the request encoding is used. If that is also not specified, or null,
 * the platform default encoding is used.
 *
 * @return a collection of uploaded files from a multi-part request.
 */
protected List<FormItem> multipartFormItems(String encoding) {
    //we are thread safe, because controllers are pinned to a thread and discarded after each request.
    if (formItems != null) {
        return formItems;
    }

    HttpServletRequest req = Context.getHttpRequest();

    if (req instanceof AWMockMultipartHttpServletRequest) {//running inside a test, and simulating upload.
        formItems = ((AWMockMultipartHttpServletRequest) req).getFormItems();
    } else {

        if (!ServletFileUpload.isMultipartContent(req))
            throw new ControllerException(
                    "this is not a multipart request, be sure to add this attribute to the form: ... enctype=\"multipart/form-data\" ...");

        DiskFileItemFactory factory = new DiskFileItemFactory();

        factory.setSizeThreshold(Configuration.getMaxUploadSize());
        factory.setRepository(Configuration.getTmpDir());

        ServletFileUpload upload = new ServletFileUpload(factory);
        if (encoding != null)
            upload.setHeaderEncoding(encoding);
        upload.setFileSizeMax(Configuration.getMaxUploadSize());
        try {
            List<org.apache.commons.fileupload.FileItem> apacheFileItems = upload
                    .parseRequest(Context.getHttpRequest());
            formItems = new ArrayList<>();
            for (FileItem apacheItem : apacheFileItems) {
                ApacheFileItemFacade f = new ApacheFileItemFacade(apacheItem);
                if (f.isFormField()) {
                    formItems.add(new FormItem(f));
                } else {
                    formItems.add(new org.javalite.activeweb.FileItem(f));
                }
            }
            return formItems;
        } catch (Exception e) {
            throw new ControllerException(e);
        }
    }
    return formItems;
}

From source file:org.jessma.util.http.FileUploader.java

private ServletFileUpload getFileUploadComponent() {
    DiskFileItemFactory dif = new DiskFileItemFactory();

    if (factorySizeThreshold != DEFAULT_SIZE_THRESHOLD)
        dif.setSizeThreshold(factorySizeThreshold);
    if (factoryRepository != null)
        dif.setRepository(new File(factoryRepository));
    if (factoryCleaningTracker != null)
        dif.setFileCleaningTracker(factoryCleaningTracker);

    ServletFileUpload sfu = new ServletFileUpload(dif);

    if (sizeMax != NO_LIMIT_SIZE_MAX)
        sfu.setSizeMax(sizeMax);// www  .j  a v  a2 s . c  om
    if (fileSizeMax != NO_LIMIT_FILE_SIZE_MAX)
        sfu.setFileSizeMax(fileSizeMax);
    if (servletHeaderencoding != null)
        sfu.setHeaderEncoding(servletHeaderencoding);
    if (servletProgressListener != null)
        sfu.setProgressListener(servletProgressListener);

    return sfu;
}