List of usage examples for org.apache.commons.fileupload FileItem getInputStream
InputStream getInputStream() throws IOException;
From source file:org.etudes.tool.melete.SectionPage.java
public String uploadSectionContent(String fieldname) throws Exception { try {/* w ww. j a v a2s . co m*/ FacesContext context = FacesContext.getCurrentInstance(); org.apache.commons.fileupload.FileItem fi = (org.apache.commons.fileupload.FileItem) context .getExternalContext().getRequestMap().get(fieldname); if (fi != null && fi.getName() != null && fi.getName().length() != 0) { Util.validateUploadFileName(fi.getName()); // filename on the client secResourceName = fi.getName(); if (secResourceName.indexOf("/") != -1) { secResourceName = secResourceName.substring(secResourceName.lastIndexOf("/") + 1); } if (secResourceName.indexOf("\\") != -1) { secResourceName = secResourceName.substring(secResourceName.lastIndexOf("\\") + 1); } if (logger.isDebugEnabled()) logger.debug("Rsrc name is " + secResourceName); if (logger.isDebugEnabled()) logger.debug("upload section content data " + (int) fi.getSize()); this.secContentData = new byte[(int) fi.getSize()]; InputStream is = fi.getInputStream(); is.read(this.secContentData); String secContentMimeType = fi.getContentType(); if (logger.isDebugEnabled()) logger.debug("file upload success" + secContentMimeType); return secContentMimeType; } else { logger.debug("File being uploaded is NULL"); return null; } } catch (MeleteException me) { logger.debug("file upload FAILED" + me.toString()); throw me; } catch (Exception e) { logger.error("file upload FAILED" + e.toString()); return null; } }
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 w w w . j a v a2 s . c o m*/ * 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
private String writeFiles(FileItem fileItem, String fileName) throws FileUploadException { int lastIndexOf = fileName.lastIndexOf("\\"); if (lastIndexOf < 0) { lastIndexOf += 1;// ww w.j a va 2 s. co m } File file = new File(FilePathUtils.RESOURCE_PATH + File.separator + fileName.substring(lastIndexOf)); byte[] buffer = new byte[1024]; int length = 0; InputStream inputStream = null; FileOutputStream outputStream = null; try { inputStream = fileItem.getInputStream(); outputStream = new FileOutputStream(file); while ((length = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, length); } } catch (FileNotFoundException ex) { throw new FileUploadException(ex.getMessage()); } catch (IOException ex) { throw new FileUploadException(ex.getMessage()); } finally { IOUtils.closeQuietly(outputStream); IOUtils.closeQuietly(inputStream); } return file.getAbsolutePath(); }
From source file:org.exoplatform.frameworks.jcr.command.web.fckeditor.UploadFileCommand.java
public boolean execute(Context context) throws Exception { GenericWebAppContext webCtx = (GenericWebAppContext) context; HttpServletResponse response = webCtx.getResponse(); HttpServletRequest request = webCtx.getRequest(); PrintWriter out = response.getWriter(); response.setContentType("text/html; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); String type = (String) context.get("Type"); if (type == null) { type = ""; }// ww w .j av a 2 s .c om // // To limit browsing set Servlet init param "digitalAssetsPath" // // with desired JCR path // String rootFolderStr = // (String)context.get("org.exoplatform.frameworks.jcr.command.web.fckeditor.digitalAssetsPath" // ); // // if(rootFolderStr == null) // rootFolderStr = "/"; // // // set current folder // String currentFolderStr = (String)context.get("CurrentFolder"); // if(currentFolderStr == null) // currentFolderStr = ""; // else if(currentFolderStr.length() < rootFolderStr.length()) // currentFolderStr = rootFolderStr; // // String jcrMapping = (String)context.get(GenericWebAppContext.JCR_CONTENT_MAPPING); // if(jcrMapping == null) // jcrMapping = DisplayResourceCommand.DEFAULT_MAPPING; // // String digitalWS = (String)webCtx.get(AppConstants.DIGITAL_ASSETS_PROP); // if(digitalWS == null) // digitalWS = AppConstants.DEFAULT_DIGITAL_ASSETS_WS; String workspace = (String) webCtx.get(AppConstants.DIGITAL_ASSETS_PROP); if (workspace == null) { workspace = AppConstants.DEFAULT_DIGITAL_ASSETS_WS; } String currentFolderStr = getCurrentFolderPath(webCtx); webCtx.setCurrentWorkspace(workspace); Node parentFolder = (Node) webCtx.getSession().getItem(currentFolderStr); DiskFileUpload upload = new DiskFileUpload(); List items = upload.parseRequest(request); Map fields = new HashMap(); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { fields.put(item.getFieldName(), item.getString()); } else { fields.put(item.getFieldName(), item); } } FileItem uplFile = (FileItem) fields.get("NewFile"); // On IE, the file name is specified as an absolute path. String fileName = uplFile.getName(); if (fileName != null) { int lastUnixPos = fileName.lastIndexOf("/"); int lastWindowsPos = fileName.lastIndexOf("\\"); int index = Math.max(lastUnixPos, lastWindowsPos); fileName = fileName.substring(index + 1); } Node file = JCRCommandHelper.createResourceFile(parentFolder, fileName, uplFile.getInputStream(), uplFile.getContentType()); parentFolder.save(); int retVal = 0; out.println("<script type=\"text/javascript\">"); out.println("window.parent.frames['frmUpload'].OnUploadCompleted(" + retVal + ",'" + "');"); out.println("</script>"); out.flush(); out.close(); return false; }
From source file:org.exoplatform.platform.portlet.juzu.branding.models.BrandingDataStorageService.java
/** * Save logo file in the jcr//from www .j ava 2 s. c om * * @param item, item file */ public void saveLogoPreview(FileItem item) { SessionProvider sessionProvider = SessionProvider.createSystemProvider(); try { Session session = sessionProvider.getSession("collaboration", repositoryService.getCurrentRepository()); Node rootNode = session.getRootNode(); if (!rootNode.hasNode("Application Data")) { rootNode.addNode("Application Data", "nt:folder"); session.save(); } Node applicationDataNode = rootNode.getNode("Application Data"); if (!applicationDataNode.hasNode("logos")) { applicationDataNode.addNode("logos", "nt:folder"); session.save(); } Node logosNode = applicationDataNode.getNode("logos"); Node fileNode = null; if (logosNode.hasNode(logo_preview_name)) { fileNode = logosNode.getNode(logo_preview_name); fileNode.remove(); session.save(); } fileNode = logosNode.addNode(logo_preview_name, "nt:file"); Node jcrContent = fileNode.addNode("jcr:content", "nt:resource"); jcrContent.setProperty("jcr:data", resizeImage(item.getInputStream())); jcrContent.setProperty("jcr:lastModified", Calendar.getInstance()); jcrContent.setProperty("jcr:encoding", "UTF-8"); jcrContent.setProperty("jcr:mimeType", item.getContentType()); logosNode.save(); session.save(); } catch (Exception e) { LOG.error("Branding - Error while saving the logo: ", e.getMessage()); } finally { sessionProvider.close(); ConversationState state = ConversationState.getCurrent(); String userId = (state != null) ? state.getIdentity().getUserId() : null; if (userId != null) { // LOG.info("Branding - A new logo on the navigation bar has been saved by user :" + userId); } } }
From source file:org.exoplatform.services.jcr.ext.script.groovy.GroovyScript2RestLoader.java
/** * This method is useful for clients that send scripts as file in * 'multipart/*' request body. <br/> * NOTE even we use iterator item should be only one, rule one address - one * script. This method is created just for comfort loading script from HTML * form. NOT use this script for uploading few files in body of * 'multipart/form-data' or other type of multipart. * // w w w. ja v a 2s . co m * @param items iterator {@link FileItem} * @param uriInfo see {@link UriInfo} * @param repository repository name * @param workspace workspace name * @param path path to resource to be created * @return Response with status 'created' */ @POST @Consumes({ "multipart/*" }) @Path("add/{repository}/{workspace}/{path:.*}") public Response addScript(Iterator<FileItem> items, @Context UriInfo uriInfo, @PathParam("repository") String repository, @PathParam("workspace") String workspace, @PathParam("path") String path) { Session ses = null; try { ses = sessionProviderService.getSessionProvider(null).getSession(workspace, repositoryService.getRepository(repository)); Node node = (Node) ses.getItem(getPath(path)); InputStream stream = null; boolean autoload = false; while (items.hasNext()) { FileItem fitem = items.next(); if (fitem.isFormField() && fitem.getFieldName() != null && fitem.getFieldName().equalsIgnoreCase("autoload")) { autoload = Boolean.valueOf(fitem.getString()); } else if (!fitem.isFormField()) { stream = fitem.getInputStream(); } } createScript(node, getName(path), autoload, stream); ses.save(); URI location = uriInfo.getBaseUriBuilder().path(getClass(), "getScript").build(repository, workspace, path); return Response.created(location).build(); } catch (PathNotFoundException e) { String msg = "Path " + path + " does not exists"; LOG.error(msg); return Response.status(Response.Status.NOT_FOUND).entity(msg).entity(MediaType.TEXT_PLAIN).build(); } catch (Exception e) { LOG.error(e.getMessage(), e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()) .type(MediaType.TEXT_PLAIN).build(); } finally { if (ses != null) { ses.logout(); } } }
From source file:org.exoplatform.services.jcr.ext.script.groovy.GroovyScript2RestLoader.java
/** * This method is useful for clients that send scripts as file in * 'multipart/*' request body. <br/> * NOTE even we use iterator item should be only one, rule one address - one * script. This method is created just for comfort loading script from HTML * form. NOT use this script for uploading few files in body of * 'multipart/form-data' or other type of multipart. * //from w ww . j a v a 2 s .com * @param items iterator {@link FileItem} * @param uriInfo see {@link UriInfo} * @param repository repository name * @param workspace workspace name * @param path path to resource to be created * @return Response with status 'created' */ @POST @Consumes({ "multipart/*" }) @Path("update/{repository}/{workspace}/{path:.*}") public Response updateScript(Iterator<FileItem> items, @Context UriInfo uriInfo, @PathParam("repository") String repository, @PathParam("workspace") String workspace, @PathParam("path") String path) { Session ses = null; try { FileItem fitem = items.next(); InputStream stream = null; if (!fitem.isFormField()) { stream = fitem.getInputStream(); } ses = sessionProviderService.getSessionProvider(null).getSession(workspace, repositoryService.getRepository(repository)); Node node = (Node) ses.getItem("/" + path); node.getNode("jcr:content").setProperty("jcr:data", stream); ses.save(); URI location = uriInfo.getBaseUriBuilder().path(getClass(), "getScript").build(repository, workspace, path); return Response.created(location).build(); } catch (PathNotFoundException e) { String msg = "Path " + path + " does not exists"; LOG.error(msg); return Response.status(Response.Status.NOT_FOUND).entity(msg).entity(MediaType.TEXT_PLAIN).build(); } catch (Exception e) { LOG.error(e.getMessage(), e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()) .type(MediaType.TEXT_PLAIN).build(); } finally { if (ses != null) { ses.logout(); } } }
From source file:org.exoplatform.services.xmpp.rest.FileExchangeService.java
@POST public Response upload() throws IOException { EnvironmentContext env = EnvironmentContext.getCurrent(); HttpServletRequest req = (HttpServletRequest) env.get(HttpServletRequest.class); HttpServletResponse resp = (HttpServletResponse) env.get(HttpServletResponse.class); String description = req.getParameter("description"); String username = req.getParameter("username"); String requestor = req.getParameter("requestor"); String isRoom = req.getParameter("isroom"); boolean isMultipart = FileUploadBase.isMultipartContent(req); if (isMultipart) { // FileItemFactory factory = new DiskFileUpload(); // Create a new file upload handler // ServletFileUpload upload = new ServletFileUpload(factory); DiskFileUpload upload = new DiskFileUpload(); // Parse the request try {//from www . j av a 2s .co m List<FileItem> items = upload.parseRequest(req); XMPPMessenger messenger = (XMPPMessenger) PortalContainer.getInstance() .getComponentInstanceOfType(XMPPMessenger.class); for (FileItem fileItem : items) { XMPPSessionImpl session = (XMPPSessionImpl) messenger.getSession(username); String fileName = fileItem.getName(); String fileType = fileItem.getContentType(); if (session != null) { if (fileName != null) { // TODO Check this for compatible or not // It's necessary because IE posts full path of uploaded files fileName = FilenameUtils.getName(fileName); fileType = FilenameUtils.getExtension(fileName); File file = new File(tmpDir); if (file.isDirectory()) { String uuid = UUID.randomUUID().toString(); boolean success = (new File(tmpDir + "/" + uuid)).mkdir(); if (success) { String path = tmpDir + "/" + uuid + "/" + fileName; File f = new File(path); success = f.createNewFile(); if (success) { // File did not exist and was created InputStream inputStream = fileItem.getInputStream(); OutputStream out = new FileOutputStream(f); byte buf[] = new byte[1024]; int len; while ((len = inputStream.read(buf)) > 0) out.write(buf, 0, len); out.close(); inputStream.close(); if (log.isDebugEnabled()) log.debug("File " + path + "is created"); session.sendFile(requestor, path, description, Boolean.parseBoolean(isRoom)); } } else { if (log.isDebugEnabled()) log.debug("File already exists"); } } } } else { if (log.isDebugEnabled()) log.debug("XMPPSession for user " + username + " is null!"); } } } catch (Exception e) { if (log.isDebugEnabled()) e.printStackTrace(); return Response.status(HTTPStatus.BAD_REQUEST).entity(e.getMessage()).build(); } } return Response.ok().build(); }
From source file:org.exoplatform.wiki.service.impl.WikiRestServiceImpl.java
@POST @Path("/upload/{wikiType}/{wikiOwner:.+}/{pageId}/") public Response upload(@PathParam("wikiType") String wikiType, @PathParam("wikiOwner") String wikiOwner, @PathParam("pageId") String pageId) { EnvironmentContext env = EnvironmentContext.getCurrent(); HttpServletRequest req = (HttpServletRequest) env.get(HttpServletRequest.class); boolean isMultipart = FileUploadBase.isMultipartContent(req); if (isMultipart) { DiskFileUpload upload = new DiskFileUpload(); // Parse the request try {/*from w w w . j a v a2 s .com*/ List<FileItem> items = upload.parseRequest(req); for (FileItem fileItem : items) { InputStream inputStream = fileItem.getInputStream(); byte[] imageBytes; if (inputStream != null) { imageBytes = new byte[inputStream.available()]; inputStream.read(imageBytes); } else { imageBytes = null; } String fileName = fileItem.getName(); String fileType = fileItem.getContentType(); if (fileName != null) { // It's necessary because IE posts full path of uploaded files fileName = FilenameUtils.getName(fileName); fileType = FilenameUtils.getExtension(fileName); } String mimeType = new MimeTypeResolver().getMimeType(fileName); WikiResource attachfile = new WikiResource(mimeType, "UTF-8", imageBytes); attachfile.setName(fileName); if (attachfile != null) { WikiService wikiService = (WikiService) PortalContainer.getComponent(WikiService.class); Page page = wikiService.getExsitedOrNewDraftPageById(wikiType, wikiOwner, pageId); if (page != null) { AttachmentImpl att = ((PageImpl) page).createAttachment(attachfile.getName(), attachfile); ConversationState conversationState = ConversationState.getCurrent(); String creator = null; if (conversationState != null && conversationState.getIdentity() != null) { creator = conversationState.getIdentity().getUserId(); } att.setCreator(creator); Utils.reparePermissions(att); } } } } catch (Exception e) { log.error(e.getMessage(), e); return Response.status(HTTPStatus.BAD_REQUEST).entity(e.getMessage()).build(); } } return Response.ok().build(); }
From source file:org.fao.fenix.web.modules.core.server.upload.CodeListUploaderServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, FenixException { // useful stuff UploadListener listener = new UploadListener(request, 30); FileItemFactory factory = new MonitoredDiskFileItemFactory(listener); ServletFileUpload upload = new ServletFileUpload(factory); ServletContext servletContext = this.getServletConfig().getServletContext(); Long codeListID = null;/*from www. j a v a 2 s . c o m*/ // spring beans WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext); DcmtImporter dcmtImporter = (DcmtImporter) wac.getBean("dcmtImporter"); try { List<FileItem> fileItemList = (List<FileItem>) upload.parseRequest(request); // coding system FileItem codingSystemItem = findFileItemByCode("CODING_SYSTEM", fileItemList); // upload policy FileItem policyItem = findFileItemByCode("POLICY", fileItemList); String policyValue = extractValue(policyItem); UploadPolicy policy = UploadPolicy.valueOfIgnoreCase(policyValue); // delimiter FileItem delimiterItem = findFileItemByCode("DELIMITER", fileItemList); String delimiterValue = extractValue(delimiterItem); // coding system name FileItem codingSystemNameItem = findFileItemByCode("CODING_SYSTEM_NAME", fileItemList); String codingSystemNameValue = extractValue(codingSystemNameItem); // coding system type FileItem codingSystemTypeItem = findFileItemByCode("CODING_SYSTEM_TYPE", fileItemList); String codingSystemTypeValue = extractValue(codingSystemTypeItem); CodingType codingType = CodingType.valueOfIgnoreCase(codingSystemTypeValue); // abstract FileItem abstractItem = findFileItemByCode("ABSTRACT", fileItemList); String abstractabstract = extractValue(abstractItem); // source Source source = createSource(fileItemList); File file = createMetadata(codingSystemNameValue, codingType, abstractabstract, source); InputStream metadataStream = new FileInputStream(file); codeListID = dcmtImporter.importCodesFromCSV(metadataStream, codingSystemItem.getInputStream(), delimiterValue, policy); LOGGER.info("CodeList imported/updated with ID: " + codeListID); } catch (FileUploadException e) { LOGGER.error(e.getMessage()); throw new FenixException(e.getMessage()); } // done! response.getOutputStream().print("codeListID:" + codeListID); }