Example usage for org.apache.commons.fileupload.servlet ServletFileUpload setSizeMax

List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload setSizeMax

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.servlet ServletFileUpload setSizeMax.

Prototype

public void setSizeMax(long sizeMax) 

Source Link

Document

Sets the maximum allowed upload size.

Usage

From source file:org.jboss.dashboard.ui.controller.RequestMultipartWrapper.java

/**
 * Constructs a new MultipartRequest to handle the specified request,
 * saving any uploaded files to the given directory, and limiting the
 * upload size to the specified length.//from w  w w  . j av a  2  s .  com
 *
 * @param request       the servlet request.
 * @param saveDirectory the directory in which to save any uploaded files.
 * @param maxPostSize   the maximum size of the POST content.
 * @throws IOException if the uploaded content is larger than
 *                     <tt>maxPostSize</tt> or there's a problem reading or parsing the request.
 */
public RequestMultipartWrapper(HttpServletRequest request, String saveDirectory, int maxPostSize,
        String encoding) throws IOException {
    super(request);
    this.privateDir = saveDirectory;
    this.encoding = encoding;

    DiskFileItemFactory factory = new DiskFileItemFactory();

    // factory.setSizeThreshold(yourMaxMemorySize);

    if (privateDir != null) {
        File dir = new File(privateDir);
        if (dir.isDirectory() && dir.canWrite()) {
            factory.setRepository(dir);
        } else {
            log.warn("Directory " + privateDir + " is not valid or permissions to write not granted");
        }
    }

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(maxPostSize);

    List<FileItem> items = null;
    try {
        items = upload.parseRequest(request);
    } catch (FileUploadException e) {
        throw new IOException("Error parsing multipart in URI" + request.getRequestURI(), e);
    }

    if (items != null) {
        for (FileItem item : items) {
            if (item.isFormField()) {
                addFormField(item);
            } else {
                try {
                    addUploadedFile(item);
                } catch (Exception e) {
                    throw new IOException("Error parsing multipart item " + item.getName(), e);
                }
            }
        }
    }

    Enumeration<String> paramNames = request.getParameterNames();
    while (paramNames.hasMoreElements()) {
        String paramName = paramNames.nextElement();
        List<String> paramValues = Arrays.asList(request.getParameter(paramName));
        requestParameters.put(paramName, paramValues);
    }
}

From source file:org.jbpm.formModeler.service.bb.mvc.controller.RequestMultipartWrapper.java

/**
 * Constructs a new MultipartRequest to handle the specified request,
 * saving any uploaded files to the given directory, and limiting the
 * upload size to the specified length./* w ww.ja  v  a2 s. com*/
 *
 * @param request       the servlet request.
 * @param saveDirectory the directory in which to save any uploaded files.
 * @param maxPostSize   the maximum size of the POST content.
 * @throws java.io.IOException if the uploaded content is larger than
 *                     <tt>maxPostSize</tt> or there's a problem reading or parsing the request.
 */
public RequestMultipartWrapper(HttpServletRequest request, String saveDirectory, int maxPostSize,
        String encoding) throws IOException {
    super(request);
    this.privateDir = saveDirectory;
    this.encoding = encoding;

    DiskFileItemFactory factory = new DiskFileItemFactory();

    // factory.setSizeThreshold(yourMaxMemorySize);

    if (privateDir != null) {
        File dir = new File(privateDir);
        if (dir.isDirectory() && dir.canWrite()) {
            factory.setRepository(dir);
        } else {
            log.warn("Directory " + privateDir + " is not valid or permissions to write not granted");
        }
    }

    ServletFileUpload upload = new ServletFileUpload(factory);

    upload.setSizeMax(maxPostSize);

    List items = null;
    try {
        items = upload.parseRequest(request);
    } catch (FileUploadException e) {
        throw new IOException("Error parsing multipart in URI" + request.getRequestURI(), e);
    }

    if (items != null) {
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (item.isFormField()) {
                addFormField(item);
            } else {
                try {
                    addUploadedFile(item);
                } catch (Exception e) {
                    throw new IOException("Error parsing multipart item " + item.getName(), e);
                }
            }
        }
    }
}

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);
    if (fileSizeMax != NO_LIMIT_FILE_SIZE_MAX)
        sfu.setFileSizeMax(fileSizeMax);
    if (servletHeaderencoding != null)
        sfu.setHeaderEncoding(servletHeaderencoding);
    if (servletProgressListener != null)
        sfu.setProgressListener(servletProgressListener);

    return sfu;/*w  w  w . ja va  2  s .c  om*/
}

From source file:org.jlibrary.web.servlet.JLibraryForwardServlet.java

