Search in sources :

Example 1 with FileUploadException

use of com.helger.web.fileupload.exception.FileUploadException in project ph-web by phax.

the class StreamingFuncTest method testIOException.

/**
 * Tests, whether an IOException is properly delegated.
 *
 * @throws IOException
 *         In case of error
 */
@Test
public void testIOException() throws IOException {
    final byte[] request = _newRequest();
    final InputStream stream = new FilterInputStream(new NonBlockingByteArrayInputStream(request)) {

        private int m_nNum;

        @Override
        public int read() throws IOException {
            if (++m_nNum > 123)
                throw new MockIOException("123");
            return super.read();
        }

        @Override
        public int read(final byte[] pB, final int pOff, final int pLen) throws IOException {
            for (int i = 0; i < pLen; i++) {
                final int res = read();
                if (res < 0)
                    return i == 0 ? -1 : i;
                pB[pOff + i] = (byte) res;
            }
            return pLen;
        }
    };
    try {
        _parseUploadToList(stream, request.length);
        fail("Expected IOException");
    } catch (final FileUploadException e) {
        assertTrue(e.getCause() instanceof MockIOException);
        assertEquals("123", e.getCause().getMessage());
    }
}
Also used : NonBlockingByteArrayInputStream(com.helger.commons.io.stream.NonBlockingByteArrayInputStream) FilterInputStream(java.io.FilterInputStream) ServletInputStream(javax.servlet.ServletInputStream) FilterInputStream(java.io.FilterInputStream) NonBlockingByteArrayInputStream(com.helger.commons.io.stream.NonBlockingByteArrayInputStream) AbstractServletInputStream(com.helger.servlet.io.AbstractServletInputStream) InputStream(java.io.InputStream) MockIOException(com.helger.commons.exception.mock.MockIOException) FileUploadException(com.helger.web.fileupload.exception.FileUploadException) IOFileUploadException(com.helger.web.fileupload.exception.IOFileUploadException) Test(org.junit.Test)

Example 2 with FileUploadException

use of com.helger.web.fileupload.exception.FileUploadException in project ph-web by phax.

the class AbstractFileUploadBase method parseRequest.

/**
 * Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a>
 * compliant <code>multipart/form-data</code> stream.
 *
 * @param aCtx
 *        The context for the request to be parsed.
 * @return A list of <code>FileItem</code> instances parsed from the request,
 *         in the order that they were transmitted.
 * @throws FileUploadException
 *         if there are problems reading/parsing the request or storing files.
 */
