List of usage examples for org.apache.commons.fileupload FileUpload getFileItemFactory
public FileItemFactory getFileItemFactory()
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.// ww w . j a v a 2s. c om * * @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 .jav 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.seasar.cubby.plugins.guice.CubbyModuleTest.java
@Test public void configure() throws Exception { final HttpServletRequest request = createNiceMock(HttpServletRequest.class); final HttpServletResponse response = createNiceMock(HttpServletResponse.class); final ServletContext servletContext = createNiceMock(ServletContext.class); expect(servletContext.getInitParameter("cubby.guice.module")).andStubReturn(TestModule.class.getName()); final Hashtable<String, Object> attributes = new Hashtable<String, Object>(); expect(servletContext.getAttribute((String) anyObject())).andStubAnswer(new IAnswer<Object>() { public Object answer() throws Throwable { return attributes.get(getCurrentArguments()[0]); }//from w ww . j a v a 2s . c o m }); servletContext.setAttribute((String) anyObject(), anyObject()); expectLastCall().andAnswer(new IAnswer<Void>() { public Void answer() throws Throwable { attributes.put((String) getCurrentArguments()[0], getCurrentArguments()[1]); return null; } }); replay(servletContext); final CubbyGuiceServletContextListener cubbyGuiceServletContextListener = new CubbyGuiceServletContextListener(); cubbyGuiceServletContextListener.contextInitialized(new ServletContextEvent(servletContext)); final GuiceFilter guiceFilter = new GuiceFilter(); guiceFilter.init(new FilterConfig() { public String getFilterName() { return "guice"; } public String getInitParameter(final String name) { return null; } @SuppressWarnings("unchecked") public Enumeration getInitParameterNames() { return new Vector<String>().elements(); } public ServletContext getServletContext() { return servletContext; } }); final FilterChain chain = new FilterChain() { public void doFilter(final ServletRequest request, final ServletResponse response) throws IOException, ServletException { final PluginRegistry pluginRegistry = PluginRegistry.getInstance(); final GuicePlugin guicePlugin = new GuicePlugin(); try { guicePlugin.initialize(servletContext); guicePlugin.ready(); pluginRegistry.register(guicePlugin); } catch (final Exception e) { throw new ServletException(e); } final Injector injector = guicePlugin.getInjector(); System.out.println(injector); final PathResolverProvider pathResolverProvider = ProviderFactory.get(PathResolverProvider.class); final PathResolver pathResolver = pathResolverProvider.getPathResolver(); System.out.println(pathResolver); final PathTemplateParser pathTemplateParser = injector.getInstance(PathTemplateParser.class); System.out.println(pathTemplateParser); assertTrue(pathTemplateParser instanceof MyPathTemplateParser); final ContainerProvider containerProvider = ProviderFactory.get(ContainerProvider.class); final Container container = containerProvider.getContainer(); final Foo foo = container.lookup(Foo.class); System.out.println(foo); System.out.println(foo.pathResolver); assertSame(pathResolver, foo.pathResolver); try { final Baz baz = injector.getInstance(Baz.class); System.out.println(baz); fail(); } catch (final ConfigurationException e) { // ok } final ConverterProvider converterProvider = ProviderFactory.get(ConverterProvider.class); System.out.println(converterProvider); System.out.println(converterProvider.getConverter(BigDecimalConverter.class)); final FileUpload fileUpload1 = injector.getInstance(FileUpload.class); System.out.println(fileUpload1); System.out.println(fileUpload1.getFileItemFactory()); final FileUpload fileUpload2 = injector.getInstance(FileUpload.class); System.out.println(fileUpload2); System.out.println(fileUpload2.getFileItemFactory()); assertNotSame(fileUpload1, fileUpload2); assertNotSame(fileUpload1.getFileItemFactory(), fileUpload2.getFileItemFactory()); } }; guiceFilter.doFilter(request, response, chain); cubbyGuiceServletContextListener.contextDestroyed(new ServletContextEvent(servletContext)); ThreadContext.remove(); }