private void upload(HttpServletRequest req, HttpServletResponse resp) {

    ServletFileUpload upload = new ServletFileUpload();
    boolean sizeExceeded = false;
    String repositoryName = req.getParameter("repository");
    ConfigurationService conf = (ConfigurationService) context.getBean("template");
    upload.setSizeMax(conf.getOperationInputBandwidth());

    try {//w ww  .j a  v a2s  .  com
        params = new HashMap();
        FileItemIterator iter = upload.getItemIterator(req);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            InputStream stream = item.openStream();
            if (item.isFormField()) {
                params.put(item.getFieldName(), Streams.asString(stream));
            } else {
                params.put("filename", item.getName());
                uploadDocumentStructure(req, resp, repositoryName, stream);
            }
        }
    } catch (SizeLimitExceededException e) {
        sizeExceeded = true;
        if (repositoryName == null || "".equals(repositoryName)) {
            repositoryName = (String) params.get("repository");
        }
        logErrorAndForward(req, resp, repositoryName, e, "Bandwith exceeded");
    } catch (FileUploadException e) {
        logErrorAndForward(req, resp, repositoryName, e, "There was a problem uploading the document.");
    } catch (IOException e) {
        logErrorAndForward(req, resp, repositoryName, e, "There was a problem uploading the document.");
    } catch (Exception t) {
        logErrorAndForward(req, resp, repositoryName, t, "There was a problem uploading the document.");
    }

}

From source file:org.ldp4j.apps.ldp4ro.servlets.FileUploaderServlet.java

private ServletFileUpload getFileItemFactory() {

    Config config = ConfigManager.getAppConfig();

    // configures upload settings
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // sets memory threshold - beyond which files are stored in disk
    factory.setSizeThreshold(config.getInt(MEMORY_THRESHOULD));

    // sets temporary location to store files
    File tempUploadDir = new File(System.getProperty("java.io.tmpdir"));
    if (!tempUploadDir.exists()) {
        tempUploadDir.mkdir();/* ww  w  .  j av  a  2  s.c  om*/
    }
    factory.setRepository(tempUploadDir);

    ServletFileUpload upload = new ServletFileUpload(factory);

    // sets maximum size of upload file
    upload.setFileSizeMax(config.getLong(MAX_FILE_SIZE));

    // sets maximum size of request (include file + form data)
    upload.setSizeMax(config.getLong(MAX_REQUEST_SIZE));

    return upload;

}

From source file:org.linagora.linshare.view.tapestry.services.impl.MyMultipartDecoderImpl.java

protected ServletFileUpload createFileUpload() {
    ServletFileUpload upload = new ServletFileUpload(fileItemFactory);

    // set maximum file upload size
    upload.setSizeMax(-1);
    upload.setFileSizeMax(-1);//ww  w  .  jav a 2 s.  c  o  m

    ProgressListener progressListener = new ProgressListener() {
        private long megaBytes = -1;

        public void update(long pBytesRead, long pContentLength, int pItems) {
            long mBytes = pBytesRead / 1000000;
            if (megaBytes == mBytes) {
                return;
            }
            megaBytes = mBytes;

            if (logger.isDebugEnabled()) {
                logger.debug("We are currently reading item " + pItems);

                if (pContentLength == -1) {
                    logger.debug("So far, " + pBytesRead + " bytes have been read.");
                } else {
                    logger.debug("So far, " + pBytesRead + " of " + pContentLength + " bytes have been read.");
                }
            }
        }
    };

    upload.setProgressListener(progressListener);

    return upload;
}

From source file:org.megatome.frame2.front.FileUploadSupport.java

@SuppressWarnings("unchecked")
public static Map<String, Object> processMultipartRequest(final HttpServletRequest request)
        throws Frame2Exception {
    Map<String, Object> parameters = new HashMap<String, Object>();

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

    // Set factory constraints
    factory.setSizeThreshold(FileUploadConfig.getBufferSize());
    factory.setRepository(new File(FileUploadConfig.getFileTempDir()));

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

    // Set overall request size constraint
    upload.setSizeMax(FileUploadConfig.getMaxFileSize());

    List<FileItem> fileItems = null;
    try {/*from   ww  w .ja  va 2 s  . c  o m*/
        fileItems = upload.parseRequest(request);
    } catch (FileUploadException fue) {
        LOGGER.severe("File Upload Error", fue); //$NON-NLS-1$
        throw new Frame2Exception("File Upload Exception", fue); //$NON-NLS-1$
    }

    for (FileItem fi : fileItems) {
        String fieldName = fi.getFieldName();

        if (fi.isFormField()) {
            if (parameters.containsKey(fieldName)) {
                List<Object> tmpArray = new ArrayList<Object>();
                if (parameters.get(fieldName) instanceof String[]) {
                    String[] origValues = (String[]) parameters.get(fieldName);
                    for (int idx = 0; idx < origValues.length; idx++) {
                        tmpArray.add(origValues[idx]);
                    }
                    tmpArray.add(fi.getString());
                } else {
                    tmpArray.add(parameters.get(fieldName));
                    tmpArray.add(fi.getString());
                }
                String[] newValues = new String[tmpArray.size()];
                newValues = tmpArray.toArray(newValues);
                parameters.put(fieldName, newValues);
            } else {
                parameters.put(fieldName, fi.getString());
            }
        } else {
            if (parameters.containsKey(fieldName)) {
                List<Object> tmpArray = new ArrayList<Object>();
                if (parameters.get(fieldName) instanceof FileItem[]) {
                    FileItem[] origValues = (FileItem[]) parameters.get(fieldName);
                    for (int idx = 0; idx < origValues.length; idx++) {
                        tmpArray.add(origValues[idx]);
                    }
                    tmpArray.add(fi);
                } else {
                    tmpArray.add(parameters.get(fieldName));
                    tmpArray.add(fi);
                }
                FileItem[] newValues = new FileItem[tmpArray.size()];
                newValues = tmpArray.toArray(newValues);
                parameters.put(fieldName, newValues);
            } else {
                parameters.put(fieldName, fi);
            }
        }
    }

    return parameters;
}

