Example usage for org.apache.commons.fileupload.util LimitedInputStream LimitedInputStream

List of usage examples for org.apache.commons.fileupload.util LimitedInputStream LimitedInputStream

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.util LimitedInputStream LimitedInputStream.

Prototype

public LimitedInputStream(InputStream pIn, long pSizeMax) 

Source Link

Document

Creates a new instance.

Usage

From source file:org.apache.myfaces.webapp.filter.portlet.PortletChacheFileSizeErrorsFileUpload.java

/**
 * Similar to {@link ServletFileUpload#parseRequest(RequestContext)} but will
 * catch and swallow FileSizeLimitExceededExceptions in order to return as
 * many usable items as possible.//from  w w  w.ja v  a2 s. co  m
 * 
 * @param fileUpload
 * @return List of {@link FileItem} excluding any that exceed max size.  
 * @throws FileUploadException
 */
public List parseRequestCatchingFileSizeErrors(ActionRequest request, FileUpload fileUpload)
        throws FileUploadException {
    try {
        List items = new ArrayList();

        // The line below throws a SizeLimitExceededException (wrapped by a
        // FileUploadIOException) if the request is longer than the max size
        // allowed by fileupload requests (FileUpload.getSizeMax)
        // But note that if the request does not send proper headers this check
        // just will not do anything and we still have to check it again.
        FileItemIterator iter = fileUpload.getItemIterator(new PortletRequestContext(request));

        FileItemFactory fac = fileUpload.getFileItemFactory();
        if (fac == null) {
            throw new NullPointerException("No FileItemFactory has been set.");
        }

        long maxFileSize = this.getFileSizeMax();
        long maxSize = this.getSizeMax();
        boolean checkMaxSize = false;

        if (maxFileSize == -1L) {
            //The max allowed file size should be approximate to the maxSize
            maxFileSize = maxSize;
        }
        if (maxSize != -1L) {
            checkMaxSize = true;
        }

        while (iter.hasNext()) {
            final FileItemStream item = iter.next();
            FileItem fileItem = fac.createItem(item.getFieldName(), item.getContentType(), item.isFormField(),
                    item.getName());

            long allowedLimit = 0L;
            try {
                if (maxFileSize != -1L || checkMaxSize) {
                    if (checkMaxSize) {
                        allowedLimit = maxSize > maxFileSize ? maxFileSize : maxSize;
                    } else {
                        //Just put the limit
                        allowedLimit = maxFileSize;
                    }

                    long contentLength = getContentLength(item.getHeaders());

                    //If we have a content length in the header we can use it
                    if (contentLength != -1L && contentLength > allowedLimit) {
                        throw new FileUploadIOException(new FileSizeLimitExceededException(
                                "The field " + item.getFieldName() + " exceeds its maximum permitted "
                                        + " size of " + allowedLimit + " characters.",
                                contentLength, allowedLimit));
                    }

                    //Otherwise we must limit the input as it arrives (NOTE: we cannot rely
                    //on commons upload to throw this exception as it will close the 
                    //underlying stream
                    final InputStream itemInputStream = item.openStream();

                    InputStream limitedInputStream = new LimitedInputStream(itemInputStream, allowedLimit) {
                        protected void raiseError(long pSizeMax, long pCount) throws IOException {
                            throw new FileUploadIOException(new FileSizeLimitExceededException(
                                    "The field " + item.getFieldName() + " exceeds its maximum permitted "
                                            + " size of " + pSizeMax + " characters.",
                                    pCount, pSizeMax));
                        }
                    };

                    //Copy from the limited stream
                    long bytesCopied = Streams.copy(limitedInputStream, fileItem.getOutputStream(), true);

                    // Decrement the bytesCopied values from maxSize, so the next file copied 
                    // takes into account this value when allowedLimit var is calculated
                    // Note the invariant before the line is maxSize >= bytesCopied, since if this
                    // is not true a FileUploadIOException is thrown first.
                    maxSize -= bytesCopied;
                } else {
                    //We can just copy the data
                    Streams.copy(item.openStream(), fileItem.getOutputStream(), true);
                }
            } catch (FileUploadIOException e) {
                try {
                    throw (FileUploadException) e.getCause();
                } catch (FileUploadBase.FileSizeLimitExceededException se) {
                    request.setAttribute("org.apache.myfaces.custom.fileupload.exception",
                            "fileSizeLimitExceeded");
                    String fieldName = fileItem.getFieldName();
                    request.setAttribute("org.apache.myfaces.custom.fileupload." + fieldName + ".maxSize",
                            new Integer((int) allowedLimit));
                }
            } catch (IOException e) {
                throw new IOFileUploadException("Processing of " + FileUploadBase.MULTIPART_FORM_DATA
                        + " request failed. " + e.getMessage(), e);
            }
            if (fileItem instanceof FileItemHeadersSupport) {
                final FileItemHeaders fih = item.getHeaders();
                ((FileItemHeadersSupport) fileItem).setHeaders(fih);
            }
            if (fileItem != null) {
                items.add(fileItem);
            }
        }
        return items;
    } catch (FileUploadIOException e) {
        throw (FileUploadException) e.getCause();
    } catch (IOException e) {
        throw new FileUploadException(e.getMessage(), e);
    }
}