@Nonnull
@ReturnsMutableCopy
public ICommonsList<IFileItem> parseRequest(@Nonnull final IRequestContext aCtx) throws FileUploadException {
    final ICommonsList<IFileItem> aItems = new CommonsArrayList<>();
    boolean bSuccessful = false;
    try {
        final IFileItemIterator aItemIter = getItemIterator(aCtx);
        final IFileItemFactory aFileItemFactory = getFileItemFactory();
        if (aFileItemFactory == null)
            throw new IllegalStateException("No FileItemFactory has been set.");
        while (aItemIter.hasNext()) {
            final IFileItemStream aFileItemStream = aItemIter.next();
            // Don't use getName() here to prevent an InvalidFileNameException.
            final IFileItem aFileItem = aFileItemFactory.createItem(aFileItemStream.getFieldName(), aFileItemStream.getContentType(), aFileItemStream.isFormField(), aFileItemStream.getNameUnchecked());
            aItems.add(aFileItem);
            try (final InputStream aIS = aFileItemStream.openStream();
                final OutputStream aOS = aFileItem.getOutputStream()) {
                final byte[] aBuffer = new byte[8192];
                int nBytesRead;
                // potentially blocking read
                while ((nBytesRead = aIS.read(aBuffer, 0, aBuffer.length)) > -1) {
                    aOS.write(aBuffer, 0, nBytesRead);
                }
            } catch (final FileUploadIOException ex) {
                throw (FileUploadException) ex.getCause();
            } catch (final IOException ex) {
                throw new IOFileUploadException("Processing of " + RequestHelper.MULTIPART_FORM_DATA + " request failed. " + ex.getMessage(), ex);
            }
            if (aFileItem instanceof IFileItemHeadersSupport) {
                final IFileItemHeaders aFileItemHeaders = aFileItemStream.getHeaders();
                ((IFileItemHeadersSupport) aFileItem).setHeaders(aFileItemHeaders);
            }
        }
        bSuccessful = true;
        return aItems;
    } catch (final FileUploadIOException ex) {
        throw (FileUploadException) ex.getCause();
    } catch (final IOException ex) {
        throw new FileUploadException(ex.getMessage(), ex);
    } finally {
        if (!bSuccessful) {
            // Delete all file items
            for (final IFileItem aFileItem : aItems) {
                try {
                    aFileItem.delete();
                } catch (final Exception ex) {
                    // ignore it
                    if (LOGGER.isErrorEnabled())
                        LOGGER.error("Failed to delete fileItem " + aFileItem, ex);
                }
            }
        }
    }
}
Also used : IFileItemHeaders(com.helger.web.fileupload.IFileItemHeaders) AbstractLimitedInputStream(com.helger.web.fileupload.io.AbstractLimitedInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileUploadIOException(com.helger.web.fileupload.exception.FileUploadIOException) IOException(java.io.IOException) SizeLimitExceededException(com.helger.web.fileupload.exception.SizeLimitExceededException) InvalidContentTypeException(com.helger.web.fileupload.exception.InvalidContentTypeException) FileUploadException(com.helger.web.fileupload.exception.FileUploadException) FileUploadIOException(com.helger.web.fileupload.exception.FileUploadIOException) NoSuchElementException(java.util.NoSuchElementException) IOException(java.io.IOException) IOFileUploadException(com.helger.web.fileupload.exception.IOFileUploadException) FileUploadIOException(com.helger.web.fileupload.exception.FileUploadIOException) IFileItemStream(com.helger.web.fileupload.IFileItemStream) IFileItemIterator(com.helger.web.fileupload.IFileItemIterator) IOFileUploadException(com.helger.web.fileupload.exception.IOFileUploadException) IFileItemHeadersSupport(com.helger.web.fileupload.IFileItemHeadersSupport) IFileItem(com.helger.web.fileupload.IFileItem) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) FileUploadException(com.helger.web.fileupload.exception.FileUploadException) IOFileUploadException(com.helger.web.fileupload.exception.IOFileUploadException) IFileItemFactory(com.helger.web.fileupload.IFileItemFactory) ReturnsMutableCopy(com.helger.commons.annotation.ReturnsMutableCopy) Nonnull(javax.annotation.Nonnull)

Example 3 with FileUploadException

use of com.helger.web.fileupload.exception.FileUploadException in project ph-web by phax.

the class DiskFileItem method write.

/**
 * A convenience method to write an uploaded item to disk. The client code is
 * not concerned with whether or not the item is stored in memory, or on disk
 * in a temporary location. They just want to write the uploaded item to a
 * file.
 * <p>
 * This implementation first attempts to rename the uploaded item to the
 * specified destination file, if the item was originally written to disk.
 * Otherwise, the data will be copied to the specified file.
 * <p>
 * This method is only guaranteed to work <em>once</em>, the first time it is
 * invoked for a particular item. This is because, in the event that the
 * method renames a temporary file, that file will no longer be available to
 * copy or rename again at a later time.
 *
 * @param aDstFile
 *        The <code>File</code> into which the uploaded item should be stored.
 * @throws FileUploadException
 *         if an error occurs.
 */
@Nonnull
public ISuccessIndicator write(@Nonnull final File aDstFile) throws FileUploadException {
    ValueEnforcer.notNull(aDstFile, "DstFile");
    if (isInMemory())
        return SimpleFileIO.writeFile(aDstFile, directGet());
    final File aOutputFile = getStoreLocation();
    if (aOutputFile != null) {
        // Save the length of the file
        m_nSize = aOutputFile.length();
        /*
       * The uploaded file is being stored on disk in a temporary location so
       * move it to the desired file.
       */
        if (FileOperations.renameFile(aOutputFile, aDstFile).isSuccess())
            return ESuccess.SUCCESS;
        // Copying needed
        return FileOperations.copyFile(aOutputFile, aDstFile);
    }
    // For whatever reason we cannot write the file to disk.
    throw new FileUploadException("Cannot write uploaded file to: " + aDstFile.getAbsolutePath());
}
Also used : File(java.io.File) FileUploadException(com.helger.web.fileupload.exception.FileUploadException) Nonnull(javax.annotation.Nonnull)