From source file:org.mentawai.filter.FileUploadFilter.java

public String filter(InvocationChain chain) throws Exception {

    Action action = chain.getAction();

    Input input = action.getInput();/*from   w  w w . ja v a 2s .  c o  m*/

    HttpServletRequest req = getRequest(action);

    if (req == null) {

        throw new FilterException("I was not possible to fetch HttpServletRequest inside FileUploadFilter!!!");
    }

    try {

        if (ServletFileUpload.isMultipartContent(req)) {

            ServletFileUpload upload = new ServletFileUpload(factory);

            if (maxSizeToThrowError > 0)
                upload.setSizeMax(maxSizeToThrowError);

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

            Iterator<FileItem> iter = items.iterator();

            while (iter.hasNext()) {

                FileItem item = iter.next();

                String name = item.getFieldName();

                if (item.isFormField()) {

                    String value = item.getString();

                    Object currValue = input.getValue(name);

                    if (currValue == null) {

                        // adding for the first time... just add...

                        input.setValue(name, value);

                    } else if (currValue instanceof String) {

                        // we already have a String, so add as an array...

                        String s = (String) currValue;

                        String[] array = new String[2];

                        array[0] = s;
                        array[1] = value;

                        input.setValue(name, array);

                    } else if (currValue instanceof String[]) {

                        String[] s = (String[]) currValue;

                        String[] array = new String[s.length + 1];

                        System.arraycopy(s, 0, array, 0, s.length);

                        array[array.length - 1] = value;

                        input.setValue(name, array);

                    } else {
                        throw new FilterException("Error trying to add a field value: " + name);
                    }

                } else {

                    if (item.getSize() > 0) {

                        input.setValue(name, new FileUpload(item));

                    } else {

                        input.removeValue(name); // probably not necessary...
                    }
                }
            }
        }
    } catch (FileUploadException e) {
        throw new FilterException(e);
    }

    return chain.invoke();
}

From source file:org.mycore.frontend.editor.MCRRequestParameters.java

public MCRRequestParameters(HttpServletRequest req) {
    if (ServletFileUpload.isMultipartContent(req)) {
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(maxSize);
        upload.setHeaderEncoding("UTF-8");

        List<FileItem> items = null;

        try {/*from w w w  .ja  v  a 2s. c o  m*/
            items = upload.parseRequest(req);
        } catch (FileUploadException ex) {
            String msg = "Error while parsing http multipart/form-data request from file upload webpage";
            throw new MCRException(msg, ex);
        }

        for (Object item1 : items) {
            FileItem item = (FileItem) item1;

            String name = item.getFieldName();
            String value = null;

            if (item.isFormField()) {
                try {
                    value = item.getString("UTF-8");
                } catch (UnsupportedEncodingException ex) {
                    throw new MCRConfigurationException("UTF-8 is unsupported encoding !?", ex);
                }
            } else {
                value = item.getName();
            }

            if (!item.isFormField())
                filelist.add(item);

            if (value != null && value.trim().length() > 0 && !files.containsKey(name)) {
                if (!item.isFormField()) {
                    files.put(name, item);
                }

                String[] values = new String[1];
                values[0] = value;
                parameters.put(name, values);
            }
        }
    } else {
        for (Enumeration<String> e = req.getParameterNames(); e.hasMoreElements();) {
            String name = (String) e.nextElement();
            String[] values = req.getParameterValues(name);

            if (values != null && values.length > 0) {
                parameters.put(name, values);
            }
        }
    }
}

From source file:org.niord.core.repo.RepositoryService.java

/**
 * Parses the file upload request and returns the file items
 * @param request the request/*w w  w. j  a  v  a 2  s. co m*/
 * @return the file items
 */
public List<FileItem> parseFileUploadRequest(HttpServletRequest request) throws FileUploadException {
    FileItemFactory factory = newDiskFileItemFactory(servletContext);
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(fileUploadMaxSize);
    upload.setSizeMax(fileUploadMaxSize);
    return upload.parseRequest(request);
}