From source file:org.apache.myfaces.webapp.filter.servlet.ServletChacheFileSizeErrorsFileUpload.java

/**
 * Similar to {@link ServletFileUpload#parseRequest(RequestContext)} but will
 * catch and swallow FileSizeLimitExceededExceptions in order to return as
 * many usable items as possible./*from   w  ww  .  j  a  v  a 2s  .  c  o  m*/
 * 
 * @param fileUpload
 * @return List of {@link FileItem} excluding any that exceed max size.  
 * @throws FileUploadException
 */
public List parseRequestCatchingFileSizeErrors(HttpServletRequest request, FileUpload fileUpload)
        throws FileUploadException {
    try {
        List items = new ArrayList();

        // The line below throws a SizeLimitExceededException (wrapped by a
        // FileUploadIOException) if the request is longer than the max size
        // allowed by fileupload requests (FileUpload.getSizeMax)
        // But note that if the request does not send proper headers this check
        // just will not do anything and we still have to check it again.
        FileItemIterator iter = fileUpload.getItemIterator(new ServletRequestContext(request));

        FileItemFactory fac = fileUpload.getFileItemFactory();
        if (fac == null) {
            throw new NullPointerException("No FileItemFactory has been set.");
        }

        long maxFileSize = this.getFileSizeMax();
        long maxSize = this.getSizeMax();
        boolean checkMaxSize = false;

        if (maxFileSize == -1L) {
            //The max allowed file size should be approximate to the maxSize
            maxFileSize = maxSize;
        }
        if (maxSize != -1L) {
            checkMaxSize = true;
        }

        while (iter.hasNext()) {
            final FileItemStream item = iter.next();
            FileItem fileItem = fac.createItem(item.getFieldName(), item.getContentType(), item.isFormField(),
                    item.getName());

            long allowedLimit = 0L;
            try {
                if (maxFileSize != -1L || checkMaxSize) {
                    if (checkMaxSize) {
                        allowedLimit = maxSize > maxFileSize ? maxFileSize : maxSize;
                    } else {
                        //Just put the limit
                        allowedLimit = maxFileSize;
                    }

                    long contentLength = getContentLength(item.getHeaders());

                    //If we have a content length in the header we can use it
                    if (contentLength != -1L && contentLength > allowedLimit) {
                        throw new FileUploadIOException(new FileSizeLimitExceededException(
                                "The field " + item.getFieldName() + " exceeds its maximum permitted "
                                        + " size of " + allowedLimit + " characters.",
                                contentLength, allowedLimit));
                    }

                    //Otherwise we must limit the input as it arrives (NOTE: we cannot rely
                    //on commons upload to throw this exception as it will close the 
                    //underlying stream
                    final InputStream itemInputStream = item.openStream();

                    InputStream limitedInputStream = new LimitedInputStream(itemInputStream, allowedLimit) {
                        protected void raiseError(long pSizeMax, long pCount) throws IOException {
                            throw new FileUploadIOException(new FileSizeLimitExceededException(
                                    "The field " + item.getFieldName() + " exceeds its maximum permitted "
                                            + " size of " + pSizeMax + " characters.",
                                    pCount, pSizeMax));
                        }
                    };

                    //Copy from the limited stream
                    long bytesCopied = Streams.copy(limitedInputStream, fileItem.getOutputStream(), true);

                    // Decrement the bytesCopied values from maxSize, so the next file copied 
                    // takes into account this value when allowedLimit var is calculated
                    // Note the invariant before the line is maxSize >= bytesCopied, since if this
                    // is not true a FileUploadIOException is thrown first.
                    maxSize -= bytesCopied;
                } else {
                    //We can just copy the data
                    Streams.copy(item.openStream(), fileItem.getOutputStream(), true);
                }
            } catch (FileUploadIOException e) {
                try {
                    throw (FileUploadException) e.getCause();
                } catch (FileUploadBase.FileSizeLimitExceededException se) {
                    request.setAttribute("org.apache.myfaces.custom.fileupload.exception",
                            "fileSizeLimitExceeded");
                    String fieldName = fileItem.getFieldName();
                    request.setAttribute("org.apache.myfaces.custom.fileupload." + fieldName + ".maxSize",
                            new Integer((int) allowedLimit));
                }
            } catch (IOException e) {
                throw new IOFileUploadException("Processing of " + FileUploadBase.MULTIPART_FORM_DATA
                        + " request failed. " + e.getMessage(), e);
            }
            if (fileItem instanceof FileItemHeadersSupport) {
                final FileItemHeaders fih = item.getHeaders();
                ((FileItemHeadersSupport) fileItem).setHeaders(fih);
            }
            if (fileItem != null) {
                items.add(fileItem);
            }
        }
        return items;
    } catch (FileUploadIOException e) {
        throw (FileUploadException) e.getCause();
    } catch (IOException e) {
        throw new FileUploadException(e.getMessage(), e);
    }
}