Example 4 with FileUploadException

use of com.helger.web.fileupload.exception.FileUploadException in project ph-web by phax.

the class RequestMultipartHelper method handleMultipartFormData.

/**
 * Parse the provided servlet request as multipart, if the Content-Type starts
 * with <code>multipart/form-data</code>.
 *
 * @param aHttpRequest
 *        Source HTTP request from which multipart/form-data (aka file
 *        uploads) should be extracted.
 * @param aConsumer
 *        A consumer that takes either {@link IFileItem} or
 *        {@link IFileItem}[] or {@link String} or {@link String}[].
 * @return {@link EChange#CHANGED} if something was added
 */
@Nonnull
public static EChange handleMultipartFormData(@Nonnull final HttpServletRequest aHttpRequest, @Nonnull final BiConsumer<String, Object> aConsumer) {
    if (aHttpRequest instanceof MockHttpServletRequest) {
        // UnsupportedOperationExceptions
        return EChange.UNCHANGED;
    }
    if (!RequestHelper.isMultipartFormDataContent(aHttpRequest)) {
        // It's not a multipart request
        return EChange.UNCHANGED;
    }
    // It is a multipart request!
    // Note: this handles only POST parameters!
    boolean bAddedFileUploadItems = false;
    try {
        // Setup the ServletFileUpload....
        final ServletFileUpload aUpload = new ServletFileUpload(PROVIDER.getFileItemFactory());
        aUpload.setSizeMax(MAX_REQUEST_SIZE);
        aUpload.setHeaderEncoding(CWeb.CHARSET_REQUEST_OBJ.name());
        final IProgressListener aProgressListener = ProgressListenerProvider.getProgressListener();
        if (aProgressListener != null)
            aUpload.setProgressListener(aProgressListener);
        ServletHelper.setRequestCharacterEncoding(aHttpRequest, CWeb.CHARSET_REQUEST_OBJ);
        // Group all items with the same name together
        final ICommonsMap<String, ICommonsList<String>> aFormFields = new CommonsHashMap<>();
        final ICommonsMap<String, ICommonsList<IFileItem>> aFormFiles = new CommonsHashMap<>();
        final ICommonsList<IFileItem> aFileItems = aUpload.parseRequest(aHttpRequest);
        for (final IFileItem aFileItem : aFileItems) {
            if (aFileItem.isFormField()) {
                // We need to explicitly use the charset, as by default only the
                // charset from the content type is used!
                aFormFields.computeIfAbsent(aFileItem.getFieldName(), k -> new CommonsArrayList<>()).add(aFileItem.getString(CWeb.CHARSET_REQUEST_OBJ));
            } else
                aFormFiles.computeIfAbsent(aFileItem.getFieldName(), k -> new CommonsArrayList<>()).add(aFileItem);
        }
        // set all form fields
        for (final Map.Entry<String, ICommonsList<String>> aEntry : aFormFields.entrySet()) {
            // Convert list of String to value (String or String[])
            final ICommonsList<String> aValues = aEntry.getValue();
            final Object aValue = aValues.size() == 1 ? aValues.getFirst() : ArrayHelper.newArray(aValues, String.class);
            aConsumer.accept(aEntry.getKey(), aValue);
        }
        // name)
        for (final Map.Entry<String, ICommonsList<IFileItem>> aEntry : aFormFiles.entrySet()) {
            // Convert list of String to value (IFileItem or IFileItem[])
            final ICommonsList<IFileItem> aValues = aEntry.getValue();
            final Object aValue = aValues.size() == 1 ? aValues.getFirst() : ArrayHelper.newArray(aValues, IFileItem.class);
            aConsumer.accept(aEntry.getKey(), aValue);
        }
        // Parsing complex file upload succeeded -> do not use standard scan for
        // parameters
        bAddedFileUploadItems = true;
    } catch (final FileUploadException ex) {
        if (!StreamHelper.isKnownEOFException(ex.getCause()))
            LOGGER.error("Error parsing multipart request content", ex);
    } catch (final RuntimeException ex) {
        LOGGER.error("Error parsing multipart request content", ex);
    }
    return EChange.valueOf(bAddedFileUploadItems);
}
Also used : StreamHelper(com.helger.commons.io.stream.StreamHelper) ServletHelper(com.helger.servlet.ServletHelper) IFileItemFactoryProviderSPI(com.helger.web.fileupload.IFileItemFactoryProviderSPI) LoggerFactory(org.slf4j.LoggerFactory) ProgressListenerProvider(com.helger.web.progress.ProgressListenerProvider) EChange(com.helger.commons.state.EChange) RequestHelper(com.helger.servlet.request.RequestHelper) HttpServletRequest(javax.servlet.http.HttpServletRequest) FileUploadException(com.helger.web.fileupload.exception.FileUploadException) CWeb(com.helger.web.CWeb) IProgressListener(com.helger.web.progress.IProgressListener) Map(java.util.Map) BiConsumer(java.util.function.BiConsumer) Nonnull(javax.annotation.Nonnull) ServletFileUpload(com.helger.web.fileupload.servlet.ServletFileUpload) ArrayHelper(com.helger.commons.collection.ArrayHelper) CGlobal(com.helger.commons.CGlobal) Logger(org.slf4j.Logger) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) IFileItem(com.helger.web.fileupload.IFileItem) CommonsHashMap(com.helger.commons.collection.impl.CommonsHashMap) ICommonsList(com.helger.commons.collection.impl.ICommonsList) ServiceLoaderHelper(com.helger.commons.lang.ServiceLoaderHelper) MockHttpServletRequest(com.helger.servlet.mock.MockHttpServletRequest) ICommonsMap(com.helger.commons.collection.impl.ICommonsMap) ICommonsList(com.helger.commons.collection.impl.ICommonsList) MockHttpServletRequest(com.helger.servlet.mock.MockHttpServletRequest) IProgressListener(com.helger.web.progress.IProgressListener) ServletFileUpload(com.helger.web.fileupload.servlet.ServletFileUpload) CommonsHashMap(com.helger.commons.collection.impl.CommonsHashMap) IFileItem(com.helger.web.fileupload.IFileItem) Map(java.util.Map) CommonsHashMap(com.helger.commons.collection.impl.CommonsHashMap) ICommonsMap(com.helger.commons.collection.impl.ICommonsMap) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) FileUploadException(com.helger.web.fileupload.exception.FileUploadException) Nonnull(javax.annotation.Nonnull)

