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

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

Introduction

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

Prototype

public long getSizeMax() 

Source Link

Document

Returns the maximum allowed upload size.

Usage

From source file:com.zimbra.cs.service.FileUploadServlet.java

public static Upload saveUpload(InputStream is, String filename, String contentType, String accountId,
        long limit) throws ServiceException, IOException {
    FileItem fi = null;/*www.  java2  s . c o  m*/
    boolean success = false;
    try {
        // store the fetched file as a normal upload
        ServletFileUpload upload = getUploader(limit);
        long sizeMax = upload.getSizeMax();
        fi = upload.getFileItemFactory().createItem("upload", contentType, false, filename);
        // sizeMax=-1 means "no limit"
        long size = ByteUtil.copy(is, true, fi.getOutputStream(), true, sizeMax < 0 ? sizeMax : sizeMax + 1);
        if (upload.getSizeMax() >= 0 && size > upload.getSizeMax()) {
            mLog.info("Exceeded maximum upload size of " + upload.getSizeMax() + " bytes");
            throw MailServiceException.UPLOAD_TOO_LARGE(filename, "upload too large");
        }

        Upload up = new Upload(accountId, fi);
        mLog.info("saveUpload(): received %s", up);
        synchronized (mPending) {
            mPending.put(up.uuid, up);
        }
        success = true;
        return up;
    } finally {
        if (!success && fi != null) {
            mLog.debug("saveUpload(): unsuccessful attempt.  Deleting %s", fi);
            fi.delete();
        }
    }
}

From source file:n3phele.backend.RepoProxy.java

@POST
@Path("{id}/upload/{bucket}")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response upload(@PathParam("id") Long id, @PathParam("bucket") String bucket,
        @QueryParam("name") String destination, @QueryParam("expires") long expires,
        @QueryParam("signature") String signature, @Context HttpServletRequest request)
        throws NotFoundException {
    Repository repo = Dao.repository().load(id);
    if (!checkTemporaryCredential(expires, signature, repo.getCredential().decrypt().getSecret(),
            bucket + ":" + destination)) {
        log.severe("Expired temporary authorization");
        throw new NotFoundException();
    }//  w w  w.  ja v a  2 s  .c  o  m

    try {
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iterator = upload.getItemIterator(request);
        log.info("FileSizeMax =" + upload.getFileSizeMax() + " SizeMax=" + upload.getSizeMax() + " Encoding "
                + upload.getHeaderEncoding());
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();

            if (item.isFormField()) {
                log.info("FieldName: " + item.getFieldName() + " value:" + Streams.asString(item.openStream()));
            } else {
                InputStream stream = item.openStream();
                log.warning("Got an uploaded file: " + item.getFieldName() + ", name = " + item.getName()
                        + " content " + item.getContentType());
                URI target = CloudStorage.factory().putObject(repo, stream, item.getContentType(), destination);
                Response.created(target).build();
            }
        }
    } catch (Exception e) {
        log.log(Level.WARNING, "Processing error", e);
    }

    return Response.status(Status.REQUEST_ENTITY_TOO_LARGE).build();
}

From source file:com.hillert.upload.web.ajax.AjaxFileUploadMultipartResolver.java

public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException {
    String encoding = determineEncoding(request);
    FileUpload fileUpload1 = prepareFileUpload(encoding); //renamed fileUpload to fileUpload1

    // Beginn of added code
    UploadListener listener = new UploadListener(request, 30);
    FileItemFactory factory = new MonitoredDiskFileItemFactory(listener);
    ServletFileUpload fileUpload = new ServletFileUpload(factory);
    fileUpload.setSizeMax(fileUpload1.getSizeMax());
    fileUpload.setHeaderEncoding(fileUpload1.getHeaderEncoding());
    //end of added code

    try {/*ww  w.  ja  v a  2  s.  com*/
        List fileItems = ((ServletFileUpload) fileUpload).parseRequest(request);
        MultipartParsingResult parsingResult = parseFileItems(fileItems, encoding);
        return new DefaultMultipartHttpServletRequest(request, parsingResult.getMultipartFiles(),
                parsingResult.getMultipartParameters());
    } catch (FileUploadBase.SizeLimitExceededException ex) {
        throw new MaxUploadSizeExceededException(fileUpload.getSizeMax(), ex);
    } catch (FileUploadException ex) {
        throw new MultipartException("Could not parse multipart servlet request", ex);
    }
}

