List of usage examples for org.apache.commons.fileupload ProgressListener ProgressListener
ProgressListener
From source file:helma.servlet.AbstractServletClient.java
protected List parseUploads(ServletRequestContext reqcx, RequestTrans reqtrans, final UploadStatus uploadStatus, String encoding) throws FileUploadException, UnsupportedEncodingException { // handle file upload DiskFileItemFactory factory = new DiskFileItemFactory(); FileUpload upload = new FileUpload(factory); // use upload limit for individual file size, but also set a limit on overall size upload.setFileSizeMax(uploadLimit * 1024); upload.setSizeMax(totalUploadLimit * 1024); // register upload tracker with user's session if (uploadStatus != null) { upload.setProgressListener(new ProgressListener() { public void update(long bytesRead, long contentLength, int itemsRead) { uploadStatus.update(bytesRead, contentLength, itemsRead); }/*from w ww. ja va 2s . co m*/ }); } List uploads = upload.parseRequest(reqcx); Iterator it = uploads.iterator(); while (it.hasNext()) { FileItem item = (FileItem) it.next(); String name = item.getFieldName(); Object value; // check if this is an ordinary HTML form element or a file upload if (item.isFormField()) { value = item.getString(encoding); } else { value = new MimePart(item); } // if multiple values exist for this name, append to _array reqtrans.addPostParam(name, value); } return uploads; }
From source file:axiom.servlet.AbstractServletClient.java
protected List parseUploads(ServletRequestContext reqcx, RequestTrans reqtrans, final UploadStatus uploadStatus, String encoding) throws FileUploadException, UnsupportedEncodingException { List uploads = null;/* w w w . j ava 2 s. c om*/ Context cx = Context.enter(); ImporterTopLevel scope = new ImporterTopLevel(cx, true); try { // handle file upload DiskFileItemFactory factory = new DiskFileItemFactory(); FileUpload upload = new FileUpload(factory); // use upload limit for individual file size, but also set a limit on overall size upload.setFileSizeMax(uploadLimit * 1024); upload.setSizeMax(totalUploadLimit * 1024); // register upload tracker with user's session if (uploadStatus != null) { upload.setProgressListener(new ProgressListener() { public void update(long bytesRead, long contentLength, int itemsRead) { uploadStatus.update(bytesRead, contentLength, itemsRead); } }); } uploads = upload.parseRequest(reqcx); Iterator it = uploads.iterator(); while (it.hasNext()) { FileItem item = (FileItem) it.next(); String name = item.getFieldName(); Object value = null; // check if this is an ordinary HTML form element or a file upload if (item.isFormField()) { value = item.getString(encoding); } else { String itemName = item.getName().trim(); if (itemName == null || itemName.equals("")) { continue; } value = new MimePart(itemName, item.get(), item.getContentType()); value = new NativeJavaObject(scope, value, value.getClass()); } item.delete(); // if multiple values exist for this name, append to _array // reqtrans.addPostParam(name, value); ???? Object ret = reqtrans.get(name); if (ret != null && ret != Scriptable.NOT_FOUND) { appendFormValue(reqtrans, name, value); } else { reqtrans.set(name, value); } } } finally { Context.exit(); } return uploads; }
From source file:org.eclipse.rap.addons.fileupload.internal.FileUploadProcessor.java
private ProgressListener createProgressListener() { ProgressListener result = new ProgressListener() { long prevTotalBytesRead = -1; public void update(long totalBytesRead, long contentLength, int item) { // Depending on the servlet engine and other environmental factors, // this listener may be notified for every network packet, so don't notify unless there // is an actual increase. if (totalBytesRead > prevTotalBytesRead) { prevTotalBytesRead = totalBytesRead; tracker.setContentLength(contentLength); tracker.setBytesRead(totalBytesRead); tracker.handleProgress(); }/* w ww . ja va2 s.c om*/ } }; return result; }
From source file:org.eclipse.rap.fileupload.internal.FileUploadProcessor.java
private ProgressListener createProgressListener() { ProgressListener result = new ProgressListener() { long prevTotalBytesRead = -1; @Override/*from w w w .j a v a2 s. co m*/ public void update(long totalBytesRead, long contentLength, int item) { // Depending on the servlet engine and other environmental factors, // this listener may be notified for every network packet, so don't notify unless there // is an actual increase. if (totalBytesRead > prevTotalBytesRead) { prevTotalBytesRead = totalBytesRead; tracker.setContentLength(contentLength); tracker.setBytesRead(totalBytesRead); tracker.handleProgress(); } } }; return result; }
From source file:org.eclipse.rap.rwt.supplemental.fileupload.internal.FileUploadProcessor.java
private ProgressListener createProgressListener(final long maxFileSize) { ProgressListener result = new ProgressListener() { long prevTotalBytesRead = -1; public void update(long totalBytesRead, long contentLength, int item) { // Depending on the servlet engine and other environmental // factors, // this listener may be notified for every network packet, so // don't notify unless there // is an actual increase. if (totalBytesRead > prevTotalBytesRead) { prevTotalBytesRead = totalBytesRead; // Note: Apache fileupload 1.2.x will throw an exception // after the upload is finished. // So we handle the file size violation as best we can from // here. // https://issues.apache.org/jira/browse/FILEUPLOAD-145 if (maxFileSize != -1 && contentLength > maxFileSize) { tracker.setException(new Exception(FILE_EXCEEDS_MAXIMUM_ALLOWED_SIZE)); tracker.handleFailed(); } else { tracker.setContentLength(contentLength); tracker.setBytesRead(totalBytesRead); tracker.handleProgress(); }/*w ww.j av a2s .c o m*/ } } }; return result; }
From source file:org.eclipse.rwt.widgets.upload.servlet.FileUploadServiceHandler.java
/** * Treats the request as a post request which contains the file to be * uploaded. Uses the apache commons fileupload library to * extract the file from the request, attaches a {@link FileUploadListener} to * get notified about the progress and writes the file content * to the given {@link FileUploadStorageItem} * @param request Request object, must not be null * @param fileUploadStorageitem Object where the file content is set to. * If null, nothing happens.// w w w.j a va 2 s . co m * @param uploadProcessId Each upload action has a unique process identifier to * match subsequent polling calls to get the progress correctly to the uploaded file. * */ private void handleFileUpload(final HttpServletRequest request, final FileUploadStorageItem fileUploadStorageitem, final String uploadProcessId) { // Ignore upload requests which have no valid widgetId if (fileUploadStorageitem != null && uploadProcessId != null && !"".equals(uploadProcessId)) { // Create file upload factory and upload servlet // You could use new DiskFileItemFactory(threshold, location) // to configure a custom in-memory threshold and storage location. // By default the upload files are stored in the java.io.tmpdir FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); // Create a file upload progress listener final ProgressListener listener = new ProgressListener() { public void update(final long aBytesRead, final long aContentLength, final int anItem) { fileUploadStorageitem.updateProgress(aBytesRead, aContentLength); } }; // Upload servlet allows to set upload listener upload.setProgressListener(listener); fileUploadStorageitem.setUploadProcessId(uploadProcessId); FileItem fileItem = null; try { final List uploadedItems = upload.parseRequest(request); // Only one file upload at once is supported. If there are multiple files, take // the first one and ignore other if (uploadedItems.size() > 0) { fileItem = (FileItem) uploadedItems.get(0); // Don't check for file size 0 because this prevents uploading new empty office xp documents // which have a file size of 0. if (!fileItem.isFormField()) { fileUploadStorageitem.setFileInputStream(fileItem.getInputStream()); fileUploadStorageitem.setContentType(fileItem.getContentType()); } } } catch (FileUploadException e) { e.printStackTrace(); } catch (final Exception e) { e.printStackTrace(); } } }
From source file:org.exoplatform.upload.UploadService.java
private ServletFileUpload makeServletFileUpload(final UploadResource upResource) { // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Set factory constraints factory.setSizeThreshold(0);/* www . jav a2 s. c om*/ factory.setRepository(new File(uploadLocation_)); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); ProgressListener listener = new ProgressListener() { public void update(long pBytesRead, long pContentLength, int pItems) { if (pBytesRead == upResource.getUploadedSize()) return; upResource.addUploadedBytes(pBytesRead - upResource.getUploadedSize()); } }; upload.setProgressListener(listener); return upload; }
From source file:org.footware.server.services.TrackUploadServlet.java
@SuppressWarnings("unchecked") @Override/* w w w. j a v a 2 s . com*/ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { logger = LoggerFactory.getLogger(TrackUploadServlet.class); // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(req); // Init fields of form String extension = ""; File uploadedFile = null; String notes = ""; String name = ""; int privacy = 0; Boolean comments = false; String fileName = null; String email = null; FileItem file = null; if (isMultipart) { // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(new File("tmp")); factory.setSizeThreshold(10000000); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Create a progress listener ProgressListener progressListener = new ProgressListener() { public void update(long pBytesRead, long pContentLength, int pItems) { logger.info("We are currently reading item " + pItems); if (pContentLength == -1) { logger.info("So far, " + pBytesRead + " bytes have been read."); } else { logger.info("So far, " + pBytesRead + " of " + pContentLength + " bytes have been read."); } } }; upload.setProgressListener(progressListener); // Parse the request List<FileItem> items; try { items = upload.parseRequest(req); Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); // Process a file upload if (!item.isFormField() && item.getFieldName().equals("file")) { // Get file name fileName = item.getName(); // If file is not set, we cancel import if (fileName == null) { logger.info("empty file name"); break; } // We have to parse the filename because of IE again else { logger.info("received file:" + fileName); fileName = FilenameUtils.getName(fileName); file = item; } // Read notes field } else if (item.isFormField() && item.getFieldName().equals("notes")) { notes = item.getString(); logger.debug("notes" + ": " + item.getString()); // Read comments field } else if (item.isFormField() && item.getFieldName().equals("comments")) { // Value can either be on or off if (item.getString().equals("on")) { comments = true; } else { comments = false; } logger.debug("comments" + ": " + item.getString()); // Read privacy field } else if (item.isFormField() && item.getFieldName().equals("privacy")) { String priv = item.getString(); // Currently values can be either public or private. // Default is private if (priv.equals("public")) { privacy = 5; } else if (priv.equals("private")) { privacy = 0; } else { privacy = 0; } logger.debug("privacy" + ": " + item.getString()); // Read name file } else if (item.isFormField() && item.getFieldName().equals("name")) { name = item.getString(); logger.debug("name" + ": " + item.getString()); } else if (item.isFormField() && item.getFieldName().equals("email")) { email = item.getString(); logger.debug("email" + ": " + item.getString()); } } User user = UserUtil.getByEmail(email); // If we read all fields, we can start the import if (file != null) { // Get UserDTO // User user = (User) req.getSession().getAttribute("user"); // UserUtil.getByEmail(email); logger.info("User: " + user.getFullName() + " " + user.getEmail()); String userDirectoryString = user.getEmail().replace("@", "_at_"); File baseDirectory = initFileStructure(userDirectoryString); // If already a file exist with the same name, we have // to search for a new name extension = fileName.substring(fileName.length() - 3, fileName.length()); uploadedFile = getSavePath(baseDirectory.getAbsolutePath(), fileName); logger.debug(uploadedFile.getAbsolutePath()); // Finally write the file to disk try { file.write(uploadedFile); } catch (Exception e) { logger.error("File upload unsucessful", e); e.printStackTrace(); return; } TrackImporter importer = importerMap.get(extension); importer.importTrack(uploadedFile); TrackVisualizationFactoryImpl speedFactory = new TrackVisualizationFactoryImpl( new TrackVisualizationSpeedStrategy()); TrackVisualizationFactoryImpl elevationFactory = new TrackVisualizationFactoryImpl( new TrackVisualizationElevationStrategy()); // Add meta information to track for (Track dbTrack : importer.getTracks()) { dbTrack.setCommentsEnabled(comments); dbTrack.setNotes(notes); dbTrack.setPublicity(privacy); dbTrack.setFilename(fileName); dbTrack.setPath(uploadedFile.getAbsolutePath()); dbTrack.setUser(user); //persist dbTrack.store(); TrackVisualization ele = new TrackVisualization(speedFactory.create(dbTrack)); ele.store(); TrackVisualization spd = new TrackVisualization(elevationFactory.create(dbTrack)); spd.store(); } } else { logger.error("error: file: " + (file != null)); } } catch (FileUploadException e1) { logger.error("File upload unsucessful", e1); e1.printStackTrace(); } catch (Exception e) { logger.error("File upload unsucessful", e); e.printStackTrace(); } } }
From source file:org.linagora.linshare.view.tapestry.services.impl.MyMultipartDecoderImpl.java
protected ServletFileUpload createFileUpload() { ServletFileUpload upload = new ServletFileUpload(fileItemFactory); // set maximum file upload size upload.setSizeMax(-1);/* w w w . ja v a 2 s . c o m*/ upload.setFileSizeMax(-1); ProgressListener progressListener = new ProgressListener() { private long megaBytes = -1; public void update(long pBytesRead, long pContentLength, int pItems) { long mBytes = pBytesRead / 1000000; if (megaBytes == mBytes) { return; } megaBytes = mBytes; if (logger.isDebugEnabled()) { logger.debug("We are currently reading item " + pItems); if (pContentLength == -1) { logger.debug("So far, " + pBytesRead + " bytes have been read."); } else { logger.debug("So far, " + pBytesRead + " of " + pContentLength + " bytes have been read."); } } } }; upload.setProgressListener(progressListener); return upload; }
From source file:org.onesocialweb.openfire.web.FileServlet.java
private void processPost(HttpServletRequest request, HttpServletResponse response) throws Exception { final PrintWriter out = response.getWriter(); // 1- Bind this request to a XMPP JID final JID user = getAuthenticatedUser(request); if (user == null) { throw new AuthenticationException(); }/*from ww w.ja va 2 s .co m*/ // 2- Process the file final UploadManager uploadManager = UploadManager.getInstance(); // Files larger than a threshold should be stored on disk in temporary // storage place final DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(256000); factory.setRepository(getTempFolder()); // Prepare the upload parser and set a max size to enforce final ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(512000000); // Get the request ID final String requestId = request.getParameter("requestId"); // Create a progress listener ProgressListener progressListener = new ProgressListener() { private long lastNotification = 0; public void update(long pBytesRead, long pContentLength, int pItems) { if (lastNotification == 0 || (pBytesRead - lastNotification) > NOTIFICATION_THRESHOLD) { lastNotification = pBytesRead; UploadManager.getInstance().updateProgress(user, pBytesRead, pContentLength, requestId); } } }; upload.setProgressListener(progressListener); // Process the upload List items = upload.parseRequest(request); for (Object objItem : items) { FileItem item = (FileItem) objItem; if (!item.isFormField()) { String fileID = UUID.randomUUID().toString(); File target = new File(getUploadFolder(), fileID); item.write(target); UploadManager.getInstance().commitFile(user, target, item.getName(), requestId); break; // Store only one file } } }