Example usage for org.apache.commons.fileupload FileItem getOutputStream

List of usage examples for org.apache.commons.fileupload FileItem getOutputStream

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItem getOutputStream.

Prototype

OutputStream getOutputStream() throws IOException;

Source Link

Document

Returns an java.io.OutputStream OutputStream that can be used for storing the contents of the file.

Usage

From source file:org.apache.hupa.server.preferences.InImapUserPreferencesStorage.java

/**
 * Right now, using the same approach present in upload attachments to create the attachment
 *//*  ww  w .  ja va 2  s  . c om*/
private static FileItem createPreferencesFileItem(InputStream is, String filename, String contentType)
        throws IOException {
    FileItemFactory f = new DiskFileItemFactory();
    FileItem item = f.createItem(filename, contentType, false, filename);
    UploadServlet.copyFromInputStreamToOutputStream(is, item.getOutputStream());
    return item;
}

From source file:org.apache.hupa.server.utils.TestUtils.java

/**
 * Creates a FileItem which stores data in memory
 *
 * @param filename//from   ww  w . j  a v  a2  s .  c  om
 * @return a new item
 * @throws IOException
 */
public static FileItem createMockFileItem(String filename, String contentType) throws IOException {
    FileItemFactory f = new DiskFileItemFactory();
    FileItem item = f.createItem("fieldname_" + filename, contentType, false, filename);
    OutputStream os = item.getOutputStream();
    os.write("ABCDEFGHIJK\n".getBytes());
    os.close();
    return item;
}

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   ww  w . j  a va  2 s .c o 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.// w  w  w . j a  v  a 2  s.  c  om
 * 
 * @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.apache.wicket.markup.html.form.upload.FileUploadTest.java

/**
 * Test that when getting an input stream a new input stream is returned every time.
 * /*from  w  ww .  ja v  a2s . c  o m*/
 * Also test that the inputstream is saved internally for later closing.
 * 
 * @throws Exception
 */
@Test
public void getInputStream() throws Exception {
    final IFileCleaner fileUploadCleaner = new FileCleaner();

    DiskFileItemFactory itemFactory = new DiskFileItemFactory() {
        @Override
        public FileCleaningTracker getFileCleaningTracker() {
            return new FileCleanerTrackerAdapter(fileUploadCleaner);
        }
    };
    FileItem fileItem = itemFactory.createItem("dummyFieldName", "text/java", false, "FileUploadTest.java");
    // Initialize the upload
    fileItem.getOutputStream();

    // Get the internal list out
    Field inputStreamsField = FileUpload.class.getDeclaredField("inputStreamsToClose");
    inputStreamsField.setAccessible(true);

    FileUpload fileUpload = new FileUpload(fileItem);

    List<?> inputStreams = (List<?>) inputStreamsField.get(fileUpload);

    assertNull(inputStreams);

    InputStream is1 = fileUpload.getInputStream();
    inputStreams = (List<?>) inputStreamsField.get(fileUpload);

    assertEquals(1, inputStreams.size());

    InputStream is2 = fileUpload.getInputStream();
    inputStreams = (List<?>) inputStreamsField.get(fileUpload);

    assertEquals(2, inputStreams.size());

    assertNotSame(is1, is2);

    // Ok lets close all the streams
    try {
        fileUpload.closeStreams();
    } catch (Exception e) {
        fail();
    }

    inputStreams = (List<?>) inputStreamsField.get(fileUpload);

    assertNull(inputStreams);

    fileUploadCleaner.destroy();
}

From source file:org.eclipse.virgo.management.console.UploadServletTests.java

@Test(expected = RuntimeException.class)
public void testDoUploadFail() throws Exception {
    UploadServlet uploadServlet = new UploadServlet();
    FileItem fileItem = new DiskFileItem("foo", "json/application", false, "src/test/resources/test.upload",
            500, new File("/target"));
    File stagingDir = new File("target");
    fileItem.getOutputStream();
    uploadServlet.doUpload(fileItem, stagingDir);
}

From source file:org.eclipse.virgo.management.console.UploadServletTests.java

@Test
public void testDoUpload() throws Exception {
    UploadServlet uploadServlet = new UploadServlet();
    FileItem fileItem = new DiskFileItem("foo", "json/application", false, "test.upload", 500,
            new File("/target"));
    File stagingDir = new File("src/test/resources");
    fileItem.getOutputStream();
    File doUpload = uploadServlet.doUpload(fileItem, stagingDir);
    assertNotNull(doUpload);/*www.j  ava2s .c  o m*/
}

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;/*  w  w w  .j  a  va 2s  .c om*/
    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>");
        }
    }
}

From source file:org.orbeon.oxf.processor.converter.ToXMLConverter.java

@Override
public ProcessorOutput createOutput(String name) {
    final ProcessorOutput output = new CacheableTransformerOutputImpl(ToXMLConverter.this, name) {
        public void readImpl(PipelineContext pipelineContext, XMLReceiver xmlReceiver) {

            // Read config input
            final XMLParsing.ParserConfiguration config = readCacheInputAsObject(pipelineContext,
                    getInputByName(INPUT_CONFIG), new CacheableInputReader<XMLParsing.ParserConfiguration>() {
                        public XMLParsing.ParserConfiguration read(
                                org.orbeon.oxf.pipeline.api.PipelineContext context, ProcessorInput input) {

                            final Element configElement = readInputAsDOM4J(context, input).getRootElement();

                            return new XMLParsing.ParserConfiguration(
                                    ProcessorUtils.selectBooleanValue(configElement, "/config/validating",
                                            URLGenerator.DEFAULT_VALIDATING),
                                    ProcessorUtils.selectBooleanValue(configElement, "/config/handle-xinclude",
                                            URLGenerator.DEFAULT_HANDLE_XINCLUDE),
                                    ProcessorUtils.selectBooleanValue(configElement,
                                            "/config/external-entities",
                                            URLGenerator.DEFAULT_EXTERNAL_ENTITIES));
                        }//w  ww.  j  a  v a  2s.  co  m
                    });

            try {
                // Get FileItem
                final FileItem fileItem = NetUtils.prepareFileItem(NetUtils.REQUEST_SCOPE, logger);

                // TODO: Can we avoid writing to a FileItem?

                // Read to OutputStream
                readInputAsSAX(pipelineContext, INPUT_DATA,
                        new BinaryTextXMLReceiver(fileItem.getOutputStream()));

                // Create parser
                final XMLReader reader = XMLParsing.newXMLReader(config);

                // Run parser on InputStream
                //inputSource.setSystemId();
                reader.setContentHandler(xmlReceiver);
                reader.parse(new InputSource(fileItem.getInputStream()));

            } catch (Exception e) {
                throw new OXFException(e);
            }
        }
    };
    addOutput(name, output);
    return output;
}

From source file:org.orbeon.oxf.processor.EmailProcessor.java

/**
 * Read a text or binary document and return it as a FileItem
 *
 * @param pipelineContext current PipelineContext
 * @param source          SAX source/* w  ww.  j a v  a2 s  . co m*/
 * @return                FileItem
 * @throws IOException
 * @throws TransformerException
 */
// NOTE: Method is public for unit tests
public static FileItem handleStreamedPartContent(PipelineContext pipelineContext, SAXSource source)
        throws IOException, TransformerException {

    final FileItem fileItem = NetUtils.prepareFileItem(NetUtils.REQUEST_SCOPE);
    TransformerUtils.sourceToSAX(source, new BinaryTextXMLReceiver(fileItem.getOutputStream()));

    return fileItem;
}