From source file:org.jahia.ajax.gwt.content.server.GWTFileManagerUploadServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    SettingsBean settingsBean = SettingsBean.getInstance();
    final long fileSizeLimit = settingsBean.getJahiaFileUploadMaxSize();
    upload.setHeaderEncoding("UTF-8");
    Map<String, FileItem> uploads = new HashMap<String, FileItem>();
    String location = null;/*www .java 2 s . c  o m*/
    String type = null;
    boolean unzip = false;
    response.setContentType("text/plain; charset=" + settingsBean.getCharacterEncoding());
    final PrintWriter printWriter = response.getWriter();
    try {
        FileItemIterator itemIterator = upload.getItemIterator(request);
        FileSizeLimitExceededException sizeLimitExceededException = null;
        while (itemIterator.hasNext()) {
            final FileItemStream item = itemIterator.next();
            if (sizeLimitExceededException != null) {
                continue;
            }
            FileItem fileItem = factory.createItem(item.getFieldName(), item.getContentType(),
                    item.isFormField(), item.getName());
            long contentLength = getContentLength(item.getHeaders());

            // If we have a content length in the header we can use it
            if (fileSizeLimit > 0 && contentLength != -1L && contentLength > fileSizeLimit) {
                throw new FileSizeLimitExceededException("The field " + item.getFieldName()
                        + " exceeds its maximum permitted size of " + fileSizeLimit + " bytes.", contentLength,
                        fileSizeLimit);
            }
            InputStream itemStream = item.openStream();

            InputStream limitedInputStream = null;
            try {
                limitedInputStream = fileSizeLimit > 0 ? new LimitedInputStream(itemStream, fileSizeLimit) {

                    @Override
                    protected void raiseError(long pSizeMax, long pCount) throws IOException {
                        throw new FileUploadIOException(new FileSizeLimitExceededException(
                                "The field " + item.getFieldName() + " exceeds its maximum permitted size of "
                                        + fileSizeLimit + " bytes.",
                                pCount, pSizeMax));
                    }
                } : itemStream;

                Streams.copy(limitedInputStream, fileItem.getOutputStream(), true);
            } catch (FileUploadIOException e) {
                if (e.getCause() instanceof FileSizeLimitExceededException) {
                    if (sizeLimitExceededException == null) {
                        sizeLimitExceededException = (FileSizeLimitExceededException) e.getCause();
                    }
                } else {
                    throw e;
                }
            } finally {
                IOUtils.closeQuietly(limitedInputStream);
            }

            if ("unzip".equals(fileItem.getFieldName())) {
                unzip = true;
            } else if ("uploadLocation".equals(fileItem.getFieldName())) {
                location = fileItem.getString("UTF-8");
            } else if ("asyncupload".equals(fileItem.getFieldName())) {
                String name = fileItem.getName();
                if (name.trim().length() > 0) {
                    uploads.put(extractFileName(name, uploads), fileItem);
                }
                type = "async";
            } else if (!fileItem.isFormField() && fileItem.getFieldName().startsWith("uploadedFile")) {
                String name = fileItem.getName();
                if (name.trim().length() > 0) {
                    uploads.put(extractFileName(name, uploads), fileItem);
                }
                type = "sync";
            }
        }
        if (sizeLimitExceededException != null) {
            throw sizeLimitExceededException;
        }
    } catch (FileUploadBase.FileSizeLimitExceededException e) {
        printWriter.write("UPLOAD-SIZE-ISSUE: " + getSizeLimitErrorMessage(fileSizeLimit, e, request) + "\n");
        return;
    } catch (FileUploadIOException e) {
        if (e.getCause() != null && (e.getCause() instanceof FileSizeLimitExceededException)) {
            printWriter.write("UPLOAD-SIZE-ISSUE: " + getSizeLimitErrorMessage(fileSizeLimit,
                    (FileSizeLimitExceededException) e.getCause(), request) + "\n");
        } else {
            logger.error("UPLOAD-ISSUE", e);
            printWriter.write("UPLOAD-ISSUE: " + e.getLocalizedMessage() + "\n");
        }
        return;
    } catch (FileUploadException e) {
        logger.error("UPLOAD-ISSUE", e);
        printWriter.write("UPLOAD-ISSUE: " + e.getLocalizedMessage() + "\n");
        return;
    }

    if (type == null || type.equals("sync")) {
        response.setContentType("text/plain");

        final JahiaUser user = (JahiaUser) request.getSession().getAttribute(Constants.SESSION_USER);

        final List<String> pathsToUnzip = new ArrayList<String>();
        for (String fileName : uploads.keySet()) {
            final FileItem fileItem = uploads.get(fileName);
            try {
                StringBuilder name = new StringBuilder(fileName);
                final int saveResult = saveToJcr(user, fileItem, location, name);
                switch (saveResult) {
                case OK:
                    if (unzip && fileName.toLowerCase().endsWith(".zip")) {
                        pathsToUnzip.add(
                                new StringBuilder(location).append("/").append(name.toString()).toString());
                    }
                    printWriter.write("OK: " + UriUtils.encode(name.toString()) + "\n");
                    break;
                case EXISTS:
                    storeUploadedFile(request.getSession().getId(), fileItem);
                    printWriter.write("EXISTS: " + UriUtils.encode(fileItem.getFieldName()) + " "
                            + UriUtils.encode(fileItem.getName()) + " " + UriUtils.encode(fileName) + "\n");
                    break;
                case READONLY:
                    printWriter.write("READONLY: " + UriUtils.encode(fileItem.getFieldName()) + "\n");
                    break;
                default:
                    printWriter.write("UPLOAD-FAILED: " + UriUtils.encode(fileItem.getFieldName()) + "\n");
                    break;
                }
            } catch (IOException e) {
                logger.error("Upload failed for file \n", e);
            } finally {
                fileItem.delete();
            }
        }

        // direct blocking unzip
        if (unzip && pathsToUnzip.size() > 0) {
            try {
                ZipHelper zip = ZipHelper.getInstance();
                //todo : in which workspace do we upload ?
                zip.unzip(pathsToUnzip, true, JCRSessionFactory.getInstance().getCurrentUserSession(),
                        (Locale) request.getSession().getAttribute(Constants.SESSION_UI_LOCALE));
            } catch (RepositoryException e) {
                logger.error("Auto-unzipping failed", e);
            } catch (GWTJahiaServiceException e) {
                logger.error("Auto-unzipping failed", e);
            }
        }
    } else {
        response.setContentType("text/html");
        for (FileItem fileItem : uploads.values()) {
            storeUploadedFile(request.getSession().getId(), fileItem);
            printWriter.write("<html><body>");
            printWriter.write("<div id=\"uploaded\" key=\"" + fileItem.getName() + "\" name=\""
                    + fileItem.getName() + "\"></div>\n");
            printWriter.write("</body></html>");
        }
    }
}