List of usage examples for org.apache.commons.fileupload.disk DiskFileItemFactory setFileCleaningTracker
public void setFileCleaningTracker(FileCleaningTracker pTracker)
From source file:it.unipmn.di.dcs.sharegrid.web.servlet.MultipartRequestWrapper.java
/** Creates an instance of DiskFileItemFactory and set the clean-up manager. */ private static DiskFileItemFactory CreateDiskFileItemFactory(ServletContext context, int thresholdSize, File repository) {/*from ww w .j av a 2 s.com*/ FileCleaningTracker fileCleaningTracker = null; fileCleaningTracker = FileCleanerCleanup.getFileCleaningTracker(context); DiskFileItemFactory factory = null; factory = new DiskFileItemFactory( //fileCleaningTracker, thresholdSize, repository); factory.setFileCleaningTracker(fileCleaningTracker); return factory; }
From source file:dk.dma.msinm.common.repo.RepositoryService.java
/** * Creates a new DiskFileItemFactory. See: * http://commons.apache.org/proper/commons-fileupload/using.html * @return the new DiskFileItemFactory// w w w . ja v a 2 s . co m */ public static DiskFileItemFactory newDiskFileItemFactory(ServletContext servletContext) { FileCleaningTracker fileCleaningTracker = FileCleanerCleanup.getFileCleaningTracker(servletContext); DiskFileItemFactory factory = new DiskFileItemFactory(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD, null); factory.setFileCleaningTracker(fileCleaningTracker); return factory; }
From source file:edu.umd.cs.submitServer.MultipartRequest.java
/** * @return/*from w w w . java 2s .co m*/ */ private static DiskFileItemFactory getFactory(ServletContext servletContext) { DiskFileItemFactory factory = new DiskFileItemFactory(); FileCleaningTracker fileCleaningTracker = FileCleanerCleanup.getFileCleaningTracker(servletContext); factory.setFileCleaningTracker(fileCleaningTracker); return factory; }
From source file:com.raissi.utils.CustomFileUploadFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { if (bypass) { filterChain.doFilter(request, response); return;// w w w . j av a 2s.c o m } HttpServletRequest httpServletRequest = (HttpServletRequest) request; boolean isMultipart = ServletFileUpload.isMultipartContent(httpServletRequest); if (isMultipart) { logger.debug("Parsing file upload request"); FileCleaningTracker fileCleaningTracker = FileCleanerCleanup .getFileCleaningTracker(request.getServletContext()); DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setFileCleaningTracker(fileCleaningTracker); if (thresholdSize != null) { diskFileItemFactory.setSizeThreshold(Integer.valueOf(thresholdSize)); } if (uploadDir != null) { diskFileItemFactory.setRepository(new File(uploadDir)); } ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); MultipartRequest multipartRequest = new MultipartRequest(httpServletRequest, servletFileUpload); logger.debug( "File upload request parsed succesfully, continuing with filter chain with a wrapped multipart request"); filterChain.doFilter(multipartRequest, response); } else { filterChain.doFilter(request, response); } }
From source file:com.bbc.remarc.ws.UploadServiceImpl.java
/** * Helper method to create a DiskFileItemFactory, which includes a cleaning tracker to remove old tmp files * @param context Servlet Context//w w w. j a v a 2 s .c om * @param repository Temp Directory * @return created DiskFileItemFactory */ private DiskFileItemFactory newDiskFileItemFactory(ServletContext context, File repository) { FileCleaningTracker fileCleaningTracker = FileCleanerCleanup.getFileCleaningTracker(context); DiskFileItemFactory factory = new DiskFileItemFactory(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD, repository); factory.setFileCleaningTracker(fileCleaningTracker); return factory; }
From source file:com.anhth12.lambda.app.serving.AbstractLambdaResource.java
protected final List<FileItem> parseMultipart(HttpServletRequest request) throws LambdaServingException { synchronized (sharedFileItemFactory) { if (sharedFileItemFactory.get() != null) { DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(1 << 16, (File) servletContext.getAttribute("javax.servlet.context.tempdir")); fileItemFactory.setFileCleaningTracker(FileCleanerCleanup.getFileCleaningTracker(servletContext)); sharedFileItemFactory.set(fileItemFactory); }/*from ww w.ja v a2s . c o m*/ } List<FileItem> fileItems; try { fileItems = new ServletFileUpload(sharedFileItemFactory.get()).parseRequest(request); } catch (FileUploadException ex) { throw new LambdaServingException(Response.Status.BAD_REQUEST, ex.getMessage()); } check(!fileItems.isEmpty(), "No parts"); return fileItems; }
From source file:com.cloudera.oryx.app.serving.AbstractOryxResource.java
private Collection<Part> parseMultipartWithCommonsFileUpload(HttpServletRequest request) throws IOException { if (sharedFileItemFactory.get() == null) { // Not a big deal if two threads actually set this up DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(1 << 16, (File) servletContext.getAttribute("javax.servlet.context.tempdir")); fileItemFactory.setFileCleaningTracker(FileCleanerCleanup.getFileCleaningTracker(servletContext)); sharedFileItemFactory.compareAndSet(null, fileItemFactory); }//from www . j a va2s . co m try { return new ServletFileUpload(sharedFileItemFactory.get()).parseRequest(request).stream() .map(FileItemPart::new).collect(Collectors.toList()); } catch (FileUploadException e) { throw new IOException(e.getMessage()); } }
From source file:gr.forth.ics.isl.x3mlEditor.upload.MultipartUploadParser.java
private DiskFileItemFactory setupFileItemFactory(File repository, ServletContext context) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD); factory.setRepository(repository);/* ww w .ja v a2s .c o m*/ FileCleaningTracker pTracker = FileCleanerCleanup.getFileCleaningTracker(context); factory.setFileCleaningTracker(pTracker); return factory; }
From source file:com.liferay.faces.metal.component.inputfile.internal.InputFileDecoderCommonsImpl.java
@Override public Map<String, List<UploadedFile>> decode(FacesContext facesContext, String location) { Map<String, List<UploadedFile>> uploadedFileMap = null; ExternalContext externalContext = facesContext.getExternalContext(); String uploadedFilesFolder = getUploadedFilesFolder(externalContext, location); // Using the sessionId, determine a unique folder path and create the path if it does not exist. String sessionId = getSessionId(externalContext); // FACES-1452: Non-alpha-numeric characters must be removed order to ensure that the folder will be // created properly. sessionId = sessionId.replaceAll("[^A-Za-z0-9]", " "); File uploadedFilesPath = new File(uploadedFilesFolder, sessionId); if (!uploadedFilesPath.exists()) { uploadedFilesPath.mkdirs();/*from w ww. j av a 2s. c o m*/ } // Initialize commons-fileupload with the file upload path. DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setRepository(uploadedFilesPath); // Initialize commons-fileupload so that uploaded temporary files are not automatically deleted. diskFileItemFactory.setFileCleaningTracker(null); // Initialize the commons-fileupload size threshold to zero, so that all files will be dumped to disk // instead of staying in memory. diskFileItemFactory.setSizeThreshold(0); // Determine the max file upload size threshold (in bytes). int uploadedFileMaxSize = WebConfigParam.UploadedFileMaxSize.getIntegerValue(externalContext); // Parse the request parameters and save all uploaded files in a map. ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); servletFileUpload.setFileSizeMax(uploadedFileMaxSize); uploadedFileMap = new HashMap<String, List<UploadedFile>>(); UploadedFileFactory uploadedFileFactory = (UploadedFileFactory) FactoryExtensionFinder .getFactory(UploadedFileFactory.class); // Begin parsing the request for file parts: try { FileItemIterator fileItemIterator = null; HttpServletRequest httpServletRequest = (HttpServletRequest) externalContext.getRequest(); fileItemIterator = servletFileUpload.getItemIterator(httpServletRequest); if (fileItemIterator != null) { int totalFiles = 0; // For each field found in the request: while (fileItemIterator.hasNext()) { try { totalFiles++; // Get the stream of field data from the request. FileItemStream fieldStream = (FileItemStream) fileItemIterator.next(); // Get field name from the field stream. String fieldName = fieldStream.getFieldName(); // Get the content-type, and file-name from the field stream. String contentType = fieldStream.getContentType(); boolean formField = fieldStream.isFormField(); String fileName = null; try { fileName = fieldStream.getName(); } catch (InvalidFileNameException e) { fileName = e.getName(); } // Copy the stream of file data to a temporary file. NOTE: This is necessary even if the // current field is a simple form-field because the call below to diskFileItem.getString() // will fail otherwise. DiskFileItem diskFileItem = (DiskFileItem) diskFileItemFactory.createItem(fieldName, contentType, formField, fileName); Streams.copy(fieldStream.openStream(), diskFileItem.getOutputStream(), true); // If the current field is a file, then if (!diskFileItem.isFormField()) { // Get the location of the temporary file that was copied from the request. File tempFile = diskFileItem.getStoreLocation(); // If the copy was successful, then if (tempFile.exists()) { // Copy the commons-fileupload temporary file to a file in the same temporary // location, but with the filename provided by the user in the upload. This has two // benefits: 1) The temporary file will have a nice meaningful name. 2) By copying // the file, the developer can have access to a semi-permanent file, because the // commmons-fileupload DiskFileItem.finalize() method automatically deletes the // temporary one. String tempFileName = tempFile.getName(); String tempFileAbsolutePath = tempFile.getAbsolutePath(); String copiedFileName = stripIllegalCharacters(fileName); String copiedFileAbsolutePath = tempFileAbsolutePath.replace(tempFileName, copiedFileName); File copiedFile = new File(copiedFileAbsolutePath); FileUtils.copyFile(tempFile, copiedFile); // If present, build up a map of headers. Map<String, List<String>> headersMap = new HashMap<String, List<String>>(); FileItemHeaders fileItemHeaders = fieldStream.getHeaders(); if (fileItemHeaders != null) { Iterator<String> headerNameItr = fileItemHeaders.getHeaderNames(); if (headerNameItr != null) { while (headerNameItr.hasNext()) { String headerName = headerNameItr.next(); Iterator<String> headerValuesItr = fileItemHeaders .getHeaders(headerName); List<String> headerValues = new ArrayList<String>(); if (headerValuesItr != null) { while (headerValuesItr.hasNext()) { String headerValue = headerValuesItr.next(); headerValues.add(headerValue); } } headersMap.put(headerName, headerValues); } } } // Put a valid UploadedFile instance into the map that contains all of the // uploaded file's attributes, along with a successful status. Map<String, Object> attributeMap = new HashMap<String, Object>(); String id = Long.toString(((long) hashCode()) + System.currentTimeMillis()); String message = null; UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile( copiedFileAbsolutePath, attributeMap, diskFileItem.getCharSet(), diskFileItem.getContentType(), headersMap, id, message, fileName, diskFileItem.getSize(), UploadedFile.Status.FILE_SAVED); addUploadedFile(uploadedFileMap, fieldName, uploadedFile); logger.debug("Received uploaded file fieldName=[{0}] fileName=[{1}]", fieldName, fileName); } else { if ((fileName != null) && (fileName.trim().length() > 0)) { Exception e = new IOException("Failed to copy the stream of uploaded file=[" + fileName + "] to a temporary file (possibly a zero-length uploaded file)"); UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e); addUploadedFile(uploadedFileMap, fieldName, uploadedFile); } } } } catch (Exception e) { logger.error(e); UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e); String fieldName = Integer.toString(totalFiles); addUploadedFile(uploadedFileMap, fieldName, uploadedFile); } } } } // If there was an error in parsing the request for file parts, then put a bogus UploadedFile instance in // the map so that the developer can have some idea that something went wrong. catch (Exception e) { logger.error(e); UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e); addUploadedFile(uploadedFileMap, "unknown", uploadedFile); } return uploadedFileMap; }
From source file:com.liferay.faces.alloy.component.inputfile.internal.InputFileDecoderCommonsImpl.java
@Override public Map<String, List<UploadedFile>> decode(FacesContext facesContext, String location) { Map<String, List<UploadedFile>> uploadedFileMap = null; ExternalContext externalContext = facesContext.getExternalContext(); String uploadedFilesFolder = getUploadedFilesFolder(externalContext, location); // Using the sessionId, determine a unique folder path and create the path if it does not exist. String sessionId = getSessionId(externalContext); // FACES-1452: Non-alpha-numeric characters must be removed order to ensure that the folder will be // created properly. sessionId = sessionId.replaceAll("[^A-Za-z0-9]", " "); File uploadedFilesPath = new File(uploadedFilesFolder, sessionId); if (!uploadedFilesPath.exists()) { uploadedFilesPath.mkdirs();//from w w w . ja va 2 s. c o m } // Initialize commons-fileupload with the file upload path. DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setRepository(uploadedFilesPath); // Initialize commons-fileupload so that uploaded temporary files are not automatically deleted. diskFileItemFactory.setFileCleaningTracker(null); // Initialize the commons-fileupload size threshold to zero, so that all files will be dumped to disk // instead of staying in memory. diskFileItemFactory.setSizeThreshold(0); // Determine the max file upload size threshold (in bytes). int uploadedFileMaxSize = WebConfigParam.UploadedFileMaxSize.getIntegerValue(externalContext); // Parse the request parameters and save all uploaded files in a map. ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); servletFileUpload.setFileSizeMax(uploadedFileMaxSize); uploadedFileMap = new HashMap<String, List<UploadedFile>>(); UploadedFileFactory uploadedFileFactory = (UploadedFileFactory) FactoryExtensionFinder .getFactory(externalContext, UploadedFileFactory.class); // Begin parsing the request for file parts: try { FileItemIterator fileItemIterator = null; HttpServletRequest httpServletRequest = (HttpServletRequest) externalContext.getRequest(); fileItemIterator = servletFileUpload.getItemIterator(httpServletRequest); if (fileItemIterator != null) { int totalFiles = 0; // For each field found in the request: while (fileItemIterator.hasNext()) { try { totalFiles++; // Get the stream of field data from the request. FileItemStream fieldStream = (FileItemStream) fileItemIterator.next(); // Get field name from the field stream. String fieldName = fieldStream.getFieldName(); // Get the content-type, and file-name from the field stream. String contentType = fieldStream.getContentType(); boolean formField = fieldStream.isFormField(); String fileName = null; try { fileName = fieldStream.getName(); } catch (InvalidFileNameException e) { fileName = e.getName(); } // Copy the stream of file data to a temporary file. NOTE: This is necessary even if the // current field is a simple form-field because the call below to diskFileItem.getString() // will fail otherwise. DiskFileItem diskFileItem = (DiskFileItem) diskFileItemFactory.createItem(fieldName, contentType, formField, fileName); Streams.copy(fieldStream.openStream(), diskFileItem.getOutputStream(), true); // If the current field is a file, then if (!diskFileItem.isFormField()) { // Get the location of the temporary file that was copied from the request. File tempFile = diskFileItem.getStoreLocation(); // If the copy was successful, then if (tempFile.exists()) { // Copy the commons-fileupload temporary file to a file in the same temporary // location, but with the filename provided by the user in the upload. This has two // benefits: 1) The temporary file will have a nice meaningful name. 2) By copying // the file, the developer can have access to a semi-permanent file, because the // commmons-fileupload DiskFileItem.finalize() method automatically deletes the // temporary one. String tempFileName = tempFile.getName(); String tempFileAbsolutePath = tempFile.getAbsolutePath(); String copiedFileName = stripIllegalCharacters(fileName); String copiedFileAbsolutePath = tempFileAbsolutePath.replace(tempFileName, copiedFileName); File copiedFile = new File(copiedFileAbsolutePath); FileUtils.copyFile(tempFile, copiedFile); // If present, build up a map of headers. Map<String, List<String>> headersMap = new HashMap<String, List<String>>(); FileItemHeaders fileItemHeaders = fieldStream.getHeaders(); if (fileItemHeaders != null) { Iterator<String> headerNameItr = fileItemHeaders.getHeaderNames(); if (headerNameItr != null) { while (headerNameItr.hasNext()) { String headerName = headerNameItr.next(); Iterator<String> headerValuesItr = fileItemHeaders .getHeaders(headerName); List<String> headerValues = new ArrayList<String>(); if (headerValuesItr != null) { while (headerValuesItr.hasNext()) { String headerValue = headerValuesItr.next(); headerValues.add(headerValue); } } headersMap.put(headerName, headerValues); } } } // Put a valid UploadedFile instance into the map that contains all of the // uploaded file's attributes, along with a successful status. Map<String, Object> attributeMap = new HashMap<String, Object>(); String id = Long.toString(((long) hashCode()) + System.currentTimeMillis()); String message = null; UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile( copiedFileAbsolutePath, attributeMap, diskFileItem.getCharSet(), diskFileItem.getContentType(), headersMap, id, message, fileName, diskFileItem.getSize(), UploadedFile.Status.FILE_SAVED); addUploadedFile(uploadedFileMap, fieldName, uploadedFile); logger.debug("Received uploaded file fieldName=[{0}] fileName=[{1}]", fieldName, fileName); } else { if ((fileName != null) && (fileName.trim().length() > 0)) { Exception e = new IOException("Failed to copy the stream of uploaded file=[" + fileName + "] to a temporary file (possibly a zero-length uploaded file)"); UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e); addUploadedFile(uploadedFileMap, fieldName, uploadedFile); } } } } catch (Exception e) { logger.error(e); UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e); String fieldName = Integer.toString(totalFiles); addUploadedFile(uploadedFileMap, fieldName, uploadedFile); } } } } // If there was an error in parsing the request for file parts, then put a bogus UploadedFile instance in // the map so that the developer can have some idea that something went wrong. catch (Exception e) { logger.error(e); UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e); addUploadedFile(uploadedFileMap, "unknown", uploadedFile); } return uploadedFileMap; }