List of usage examples for org.apache.commons.fileupload FileItemStream getName
String getName();
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 v a 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 a2 s . co 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.apache.olio.webapp.fileupload.FileUploadHandler.java
/** * Handle upload of a "file" form item//from w w w . ja v a 2 s. c o m * * @param item The Commons Fileupload item being loaded * @param htUpload The Status Hashtable that contains the items that have been uploaded for post-processing use * @param serverLocationDir The Status Hashtable that contains the items that have been uploaded for post-processing use */ protected void fileItemFound(FileItemStream item, Hashtable<String, String> htUpload, String serverLocationDir, String id) throws Exception { String fileLocation = null; String fileName = item.getName(); if (fileName != null && !fileName.equals("")) { // see if IE on windows which send full path with item, but just filename // check for both separators because client OS my be different that server OS // check for unix separator logger.fine("Have item - " + fileName + " - in name= " + item.getFieldName()); int iPos = fileName.lastIndexOf("/"); if (iPos > -1) { fileName = fileName.substring(iPos + 1); logger.fine("Have full path, need to truncate \n" + item.getName() + "\n" + fileName); } // check for windows separator iPos = fileName.lastIndexOf("\\"); if (iPos > -1) { fileName = fileName.substring(iPos + 1); logger.fine("Have full path, need to truncate \n" + item.getName() + "\n" + fileName); } fileLocation = serverLocationDir + File.separator + fileName; String thumbnailName; String ext = WebappUtil.getFileExtension(fileName); if (item.getFieldName().equals(WebConstants.UPLOAD_PERSON_IMAGE_PARAM)) { fileName = "P" + id; thumbnailName = fileName + 'T' + ext; // Append the extension fileName += ext; writeWithThumbnail(item, fileName, thumbnailName); htUpload.put(WebConstants.UPLOAD_PERSON_IMAGE_PARAM, fileName); htUpload.put(WebConstants.UPLOAD_PERSON_IMAGE_THUMBNAIL_PARAM, thumbnailName); } else if (item.getFieldName().equals(WebConstants.UPLOAD_PERSON_IMAGE_THUMBNAIL_PARAM)) { fileName = "P" + id + "T" + ext; write(item, fileName); htUpload.put(WebConstants.UPLOAD_PERSON_IMAGE_THUMBNAIL_PARAM, fileName); } else if (item.getFieldName().equals(WebConstants.UPLOAD_EVENT_IMAGE_PARAM)) { //String submitter = htUpload.get(WebConstants.SUBMITTER_USER_NAME_PARAM); fileName = "E" + id; thumbnailName = fileName + 'T' + ext; fileName += ext; writeWithThumbnail(item, fileName, thumbnailName); htUpload.put(WebConstants.UPLOAD_EVENT_IMAGE_PARAM, fileName); htUpload.put(WebConstants.UPLOAD_EVENT_IMAGE_THUMBNAIL_PARAM, thumbnailName); } else if (item.getFieldName().equals("eventThumbnail")) { fileName = "E" + id + 'T' + ext; write(item, fileName); htUpload.put(WebConstants.UPLOAD_EVENT_IMAGE_THUMBNAIL_PARAM, fileName); } else if (item.getFieldName().equals("upload_event_literature")) { fileName = "E" + id + 'L' + ext; fileLocation = serverLocationDir + "/" + fileName; write(item, fileLocation); htUpload.put(WebConstants.UPLOAD_LITERATURE_PARAM, fileName); } else { logger.warning("******** what is this? item is " + item.getFieldName()); } logger.fine("Writing item to " + fileLocation); // store image location in Hashtable for later access String fieldName = item.getFieldName(); logger.fine("Inserting form item in map " + fieldName + " = " + fileName); htUpload.put(fieldName, fileName); // insert location String key = fieldName + FileUploadUtil.FILE_LOCATION_KEY; logger.fine("Inserting form item in map " + key + " = " + fileLocation); htUpload.put(key, fileLocation); } }
From source file:org.apache.olio.webapp.fileupload.FileUploadHandler.java
/** * write out file item to a file using the Apache Commons FileUpload FileItem.write method as a guide, * so the output could be monitored/*from w w w.ja va 2 s. c om*/ * * @param item The Commons Fileupload item being loaded * @param fileName File name to write uploaded data. * @throws Exception Exceptions propagated from Apache Commons Fileupload classes */ public void write(FileItemStream item, String fileName) throws Exception { // use name for update of session String itemName = item.getName(); ServiceLocator locator = ServiceLocator.getInstance(); FileSystem fs = locator.getFileSystem(); logger.fine("Getting fileItem from memory - " + itemName); OutputStream fout = fs.create(fileName); // It would have been more efficient to use NIO if we are writing to // the local filesystem. However, since we need to support DFS, // a simple solution is provided. // TO DO: Optimize write if required. try { byte[] buf = new byte[8192]; int count, size = 0; InputStream is = item.openStream(); while ((count = is.read(buf)) != -1) { fout.write(buf, 0, count); size += count; } updateSessionStatus("", size); } finally { if (fout != null) { fout.close(); } } }
From source file:org.apache.olio.webapp.fileupload.FileUploadHandler.java
/** * /*from w w w. j a va 2 s . co m*/ * @param item FileItemStream from the file upload handler * @param imageName name to save the image. * @param thumbnailName name to save the thumbnail. Extension is appended. * @throws java.lang.Exception */ public void writeWithThumbnail(FileItemStream item, String imageName, String thumbnailName) throws Exception { // use name for update of session String itemName = item.getName(); ServiceLocator locator = ServiceLocator.getInstance(); FileSystem fs = locator.getFileSystem(); logger.fine("Getting fileItem from memory - " + itemName); OutputStream imgOut = null; OutputStream thumbOut = null; InputStream is = null; try { imgOut = fs.create(imageName); thumbOut = fs.create(thumbnailName); // It would have been more efficient to use NIO if we are writing to // the local filesystem. However, since we need to support DFS, // a simple solution is provided. // TO DO: Optimize write if required. is = item.openStream(); FileUploadStatus status = getFileUploadStatus(); status.setCurrentItem(itemName); WebappUtil.saveImageWithThumbnail(is, imgOut, thumbOut, status); } finally { if (imgOut != null) try { imgOut.close(); } catch (IOException e) { } if (thumbOut != null) try { thumbOut.close(); } catch (IOException e) { } if (is != null) try { is.close(); } catch (IOException e) { } } }
From source file:org.apache.struts.extras.SecureJakartaStreamMultiPartRequest.java
/** * Processes the upload./*w w w. ja v a 2 s .co m*/ * * @param request * @param saveDir * @throws Exception */ private void processUpload(HttpServletRequest request, String saveDir) throws Exception { // Sanity check that the request is a multi-part/form-data request. if (ServletFileUpload.isMultipartContent(request)) { // Sanity check on request size. boolean requestSizePermitted = isRequestSizePermitted(request); // Interface with Commons FileUpload API // Using the Streaming API ServletFileUpload servletFileUpload = new ServletFileUpload(); FileItemIterator i = servletFileUpload.getItemIterator(request); // Iterate the file items while (i.hasNext()) { try { FileItemStream itemStream = i.next(); // If the file item stream is a form field, delegate to the // field item stream handler if (itemStream.isFormField()) { processFileItemStreamAsFormField(itemStream); } // Delegate the file item stream for a file field to the // file item stream handler, but delegation is skipped // if the requestSizePermitted check failed based on the // complete content-size of the request. else { // prevent processing file field item if request size not allowed. // also warn user in the logs. if (!requestSizePermitted) { addFileSkippedError(itemStream.getName(), request); LOG.warn("Skipped stream '#0', request maximum size (#1) exceeded.", itemStream.getName(), maxSize); continue; } processFileItemStreamAsFileField(itemStream, saveDir); } } catch (IOException e) { e.printStackTrace(); } } } }
From source file:org.apache.struts.extras.SecureJakartaStreamMultiPartRequest.java
/** * Processes the FileItemStream as a file field. * * @param itemStream/* w w w.j a v a2s. c o m*/ * @param location */ private void processFileItemStreamAsFileField(FileItemStream itemStream, String location) { File file = null; try { // Create the temporary upload file. file = createTemporaryFile(itemStream.getName(), location); if (streamFileToDisk(itemStream, file)) createFileInfoFromItemStream(itemStream, file); } catch (IOException e) { if (file != null) { try { file.delete(); } catch (SecurityException se) { se.printStackTrace(); LOG.warn("Failed to delete '#0' due to security exception above.", file.getName()); } } } }
From source file:org.apache.struts.extras.SecureJakartaStreamMultiPartRequest.java
/** * Creates an internal <code>FileInfo</code> structure used to pass information * to the <code>FileUploadInterceptor</code> during the interceptor stack * invocation process.//from ww w. j ava 2 s . com * * @param itemStream * @param file */ private void createFileInfoFromItemStream(FileItemStream itemStream, File file) { // gather attributes from file upload stream. String fileName = itemStream.getName(); String fieldName = itemStream.getFieldName(); // create internal structure FileInfo fileInfo = new FileInfo(file, itemStream.getContentType(), fileName); // append or create new entry. if (!fileInfos.containsKey(fieldName)) { List<FileInfo> infos = new ArrayList<FileInfo>(); infos.add(fileInfo); fileInfos.put(fieldName, infos); } else { fileInfos.get(fieldName).add(fileInfo); } }
From source file:org.artags.server.web.TagUploadServlet.java
@Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try {//from ww w. jav a2 s . c o m // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(); upload.setSizeMax(1000000); res.setContentType(Constants.CONTENT_TYPE_TEXT); PrintWriter out = res.getWriter(); byte[] image = null; byte[] thumbnail = null; Tag tag = new Tag(); TagImage tagImage = new TagImage(); TagThumbnail tagThumbnail = new TagThumbnail(); String contentType = null; boolean bLandscape = false; try { FileItemIterator iterator = upload.getItemIterator(req); while (iterator.hasNext()) { FileItemStream item = iterator.next(); InputStream in = item.openStream(); if (item.isFormField()) { if (Constants.PARAMATER_NAME.equals(item.getFieldName())) { String name = IOUtils.toString(in, "UTF-8"); tag.setName(name); } if (Constants.PARAMATER_LAT.equals(item.getFieldName())) { tag.setLat(Double.parseDouble(IOUtils.toString(in))); } if (Constants.PARAMATER_LON.equals(item.getFieldName())) { tag.setLon(Double.parseDouble(IOUtils.toString(in))); } if (Constants.PARAMATER_LANDSCAPE.equals(item.getFieldName())) { bLandscape = IOUtils.toString(in).equals("on"); } } else { String fieldName = item.getFieldName(); String fileName = item.getName(); contentType = item.getContentType(); try { if (fieldName.equals("thumbnail")) { thumbnail = IOUtils.toByteArray(in); } else { image = IOUtils.toByteArray(in); } } finally { IOUtils.closeQuietly(in); } } } } catch (SizeLimitExceededException e) { out.println("You exceeded the maximum size (" + e.getPermittedSize() + ") of the file (" + e.getActualSize() + ")"); } contentType = (contentType != null) ? contentType : "image/jpeg"; if (bLandscape) { image = rotate(image); if (thumbnail != null) { thumbnail = rotate(thumbnail); } } tagImage.setImage(image); tagImage.setContentType(contentType); if (thumbnail != null) { tagThumbnail.setImage(thumbnail); } else { tagThumbnail.setImage(createThumbnail(image)); } tagThumbnail.setContentType(contentType); TagImageDAO daoImage = new TagImageDAO(); daoImage.create(tagImage); TagThumbnailDAO daoThumbnail = new TagThumbnailDAO(); daoThumbnail.create(tagThumbnail); TagDAO dao = new TagDAO(); tag.setKeyImage(tagImage.getKey()); tag.setKeyThumbnail(tagThumbnail.getKey()); tag.setDate(new Date().getTime()); tag.setDateUpdate(new Date().getTime()); Tag newTag = dao.create(tag); out.print("" + newTag.getKey().getId()); out.close(); CacheService.instance().invalidate(); } catch (Exception ex) { throw new ServletException(ex); } }
From source file:org.bigloupe.web.filemanager.command.UploadCommand.java
/** * Allows overriding for some setups...// www . ja v a 2 s.c om * * @param uplFile * @return file name for uploaded file */ protected String getUploadedFileName(FileItemStream uplFile) { return uplFile.getName(); }