From source file:com.zimbra.cs.service.FileUploadServlet.java

/**
 * This is used when handling a POST request generated by {@link ZMailbox#uploadContentAsStream}
 *
 * @param req/*w  w w  .  ja  v a 2  s .c  o  m*/
 * @param resp
 * @param fmt
 * @param acct
 * @param limitByFileUploadMaxSize
 * @return
 * @throws IOException
 * @throws ServiceException
 */
List<Upload> handlePlainUpload(HttpServletRequest req, HttpServletResponse resp, String fmt, Account acct,
        boolean limitByFileUploadMaxSize) throws IOException, ServiceException {
    // metadata is encoded in the response's HTTP headers
    ContentType ctype = new ContentType(req.getContentType());
    String contentType = ctype.getContentType(), filename = ctype.getParameter("name");
    if (filename == null) {
        filename = new ContentDisposition(req.getHeader("Content-Disposition")).getParameter("filename");
    }

    if (filename == null || filename.trim().equals("")) {
        mLog.info("Rejecting upload with no name.");
        drainRequestStream(req);
        sendResponse(resp, HttpServletResponse.SC_NO_CONTENT, fmt, null, null, null);
        return Collections.emptyList();
    }

    // Unescape the filename so it actually displays correctly
    filename = StringEscapeUtils.unescapeHtml(filename);

    // store the fetched file as a normal upload
    ServletFileUpload upload = getUploader2(limitByFileUploadMaxSize);
    FileItem fi = upload.getFileItemFactory().createItem("upload", contentType, false, filename);
    try {
        // write the upload to disk, but make sure not to exceed the permitted max upload size
        long size = ByteUtil.copy(req.getInputStream(), false, fi.getOutputStream(), true,
                upload.getSizeMax() * 3);
        if ((upload.getSizeMax() >= 0 /* -1 would mean "no limit" */) && (size > upload.getSizeMax())) {
            mLog.debug("handlePlainUpload(): deleting %s", fi);
            fi.delete();
            mLog.info("Exceeded maximum upload size of " + upload.getSizeMax() + " bytes: " + acct.getId());
            drainRequestStream(req);
            sendResponse(resp, HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, fmt, null, null, null);
            return Collections.emptyList();
        }
    } catch (IOException ioe) {
        mLog.warn("Unable to store upload.  Deleting %s", fi, ioe);
        fi.delete();
        drainRequestStream(req);
        sendResponse(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, fmt, null, null, null);
        return Collections.emptyList();
    }
    List<FileItem> items = new ArrayList<FileItem>(1);
    items.add(fi);

    Upload up = new Upload(acct.getId(), fi, filename);
    mLog.info("Received plain: %s", up);
    synchronized (mPending) {
        mPending.put(up.uuid, up);
    }

    List<Upload> uploads = Arrays.asList(up);
    sendResponse(resp, HttpServletResponse.SC_OK, fmt, null, uploads, items);
    return uploads;
}

From source file:com.zimbra.cs.service.FileUploadServlet.java