Aggregations

FileUploadException (com.helger.web.fileupload.exception.FileUploadException)4 Nonnull (javax.annotation.Nonnull)3 CommonsArrayList (com.helger.commons.collection.impl.CommonsArrayList)2 IFileItem (com.helger.web.fileupload.IFileItem)2 IOFileUploadException (com.helger.web.fileupload.exception.IOFileUploadException)2 InputStream (java.io.InputStream)2 CGlobal (com.helger.commons.CGlobal)1 ReturnsMutableCopy (com.helger.commons.annotation.ReturnsMutableCopy)1 ArrayHelper (com.helger.commons.collection.ArrayHelper)1 CommonsHashMap (com.helger.commons.collection.impl.CommonsHashMap)1 ICommonsList (com.helger.commons.collection.impl.ICommonsList)1 ICommonsMap (com.helger.commons.collection.impl.ICommonsMap)1 MockIOException (com.helger.commons.exception.mock.MockIOException)1 NonBlockingByteArrayInputStream (com.helger.commons.io.stream.NonBlockingByteArrayInputStream)1 StreamHelper (com.helger.commons.io.stream.StreamHelper)1 ServiceLoaderHelper (com.helger.commons.lang.ServiceLoaderHelper)1 EChange (com.helger.commons.state.EChange)1 ServletHelper (com.helger.servlet.ServletHelper)1 AbstractServletInputStream (com.helger.servlet.io.AbstractServletInputStream)1 MockHttpServletRequest (com.helger.servlet.mock.MockHttpServletRequest)1