List of usage examples for org.apache.commons.fileupload FileItem getSize
long getSize();
From source file:org.exoplatform.calendar.ws.CalendarRestApi.java
/** * Creates attachments for an event with specified id if: * - the authenticated user is the owner of the calendar of the event * - for group calendars, the authenticated user has edit rights on the calendar * - the calendar of the event has been shared with the authenticated user, with modification rights * - the calendar of the event has been shared with a group of the authenticated user, with modification rights * //from ww w . ja v a 2 s . c om * This entry point only allow http POST request, with file input stream in the http form submit, and the id of event in the path * * @param id * identity of event to create attachment * * @param iter * Iterator of org.apache.commons.fileupload.FileItem object * (eXo rest framework use apache file upload to parse the input stream of http form submit request, and inject FileItem objects * * @request POST: http://localhost:8080/portal/rest/v1/calendar/events/Event123/attachments * * @response HTTP status code: * 201 if created successfully, and http header *location* href point to the newly created attachment resource. * 404 if event to create attachment not found * 401 if user don"t have create permission, 503 if there is any error during the save process * * @return http status code * * @authentication * * @anchor CalendarRestApi.createAttachmentForEvent */ @POST @RolesAllowed("users") @Path("/events/{id}/attachments") @Consumes("multipart/*") public Response createAttachmentForEvent(@Context UriInfo uriInfo, @PathParam("id") String id, Iterator<FileItem> iter) { try { CalendarEvent ev = calendarServiceInstance().getEventById(id); if (ev == null) return Response.status(HTTPStatus.NOT_FOUND).cacheControl(nc).build(); Calendar cal = calendarServiceInstance().getCalendarById(ev.getCalendarId()); if (Utils.isCalendarEditable(currentUserId(), cal)) { int calType = Calendar.TYPE_ALL; List<Attachment> attachment = new ArrayList<Attachment>(); try { calType = Integer.parseInt(ev.getCalType()); } catch (NumberFormatException e) { calType = calendarServiceInstance().getTypeOfCalendar(currentUserId(), ev.getCalendarId()); } attachment.addAll(ev.getAttachment()); while (iter.hasNext()) { FileItem file = iter.next(); String fileName = file.getName(); if (fileName != null) { String mimeType = new MimeTypeResolver().getMimeType(fileName.toLowerCase()); Attachment at = new Attachment(); at.setMimeType(mimeType); at.setSize(file.getSize()); at.setName(file.getName()); at.setInputStream(file.getInputStream()); attachment.add(at); } } ev.setAttachment(attachment); switch (calType) { case Calendar.TYPE_PRIVATE: calendarServiceInstance().saveUserEvent(currentUserId(), ev.getCalendarId(), ev, false); break; case Calendar.TYPE_PUBLIC: calendarServiceInstance().savePublicEvent(ev.getCalendarId(), ev, false); break; case Calendar.TYPE_SHARED: calendarServiceInstance().saveEventToSharedCalendar(currentUserId(), ev.getCalendarId(), ev, false); break; default: break; } StringBuilder attUri = new StringBuilder(getBasePath(uriInfo)); attUri.append("/").append(ev.getId()); attUri.append(ATTACHMENT_URI); return Response.status(HTTPStatus.CREATED).header(HEADER_LOCATION, attUri.toString()) .cacheControl(nc).build(); } // return Response.status(HTTPStatus.UNAUTHORIZED).cacheControl(nc).build(); } catch (Exception e) { if (log.isDebugEnabled()) log.debug(e.getMessage()); } return Response.status(HTTPStatus.UNAVAILABLE).cacheControl(nc).build(); }
From source file:org.exoplatform.document.upload.handle.UploadMultipartHandler.java
@Override public List<Document> parseHttpRequest(HttpServletRequest request) throws SizeLimitExceededException, FileUploadException { if (logger.isDebugEnabled()) { logger.info("Parse file item form HTTP servlet request."); }/* ww w .j a v a 2 s. com*/ Document document = null; List<Document> documents = new ArrayList<Document>(); boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) return documents; File repository = FileUtils.forceMkdir(FilePathUtils.REPOSITORY_PATH); if (repository != null) logger.info("The" + FilePathUtils.REPOSITORY_PATH + " Directory is created"); if (FileUtils.forceMkdir(FilePathUtils.RESOURCE_PATH) != null) logger.info("To create specified sub-folder under " + FilePathUtils.ROOT_PATH + " top-level folder"); // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(MEMORY_CACHE_SIZE); factory.setRepository(repository); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(MAXIMUM_FILE_SIZE); try { List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> iterator = items.iterator(); while (iterator.hasNext()) { FileItem fileItem = iterator.next(); if (!fileItem.isFormField()) { // Write file items to disk-based String absolutePath = writeFiles(fileItem, fileItem.getName()); document = Document.getInstance(); document.setFilename(fileItem.getName()); document.setContentType(fileItem.getContentType()); document.setSize(fileItem.getSize()); document.setUrl(absolutePath); document.setReadOnly(false); document.setArchive(false); document.setDirectory(false); document.setHidden(false); document.setSystem(false); document.setOther(false); document.setRegularFile(false); Date time = Calendar.getInstance().getTime(); document.setCreationTime(time); document.setLastAccessTime(time); document.setLastModifiedTime(time); documents.add(document); logger.info("File(s) " + document.getFilename() + " was/were uploaded successfully"); } } } catch (SizeLimitExceededException slee) { throw new SizeLimitExceededException( "The request was rejected because its size exceeds (" + slee.getActualSize() + "bytes) the configured maximum (" + slee.getPermittedSize() + "bytes)"); } catch (FileUploadException fue) { throw new FileUploadException("Upload file stream was been cancelled", fue.getCause()); } finally { try { FileUtils.cleanDirectory(factory.getRepository()); logger.info("Cleans a directory without deleting it"); } catch (IOException ex) { logger.warn(ex.getMessage(), ex); } } return documents; }
From source file:org.gatein.management.gadget.mop.exportimport.server.FileUploadServlet.java
/** * Override executeAction to save the received files in a custom place and delete this items from session. *///from w w w. ja va2s . c om @Override public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles) throws UploadActionException { StringBuilder response = new StringBuilder("<response>\n"); int count = 0; for (FileItem item : sessionFiles) { // if (false == item.isFormField()) { if (!item.isFormField()) { count++; try { // Create a new file based on the remote file name in the client String saveName = item.getName().replaceAll("[\\\\/><\\|\\s\"'{}()\\[\\]]+", "_"); // Create a temporary file placed in the default system temp folder File file = File.createTempFile(saveName, ".zip"); item.write(file); // Save a list with the received files receivedFiles.put(item.getFieldName(), file); receivedContentTypes.put(item.getFieldName(), item.getContentType()); String importMode = request.getParameter("importMode"); // process the uploaded file processImport(request.getParameter("pc"), new FileInputStream(file), importMode); // Compose a xml message with the full file information which can be parsed in client side response.append("<file-").append(count).append("-field>").append(item.getFieldName()) .append("</file-").append(count).append("-field>\n"); response.append("<file-").append(count).append("-name>").append(item.getName()) .append("</file-").append(count).append("-name>\n"); response.append("<file-").append(count).append("-size>").append(item.getSize()) .append("</file-").append(count).append("-size>\n"); response.append("<file-").append(count).append("-type>").append(item.getContentType()) .append("</file-").append(count).append("type>\n"); } catch (Exception e) { throw new UploadActionException(e); } } } // Remove files from session because we have a copy of them removeSessionFileItems(request); // Send information of the received files to the client. return response.append("</response>\n").toString(); }
From source file:org.gatein.management.gadget.server.FileUploadServlet.java
/** * Override executeAction to save the received files in a custom place * and delete this items from session./*from w ww . j a v a2 s .c om*/ */ @Override public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles) throws UploadActionException { StringBuilder response = new StringBuilder("<response>\n"); int count = 0; for (FileItem item : sessionFiles) { //if (false == item.isFormField()) { if (!item.isFormField()) { count++; try { // Create a new file based on the remote file name in the client String saveName = item.getName().replaceAll("[\\\\/><\\|\\s\"'{}()\\[\\]]+", "_"); // Create a temporary file placed in the default system temp folder File file = File.createTempFile(saveName, ".zip"); item.write(file); // Save a list with the received files receivedFiles.put(item.getFieldName(), file); receivedContentTypes.put(item.getFieldName(), item.getContentType()); String overwriteVal = request.getParameter("overwrite"); boolean overwrite = Boolean.parseBoolean(overwriteVal); // process the uploaded file processImport(request.getParameter("pc"), new FileInputStream(file), overwrite); // Compose a xml message with the full file information which can be parsed in client side response.append("<file-").append(count).append("-field>").append(item.getFieldName()) .append("</file-").append(count).append("-field>\n"); response.append("<file-").append(count).append("-name>").append(item.getName()) .append("</file-").append(count).append("-name>\n"); response.append("<file-").append(count).append("-size>").append(item.getSize()) .append("</file-").append(count).append("-size>\n"); response.append("<file-").append(count).append("-type>").append(item.getContentType()) .append("</file-").append(count).append("type>\n"); } catch (Exception e) { throw new UploadActionException(e); } } } // Remove files from session because we have a copy of them removeSessionFileItems(request); // Send information of the received files to the client. return response.append("</response>\n").toString(); }
From source file:org.gatein.wcm.portlet.editor.views.UploadsActions.java
public String actionEditUpload(ActionRequest request, ActionResponse response, UserWcm userWcm) { String tmpDir = System.getProperty(Wcm.UPLOADS.TMP_DIR); FileItemFactory factory = new DiskFileItemFactory(Wcm.UPLOADS.MAX_FILE_SIZE, new File(tmpDir)); PortletFileUpload upload = new PortletFileUpload(factory); try {//from w ww .java 2s. c om List<FileItem> items = upload.parseRequest(request); FileItem file = null; String description = null; String editUploadId = null; for (FileItem item : items) { if (!item.isFormField()) { file = item; } else { if (item.getFieldName().equals("uploadFileDescription")) { description = item.getString(); } else if (item.getFieldName().equals("editUploadId")) { editUploadId = item.getString(); } } } Upload updateUpload = wcm.findUpload(new Long(editUploadId), userWcm); if (updateUpload != null) { if (file != null && file.getSize() > 0 && file.getName().length() > 0) { updateUpload.setFileName(file.getName()); updateUpload.setMimeType(file.getContentType()); updateUpload.setDescription(description); wcm.unlock(new Long(editUploadId), Wcm.LOCK.UPLOAD, userWcm); wcm.update(updateUpload, file.getInputStream(), userWcm); } else { if (description != null) { updateUpload.setDescription(description); wcm.unlock(new Long(editUploadId), Wcm.LOCK.UPLOAD, userWcm); wcm.update(updateUpload, userWcm); } } } return Wcm.VIEWS.UPLOADS; } catch (Exception e) { log.warning("Error uploading file"); e.printStackTrace(); response.setRenderParameter("errorWcm", "Error uploading file " + e.toString()); } return Wcm.VIEWS.UPLOADS; }
From source file:org.gedantic.web.servlet.FileUploadHandler.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { LOG.debug(">doPost"); // process only if its multipart content if (ServletFileUpload.isMultipartContent(request)) { try {//from ww w. jav a2 s.c o m List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); long length = 0; for (FileItem item : multiparts) { if (!item.isFormField()) { if (!item.getName().toLowerCase().endsWith(".ged") && !item.getName().toLowerCase().endsWith(".gedcom")) { LOG.info("Upload file " + item.getName() + " doesn't end in .ged or .gedcom"); throw new RuntimeException( "Upload file " + item.getName() + " doesn't end in .ged or .gedcom"); } if (item.getSize() > MAX_MB * 1024 * 1024) { LOG.info("Upload file " + item.getName() + " exceeds " + MAX_MB + "MB limit - was " + item.getSize()); throw new RuntimeException("Upload file " + item.getName() + " exceeds " + MAX_MB + "MB limit - was " + item.getSize()); } String name = new File(item.getName()).getName(); String fullPathAndName = UPLOAD_DIRECTORY + File.separator + name; File file = new File(fullPathAndName); item.write(file); length = file.length(); LOG.info("Wrote " + fullPathAndName + " (" + length + " bytes)"); new ParserAndLoader(request, response, file).parseAndLoadIntoSession(); } } } catch (RuntimeException ex) { LOG.error("Unable to upload file: " + ex.getMessage()); response.setStatus(403); } catch (Exception ex) { LOG.error("Unable to upload file: ", ex); response.setStatus(403); } } Runtime rt = Runtime.getRuntime(); long maxMemory = rt.maxMemory(); long freeMemory = rt.freeMemory(); LOG.info("fileUploaded - freeMemory:" + Double.toString(freeMemory / (1024 * 1024)) + " maxMemory:" + Double.toString(maxMemory / (1024 * 1024))); LOG.debug("<doPost"); }
From source file:org.getobjects.appserver.elements.WOFileUpload.java
@Override public void takeValuesFromRequest(final WORequest _rq, final WOContext _ctx) { final Object cursor = _ctx.cursor(); String formName = this.elementNameInContext(_ctx); Object formValue = _rq.formValueForKey(formName); if (this.writeValue != null) this.writeValue.setValue(formValue, cursor); if (formValue == null) { if (this.filePath != null) this.filePath.setValue(null, cursor); if (this.data != null) this.data.setValue(null, cursor); } else if (formValue instanceof String) { /* this happens if the enctype is not multipart/formdata */ if (this.filePath != null) this.filePath.setStringValue((String) formValue, cursor); } else if (formValue instanceof FileItem) { FileItem fileItem = (FileItem) formValue; if (this.size != null) this.size.setValue(fileItem.getSize(), cursor); if (this.contentType != null) this.contentType.setStringValue(fileItem.getContentType(), cursor); if (this.filePath != null) this.filePath.setStringValue(fileItem.getName(), cursor); /* process content */ if (this.data != null) this.data.setValue(fileItem.get(), cursor); else if (this.string != null) { // TODO: we could support a encoding get-binding this.string.setStringValue(fileItem.getString(), cursor); } else if (this.inputStream != null) { try { this.inputStream.setValue(fileItem.getInputStream(), cursor); } catch (IOException e) { log.error("failed to get input stream for upload file", e); this.inputStream.setValue(null, cursor); }/* w w w . j av a 2 s . c om*/ } /* delete temporary file */ if (this.deleteAfterPush != null) { if (this.deleteAfterPush.booleanValueInComponent(cursor)) fileItem.delete(); } } else log.warn("cannot process WOFileUpload value: " + formValue); }
From source file:org.infoglue.deliver.taglib.common.ParseMultipartTag.java
/** * Process the end tag. Sets a cookie. * //from w w w.ja v a 2s . c o m * @return indication of whether to continue evaluating the JSP page. * @throws JspException if an error occurred while processing this tag. */ public int doEndTag() throws JspException { Map parameters = new HashMap(); try { //Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); //Set factory constraints factory.setSizeThreshold(maxSize.intValue()); //factory.setRepository(new File(CmsPropertyHandler.getDigitalAssetPath())); //Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); //Set overall request size constraint upload.setSizeMax(this.maxSize.intValue()); if (upload.isMultipartContent(this.getController().getHttpServletRequest())) { //Parse the request List items = upload.parseRequest(this.getController().getHttpServletRequest()); List files = new ArrayList(); //Process the uploaded items Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); if (isValidContentType(contentType)) { files.add(item); } else { if ((item.getName() == null || item.getName().equals("")) && this.ignoreEmpty) { logger.warn("Empty file but that was ok.."); } else { pageContext.setAttribute("status", "nok"); pageContext.setAttribute("upload_error", "A field did not have a valid content type"); pageContext.setAttribute(fieldName + "_error", "Not a valid content type"); //throw new JspException("Not a valid content type"); } } } else { String name = item.getFieldName(); String value = item.getString(); String oldValue = (String) parameters.get(name); if (oldValue != null) value = oldValue + "," + value; if (value != null) { try { String fromEncoding = "iso-8859-1"; String toEncoding = "utf-8"; String testValue = new String(value.getBytes(fromEncoding), toEncoding); if (testValue.indexOf((char) 65533) == -1) value = testValue; } catch (Exception e) { e.printStackTrace(); } } parameters.put(name, value); } } parameters.put("files", files); setResultAttribute(parameters); } else { setResultAttribute(null); } } catch (Exception e) { logger.warn("Error doing an upload" + e.getMessage(), e); //pageContext.setAttribute("fieldName_exception", "contentType_MAX"); //throw new JspException("File upload failed: " + e.getMessage()); pageContext.setAttribute("status", "nok"); pageContext.setAttribute("upload_error", "" + e.getMessage()); } return EVAL_PAGE; }
From source file:org.jahia.ajax.gwt.content.server.GWTFileManagerUploadServlet.java
private int saveToJcr(JahiaUser user, FileItem item, String location, StringBuilder name) throws IOException { String filename = name.toString(); if (logger.isDebugEnabled()) { logger.debug("item : " + item); logger.debug("destination : " + location); logger.debug("filename : " + filename); logger.debug("size : " + item.getSize()); }/* ww w . j a v a2s. c om*/ if (item == null || location == null || filename == null) { return UNKNOWN_ERROR; } JCRNodeWrapper locationFolder; try { locationFolder = JCRSessionFactory.getInstance().getCurrentUserSession().getNode(location); } catch (RepositoryException e) { logger.error(e.toString(), e); return BAD_LOCATION; } if (!locationFolder.hasPermission("jcr:addChildNodes") || locationFolder.isLocked()) { logger.debug("destination is not writable for user " + user.getName()); return READONLY; } try { if (locationFolder.hasNode(JCRContentUtils.escapeLocalNodeName(filename))) { return EXISTS; } InputStream is = item.getInputStream(); try { boolean versioningAvailable = false; if (locationFolder.getProvider().isVersioningAvailable()) { versioningAvailable = true; } if (versioningAvailable) { locationFolder.getSession().checkout(locationFolder); } JCRNodeWrapper node = locationFolder.uploadFile(filename, is, JCRContentUtils.getMimeType(filename, item.getContentType())); node.getSession().save(); if (!node.getName().equals(filename)) { name.delete(0, name.length()); name.append(node.getName()); } // Handle potential move of the node after save node = node.getSession().getNodeByIdentifier(node.getIdentifier()); if (node.getProvider().isVersioningAvailable()) { node.checkpoint(); JCRVersionService.getInstance().addVersionLabel(node, VersioningHelper .getVersionLabel(node.getProperty("jcr:created").getDate().getTime().getTime())); } } finally { IOUtils.closeQuietly(is); } locationFolder.saveSession(); } catch (RepositoryException e) { logger.error("exception ", e); return UNKNOWN_ERROR; } return OK; }
From source file:org.jamwiki.servlets.UploadServlet.java
/** * *//*from w ww .j a v a 2 s .c o m*/ private void upload(HttpServletRequest request, ModelAndView next, WikiPageInfo pageInfo) throws Exception { String virtualWiki = pageInfo.getVirtualWikiName(); List<FileItem> fileItems = ServletUtil.processMultipartRequest(request); String filename = null; String destinationFilename = null; String contentType = null; long fileSize = 0; String contents = null; boolean isImage = true; File uploadedFile = null; String url = null; byte buff[] = null; for (FileItem fileItem : fileItems) { String fieldName = fileItem.getFieldName(); if (fileItem.isFormField()) { if (fieldName.equals("description")) { // FIXME - these should be parsed contents = fileItem.getString("UTF-8"); } else if (fieldName.equals("destination")) { destinationFilename = fileItem.getString("UTF-8"); } continue; } // file name can have encoding issues, so manually convert filename = fileItem.getName(); if (filename == null) { throw new WikiException(new WikiMessage("upload.error.filename")); } filename = ImageUtil.sanitizeFilename(filename); url = ImageUtil.generateFileUrl(virtualWiki, filename, null); if (!ImageUtil.isFileTypeAllowed(filename)) { String extension = FilenameUtils.getExtension(filename); throw new WikiException(new WikiMessage("upload.error.filetype", extension)); } fileSize = fileItem.getSize(); contentType = fileItem.getContentType(); if (ImageUtil.isImagesOnFS()) { uploadedFile = ImageUtil.buildAbsoluteFile(url); fileItem.write(uploadedFile); isImage = ImageUtil.isImage(uploadedFile); } else { buff = fileItem.get(); } } if (ImageUtil.isImagesOnFS() && uploadedFile == null) { throw new WikiException(new WikiMessage("upload.error.filenotfound")); } destinationFilename = processDestinationFilename(virtualWiki, destinationFilename, filename); String pageName = ImageUtil .generateFilePageName((!StringUtils.isEmpty(destinationFilename) ? destinationFilename : filename)); if (this.handleSpam(request, pageInfo, pageName, contents, null)) { if (ImageUtil.isImagesOnFS()) { // delete the spam file uploadedFile.delete(); } this.view(request, next, pageInfo); next.addObject("contents", contents); return; } if (!StringUtils.isEmpty(destinationFilename)) { // rename the uploaded file if a destination file name was specified filename = ImageUtil.sanitizeFilename(destinationFilename); url = ImageUtil.generateFileUrl(virtualWiki, filename, null); if (ImageUtil.isImagesOnFS()) { File renamedFile = ImageUtil.buildAbsoluteFile(url); if (!uploadedFile.renameTo(renamedFile)) { throw new WikiException(new WikiMessage("upload.error.filerename", destinationFilename)); } } } ImageData imageData = null; if (!ImageUtil.isImagesOnFS()) { imageData = processImageData(contentType, buff); isImage = (imageData.width >= 0); } String ipAddress = ServletUtil.getIpAddress(request); WikiUser user = ServletUtil.currentWikiUser(); Topic topic = ImageUtil.writeImageTopic(virtualWiki, pageName, contents, user, isImage, ipAddress); WikiFileVersion wikiFileVersion = new WikiFileVersion(); wikiFileVersion.setUploadComment(topic.getTopicContent()); ImageUtil.writeWikiFile(topic, wikiFileVersion, user, ipAddress, filename, url, contentType, fileSize, imageData); ServletUtil.redirect(next, virtualWiki, topic.getName()); }