@SuppressWarnings("unchecked")
List<Upload> handleMultipartUpload(HttpServletRequest req, HttpServletResponse resp, String fmt, Account acct,
        boolean limitByFileUploadMaxSize, AuthToken at, boolean csrfCheckComplete)
        throws IOException, ServiceException {
    List<FileItem> items = null;
    String reqId = null;/*  ww w.  ja v a2 s . c  om*/

    ServletFileUpload upload = getUploader2(limitByFileUploadMaxSize);
    try {
        items = upload.parseRequest(req);

        if (!csrfCheckComplete && !CsrfUtil.checkCsrfInMultipartFileUpload(items, at)) {
            drainRequestStream(req);
            mLog.info("CSRF token validation failed for account: %s, Auth token is CSRF enabled",
                    acct.getName());
            sendResponse(resp, HttpServletResponse.SC_UNAUTHORIZED, fmt, null, null, items);
            return Collections.emptyList();
        }
    } catch (FileUploadBase.SizeLimitExceededException e) {
        // at least one file was over max allowed size
        mLog.info("Exceeded maximum upload size of " + upload.getSizeMax() + " bytes: " + e);
        drainRequestStream(req);
        sendResponse(resp, HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, fmt, reqId, null, items);
        return Collections.emptyList();
    } catch (FileUploadBase.InvalidContentTypeException e) {
        // at least one file was of a type not allowed
        mLog.info("File upload failed", e);
        drainRequestStream(req);
        sendResponse(resp, HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, fmt, reqId, null, items);
        return Collections.emptyList();
    } catch (FileUploadException e) {
        // parse of request failed for some other reason
        mLog.info("File upload failed", e);
        drainRequestStream(req);
        sendResponse(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, fmt, reqId, null, items);
        return Collections.emptyList();
    }

    String charset = "utf-8";
    LinkedList<String> names = new LinkedList<String>();
    HashMap<FileItem, String> filenames = new HashMap<FileItem, String>();
    if (items != null) {
        for (Iterator<FileItem> it = items.iterator(); it.hasNext();) {
            FileItem fi = it.next();
            if (fi == null)
                continue;

            if (fi.isFormField()) {
                if (fi.getFieldName().equals("requestId")) {
                    // correlate this file upload session's request and response
                    reqId = fi.getString();
                } else if (fi.getFieldName().equals("_charset_") && !fi.getString().equals("")) {
                    // get the form value charset, if specified
                    charset = fi.getString();
                } else if (fi.getFieldName().startsWith("filename")) {
                    // allow a client to explicitly provide filenames for the uploads
                    names.clear();
                    String value = fi.getString(charset);
                    if (!Strings.isNullOrEmpty(value)) {
                        for (String name : value.split("\n")) {
                            names.add(name.trim());
                        }
                    }
                }
                // strip form fields out of the list of uploads
                it.remove();
            } else {
                if (fi.getName() == null || fi.getName().trim().equals("")) {
                    it.remove();
                } else {
                    filenames.put(fi, names.isEmpty() ? null : names.remove());
                }
            }
        }
    }

    // restrict requestId value for safety due to later use in javascript
    if (reqId != null && reqId.length() != 0) {
        if (!ALLOWED_REQUESTID_CHARS.matcher(reqId).matches()) {
            mLog.info("Rejecting upload with invalid chars in reqId: %s", reqId);
            sendResponse(resp, HttpServletResponse.SC_BAD_REQUEST, fmt, null, null, items);
            return Collections.emptyList();
        }
    }

    // empty upload is not a "success"
    if (items == null || items.isEmpty()) {
        mLog.info("No data in upload for reqId: %s", reqId);
        sendResponse(resp, HttpServletResponse.SC_NO_CONTENT, fmt, reqId, null, items);
        return Collections.emptyList();
    }

    // cache the uploaded files in the hash and construct the list of upload IDs
    List<Upload> uploads = new ArrayList<Upload>(items.size());
    for (FileItem fi : items) {
        String name = filenames.get(fi);
        if (name == null || name.trim().equals(""))
            name = fi.getName();
        Upload up = new Upload(acct.getId(), fi, name);

        mLog.info("Received multipart: %s", up);
        synchronized (mPending) {
            mPending.put(up.uuid, up);
        }
        uploads.add(up);
    }

    sendResponse(resp, HttpServletResponse.SC_OK, fmt, reqId, uploads, items);
    return uploads;
}

From source file:org.apache.tapestry5.upload.internal.services.MultipartDecoderImplTest.java

@Test
public void create_file_upload_gets_configuration_from_symbols() throws Exception {
    MultipartDecoderImpl decoder = new MultipartDecoderImpl(fileItemFactory, 7777, 6666, CHARSET);

    replay();/*from  w ww.ja v  a 2 s . c  o  m*/

    ServletFileUpload servletFileUpload = decoder.createFileUpload();
    assertNotNull(servletFileUpload);

    verify();

    assertEquals(servletFileUpload.getFileSizeMax(), 6666);
    assertEquals(servletFileUpload.getSizeMax(), 7777);
}

From source file:org.sakaiproject.util.RequestFilter.java

/**
 * if the filter is configured to parse file uploads, AND the request is multipart (typically a file upload), then parse the
 * request.//from w  w  w . j  av  a  2 s . com
 *
 * @return If there is a file upload, and the filter handles it, return the wrapped request that has the results of the parsed
 *         file upload. Parses the files using Apache commons-fileuplaod. Exposes the results through a wrapped request. Files
 *         are available like: fileItem = (FileItem) request.getAttribute("myHtmlFileUploadId");
 */
protected HttpServletRequest handleFileUpload(HttpServletRequest req, HttpServletResponse resp,
        List<FileItem> tempFiles) throws ServletException, UnsupportedEncodingException {
    if (!m_uploadEnabled || !ServletFileUpload.isMultipartContent(req)
            || req.getAttribute(ATTR_UPLOADS_DONE) != null) {
        return req;
    }

    // mark that the uploads have been parsed, so they aren't parsed again on this request
    req.setAttribute(ATTR_UPLOADS_DONE, ATTR_UPLOADS_DONE);

    // Result - map that will be created of request parameters,
    // parsed parameters, and uploaded files
    Map map = new HashMap();

    // parse using commons-fileupload

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

    // set the factory parameters: the temp dir and the keep-in-memory-if-smaller threshold
    if (m_uploadTempDir != null)
        factory.setRepository(new File(m_uploadTempDir));
    if (m_uploadThreshold > 0)
        factory.setSizeThreshold(m_uploadThreshold);

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

    // set the encoding
    String encoding = req.getCharacterEncoding();
    if (encoding != null && encoding.length() > 0)
        upload.setHeaderEncoding(encoding);

    // set the max upload size
    long uploadMax = -1;
    if (m_uploadMaxSize > 0)
        uploadMax = m_uploadMaxSize;

    // check for request-scoped override to upload.max (value in megs)
    String override = req.getParameter(CONFIG_UPLOAD_MAX);
    if (override != null) {
        try {
            // get the max in bytes
            uploadMax = Long.parseLong(override) * 1024L * 1024L;
        } catch (NumberFormatException e) {
            M_log.warn(CONFIG_UPLOAD_MAX + " set to non-numeric: " + override);
        }
    }

    // limit to the ceiling
    if (uploadMax > m_uploadCeiling) {
        /**
         * KNL-602 This is the expected behaviour of the request filter honouring the globaly configured
         * value -DH
         */
        M_log.debug("Upload size exceeds ceiling: " + ((uploadMax / 1024L) / 1024L) + " > "
                + ((m_uploadCeiling / 1024L) / 1024L) + " megs");

        uploadMax = m_uploadCeiling;
    }

    // to let commons-fileupload throw the exception on over-max, and also halt full processing of input fields
    if (!m_uploadContinue) {
        // TODO: when we switch to commons-fileupload 1.2
        // // either per file or overall request, as configured
        // if (m_uploadMaxPerFile)
        // {
        // upload.setFileSizeMax(uploadMax);
        // }
        // else
        // {
        // upload.setSizeMax(uploadMax);
        // }

        upload.setSizeMax(uploadMax);
    }

    try {
        // parse multipart encoded parameters
        boolean uploadOk = true;
        List list = upload.parseRequest(req);
        for (int i = 0; i < list.size(); i++) {
            FileItem item = (FileItem) list.get(i);

            if (item.isFormField()) {
                String str = item.getString(encoding);

                Object obj = map.get(item.getFieldName());
                if (obj == null) {
                    map.put(item.getFieldName(), new String[] { str });
                } else if (obj instanceof String[]) {
                    String[] old_vals = (String[]) obj;
                    String[] values = new String[old_vals.length + 1];
                    for (int i1 = 0; i1 < old_vals.length; i1++) {
                        values[i1] = old_vals[i1];
                    }
                    values[values.length - 1] = str;
                    map.put(item.getFieldName(), values);
                } else if (obj instanceof String) {
                    String[] values = new String[2];
                    values[0] = (String) obj;
                    values[1] = str;
                    map.put(item.getFieldName(), values);
                }
            } else {
                // collect it for delete at the end of the request
                tempFiles.add(item);

                // check the max, unless we are letting commons-fileupload throw exception on max exceeded
                // Note: the continue option assumes the max is per-file, not overall.
                if (m_uploadContinue && (item.getSize() > uploadMax)) {
                    uploadOk = false;

                    M_log.info("Upload size limit exceeded: " + ((uploadMax / 1024L) / 1024L));

                    req.setAttribute("upload.status", "size_limit_exceeded");
                    // TODO: for 1.2 commons-fileupload, switch this to a FileSizeLimitExceededException
                    req.setAttribute("upload.exception",
                            new FileUploadBase.SizeLimitExceededException("", item.getSize(), uploadMax));
                    req.setAttribute("upload.limit", Long.valueOf((uploadMax / 1024L) / 1024L));
                } else {
                    req.setAttribute(item.getFieldName(), item);
                }
            }
        }

        // unless we had an upload file that exceeded max, set the upload status to "ok"
        if (uploadOk) {
            req.setAttribute("upload.status", "ok");
        }
    } catch (FileUploadBase.SizeLimitExceededException ex) {
        M_log.info("Upload size limit exceeded: " + ((upload.getSizeMax() / 1024L) / 1024L));

        // DON'T throw an exception, instead note the exception
        // so that the tool down-the-line can handle the problem
        req.setAttribute("upload.status", "size_limit_exceeded");
        req.setAttribute("upload.exception", ex);
        req.setAttribute("upload.limit", Long.valueOf((upload.getSizeMax() / 1024L) / 1024L));
    }
    // TODO: put in for commons-fileupload 1.2
    // catch (FileUploadBase.FileSizeLimitExceededException ex)
    // {
    // M_log.info("Upload size limit exceeded: " + ((upload.getFileSizeMax() / 1024L) / 1024L));
    //
    // // DON'T throw an exception, instead note the exception
    // // so that the tool down-the-line can handle the problem
    // req.setAttribute("upload.status", "size_limit_exceeded");
    // req.setAttribute("upload.exception", ex);
    // req.setAttribute("upload.limit", new Long((upload.getFileSizeMax() / 1024L) / 1024L));
    // }
    catch (FileUploadException ex) {
        M_log.info("Unexpected exception in upload parsing", ex);
        req.setAttribute("upload.status", "exception");
        req.setAttribute("upload.exception", ex);
    }

    // add any parameters that were in the URL - make sure to get multiples
    for (Enumeration e = req.getParameterNames(); e.hasMoreElements();) {
        String name = (String) e.nextElement();
        String[] values = req.getParameterValues(name);
        map.put(name, values);
    }

    // return a wrapped response that exposes the parsed parameters and files
    return new WrappedRequestFileUpload(req, map);
}