List of usage examples for org.apache.commons.fileupload.portlet PortletFileUpload PortletFileUpload
public PortletFileUpload(FileItemFactory fileItemFactory)
FileItem
instances. From source file:org.infoglue.calendar.actions.CreateResourceAction.java
/** * This is the entry point for the main listing. *//*w ww. j a v a2 s .co m*/ public String execute() throws Exception { log.debug("-------------Uploading file....."); File uploadedFile = null; String maxUploadSize = ""; String uploadSize = ""; try { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(2000000); //factory.setRepository(yourTempDirectory); PortletFileUpload upload = new PortletFileUpload(factory); String maxSize = getSetting("AssetUploadMaxFileSize"); log.debug("maxSize:" + maxSize); if (maxSize != null && !maxSize.equals("") && !maxSize.equals("@AssetUploadMaxFileSize@")) { try { maxUploadSize = maxSize; upload.setSizeMax((new Long(maxSize) * 1000)); } catch (Exception e) { log.warn("Faulty max size parameter sent from portlet component:" + maxSize); } } else { maxSize = "" + (10 * 1024); maxUploadSize = maxSize; upload.setSizeMax((new Long(maxSize) * 1000)); } List fileItems = upload.parseRequest(ServletActionContext.getRequest()); log.debug("fileItems:" + fileItems.size()); Iterator i = fileItems.iterator(); while (i.hasNext()) { Object o = i.next(); DiskFileItem dfi = (DiskFileItem) o; log.debug("dfi:" + dfi.getFieldName()); log.debug("dfi:" + dfi); if (dfi.isFormField()) { String name = dfi.getFieldName(); String value = dfi.getString(); uploadSize = "" + (dfi.getSize() / 1000); log.debug("name:" + name); log.debug("value:" + value); if (name.equals("assetKey")) { this.assetKey = value; } else if (name.equals("eventId")) { this.eventId = new Long(value); ServletActionContext.getRequest().setAttribute("eventId", this.eventId); } else if (name.equals("calendarId")) { this.calendarId = new Long(value); ServletActionContext.getRequest().setAttribute("calendarId", this.calendarId); } else if (name.equals("mode")) this.mode = value; } else { String fieldName = dfi.getFieldName(); String fileName = dfi.getName(); uploadSize = "" + (dfi.getSize() / 1000); this.fileName = fileName; log.debug("FileName:" + this.fileName); uploadedFile = new File(getTempFilePath() + File.separator + fileName); dfi.write(uploadedFile); } } } catch (Exception e) { ServletActionContext.getRequest().getSession().setAttribute("errorMessage", "Exception uploading resource. " + e.getMessage() + ".<br/>Max upload size: " + maxUploadSize + " KB"); // + "<br/>Attempted upload size (in KB):" + uploadSize); ActionContext.getContext().getValueStack().getContext().put("errorMessage", "Exception uploading resource. " + e.getMessage() + ".<br/>Max upload size: " + maxUploadSize + " KB"); // + "<br/>Attempted upload size (in KB):" + uploadSize); log.error("Exception uploading resource. " + e.getMessage()); return Action.ERROR; } try { log.debug("Creating resources.....:" + this.eventId + ":" + ServletActionContext.getRequest().getParameter("eventId") + ":" + ServletActionContext.getRequest().getParameter("calendarId")); ResourceController.getController().createResource(this.eventId, this.getAssetKey(), this.getFileContentType(), this.getFileName(), uploadedFile, getSession()); } catch (Exception e) { ServletActionContext.getRequest().getSession().setAttribute("errorMessage", "Exception saving resource to database: " + e.getMessage()); ActionContext.getContext().getValueStack().getContext().put("errorMessage", "Exception saving resource to database: " + e.getMessage()); log.error("Exception saving resource to database. " + e.getMessage()); return Action.ERROR; } return Action.SUCCESS; }
From source file:org.infoglue.calendar.actions.UpdateEventAction.java
/** * This is the entry point for the main listing. *//* w ww .ja v a2s .c om*/ public String upload() throws Exception { try { DiskFileItemFactory factory = new DiskFileItemFactory(); // Configure the factory here, if desired. PortletFileUpload upload = new PortletFileUpload(factory); // Configure the uploader here, if desired. List fileItems = upload.parseRequest(ServletActionContext.getRequest()); log.debug("fileItems:" + fileItems.size()); Iterator i = fileItems.iterator(); while (i.hasNext()) { Object o = i.next(); DiskFileItem dfi = (DiskFileItem) o; log.debug("dfi:" + dfi.getFieldName()); log.debug("dfi:" + dfi); if (!dfi.isFormField()) { String fieldName = dfi.getFieldName(); String fileName = dfi.getName(); String contentType = dfi.getContentType(); boolean isInMemory = dfi.isInMemory(); long sizeInBytes = dfi.getSize(); log.debug("fieldName:" + fieldName); log.debug("fileName:" + fileName); log.debug("contentType:" + contentType); log.debug("isInMemory:" + isInMemory); log.debug("sizeInBytes:" + sizeInBytes); File uploadedFile = new File(getTempFilePath() + File.separator + fileName); dfi.write(uploadedFile); } } } catch (Exception e) { e.printStackTrace(); } log.debug(""); ResourceController.getController().createResource(this.eventId, this.getAssetKey(), this.getFileContentType(), this.getFileFileName(), this.getFile(), getSession()); return "successUpload"; }
From source file:org.intalio.tempo.web.AlfrescoFacesPortlet.java
/** * Called by the portlet container to allow the portlet to process an action * request./*ww w . ja v a 2 s . co m*/ */ public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException { Application.setInPortalServer(true); // Set the current locale I18NUtil.setLocale(Application.getLanguage(request.getPortletSession())); boolean isMultipart = PortletFileUpload.isMultipartContent(request); try { // NOTE: Due to filters not being called within portlets we can not // make use // of the MyFaces file upload support, therefore we are using a pure // portlet request/action to handle file uploads until there is a // solution. if (isMultipart) { if (logger.isDebugEnabled()) logger.debug("Handling multipart request..."); PortletSession session = request.getPortletSession(); // get the file from the request and put it in the session DiskFileItemFactory factory = new DiskFileItemFactory(); PortletFileUpload upload = new PortletFileUpload(factory); List<FileItem> fileItems = upload.parseRequest(request); Iterator<FileItem> iter = fileItems.iterator(); FileUploadBean bean = new FileUploadBean(); while (iter.hasNext()) { FileItem item = iter.next(); String filename = item.getName(); if (item.isFormField() == false) { if (logger.isDebugEnabled()) logger.debug("Processing uploaded file: " + filename); // workaround a bug in IE where the full path is // returned // IE is only available for Windows so only check for // the Windows path separator int idx = filename.lastIndexOf('\\'); if (idx == -1) { // if there is no windows path separator check for // *nix idx = filename.lastIndexOf('/'); } if (idx != -1) { filename = filename.substring(idx + File.separator.length()); } File tempFile = TempFileProvider.createTempFile("alfresco", ".upload"); item.write(tempFile); bean.setFile(tempFile); bean.setFileName(filename); bean.setFilePath(tempFile.getAbsolutePath()); session.setAttribute(FileUploadBean.FILE_UPLOAD_BEAN_NAME, bean, PortletSession.PORTLET_SCOPE); } } // Set the VIEW_ID parameter to tell the faces portlet bridge to // treat the request // as a JSF request, this will send us back to the previous page // we came from. String lastViewId = (String) request.getPortletSession().getAttribute(SESSION_LAST_VIEW_ID); if (lastViewId != null) { response.setRenderParameter(VIEW_ID, lastViewId); } } else { User user = (User) request.getPortletSession() .getAttribute(AuthenticationHelper.AUTHENTICATION_USER); if (user != null) { // setup the authentication context try { WebApplicationContext ctx = (WebApplicationContext) getPortletContext() .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); AuthenticationService auth = (AuthenticationService) ctx.getBean("AuthenticationService"); auth.validate(user.getTicket()); // save last username into portlet preferences, get from // LoginBean state LoginBean loginBean = (LoginBean) request.getPortletSession() .getAttribute(AuthenticationHelper.LOGIN_BEAN); if (loginBean != null) { // TODO: Need to login to the Portal to get a user // here to store prefs against // so not really a suitable solution as they get // thrown away at present! // Also would need to store prefs PER user - so auto // login for each...? String oldValue = request.getPreferences().getValue(PREF_ALF_USERNAME, null); if (oldValue == null || oldValue.equals(loginBean.getUsernameInternal()) == false) { if (request.getPreferences().isReadOnly(PREF_ALF_USERNAME) == false) { request.getPreferences().setValue(PREF_ALF_USERNAME, loginBean.getUsernameInternal()); request.getPreferences().store(); } } } // do the normal JSF processing super.processAction(request, response); } catch (AuthenticationException authErr) { // remove User object as it's now useless request.getPortletSession().removeAttribute(AuthenticationHelper.AUTHENTICATION_USER); } } else { // do the normal JSF processing as we may be on the login // page super.processAction(request, response); } } } catch (Throwable e) { if (getErrorPage() != null) { handleError(request, response, e); } else { logger.warn("No error page configured, re-throwing exception"); if (e instanceof PortletException) { throw (PortletException) e; } else if (e instanceof IOException) { throw (IOException) e; } else { throw new PortletException(e); } } } }
From source file:org.jcrportlet.portlet.JCRPortlet.java
@Override public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException { // TODO Auto-generated method stub if (PortletFileUpload.isMultipartContent(request)) { FileItemFactory factory = new DiskFileItemFactory(); PortletFileUpload fu = new PortletFileUpload(factory); List<FileItem> list; try {/*from w ww . j a va 2 s. c o m*/ FileItem item = null; list = fu.parseRequest(request); for (FileItem fileItem : list) { item = fileItem; } JCRBrowser jcrBrowser = new JCRBrowser(); jcrBrowser.connectRepository("repository"); Node fileNode = jcrBrowser.uploadItem("hehe", item); } catch (FileUploadException e) { e.printStackTrace(); } catch (RepositoryException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (RepositoryConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
From source file:org.logomattic.portlet.LogomatticPortlet.java
@Override public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException { LogomatticContext model = new LogomatticContext(chromattic, request, response); try {/*from ww w . j a va2 s . co m*/ if (PortletFileUpload.isMultipartContent(request)) { FileItem image = null; try { FileItemFactory factory = new DiskFileItemFactory(); PortletFileUpload fu = new PortletFileUpload(factory); List<FileItem> list = fu.parseRequest(request); for (FileItem item : list) { if (item.getFieldName().equals("uploadedimage")) { if (item.getContentType().startsWith("image/")) { image = item; break; } } } } catch (FileUploadException e) { throw new PortletException("Could not process file upload", e); } // if (image != null) { model.save(image); } } else { String action = request.getParameter("action"); if ("use".equals(action)) { String docId = request.getParameter("docid"); if (docId != null) { PortletPreferences prefs = request.getPreferences(); prefs.setValue("url", docId); prefs.store(); } } else if ("remove".equals(action)) { String docId = request.getParameter("docid"); if (docId != null) { PortletPreferences prefs = request.getPreferences(); if (docId.equals(prefs.getValue("url", null))) { prefs.reset("url"); prefs.store(); } // model.remove(docId); } } else if ("title".equals(action)) { String title = request.getParameter("title"); if (title != null) { PortletPreferences prefs = request.getPreferences(); prefs.setValue("title", title); prefs.store(); } } } } finally { model.close(); } }
From source file:org.seasar.teeda.extension.portlet.MultipartFormDataActionRequestWrapper.java
/** * @param request /* www . j av a 2s . c o m*/ * @param maxSize * @param maxFileSize * @param thresholdSize * @param repositoryPath */ public MultipartFormDataActionRequestWrapper(final ActionRequest request, final int maxSize, final int maxFileSize, final int thresholdSize, final String repositoryPath, final String encoding) { this.request = request; final DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(thresholdSize); if (!StringUtil.isEmpty(repositoryPath)) { factory.setRepository(new File(repositoryPath)); } fileUpload = new PortletFileUpload(factory); fileUpload.setSizeMax(maxSize); fileUpload.setFileSizeMax(maxFileSize); this.encoding = encoding; parseRequest(request); }
From source file:org.springframework.web.portlet.multipart.CommonsPortletMultipartResolver.java
/** * Initialize the underlying {@code org.apache.commons.fileupload.portlet.PortletFileUpload} * instance. Can be overridden to use a custom subclass, e.g. for testing purposes. * @return the new PortletFileUpload instance */// www . java 2 s.com @Override protected FileUpload newFileUpload(FileItemFactory fileItemFactory) { return new PortletFileUpload(fileItemFactory); }
From source file:org.xmlportletfactory.portal.example01.UsersPortlet.java
private ActionRequest extractFields(ActionRequest request, boolean edit) throws FileUploadException { FileItemFactory factory = new DiskFileItemFactory(); PortletFileUpload uploadItems = new PortletFileUpload(factory); List<FileItem> allItems = uploadItems.parseRequest(request); //Separate formFields <-> fileItems for (FileItem item : allItems) { String formField = item.getFieldName(); if (item.isFormField()) { //Non-file items //Push all to request object if (formField.startsWith(UsersUpload.HIDDEN)) { uploadManager.addHidden(formField, Long.parseLong(item.getString())); } else if (formField.endsWith(UsersUpload.DOCUMENT_DELETE)) { int pos = formField.indexOf(UsersUpload.DOCUMENT_DELETE); formField = formField.substring(0, pos - 1); int pos2 = formField.lastIndexOf(UsersUpload.SEPARATOR); formField = formField.substring(pos2 + 1); if (item.getString().equals("true")) uploadManager.addDeleted(formField); } else { int pos = formField.lastIndexOf(UsersUpload.SEPARATOR); formField = formField.substring(pos + 1); try { request.setAttribute(formField, item.getString("UTF-8").trim()); } catch (Exception e) { }/*from ww w . j a va 2 s . c om*/ } } else { uploadManager.add(item); } } return request; }
From source file:se.vgregion.webbisar.helpers.WebbisPortletHelper.java
/** * This method will parse the multipart request and if the user has pressed cancel return without doing * anything else. If the user has pressed submit it will save uploaded images/video in the temp folder on disk. * It will also save references to the images/video in the session with the prefix 'webbis.mainform.'. * /*from ww w . j a v a2 s. c om*/ * @param request * the ActionRequest object * @return List of image references or NULL if video added or user pressed cancel */ public List<String> parseAndSaveMultipartFiles(ActionRequest request) throws WebbisValidationException { try { PortletSession session = request.getPortletSession(true); PortletFileUpload upload = new PortletFileUpload(diskFileItemFactory); List<FileItem> fileItems = upload.parseRequest(request); // first check which button was clicked; submit or cancel for (FileItem item : fileItems) { if (item.isFormField()) { if (item.getFieldName().equals("cancelAddImages")) { // do nothing more - the user has pressed 'cancel'. return null; } } } List<String> imageFiles = new ArrayList<String>(); // Check if "main" or multiple birth sibling webbis Integer webbisIndex = 0; if (session.getAttribute(SESSION_ATTRIB_KEY_WEBBIS_INDEX) != null) { webbisIndex = (Integer) session.getAttribute(SESSION_ATTRIB_KEY_WEBBIS_INDEX); } // Validate mediafiles, e.g. size and/or number of video files validateMediafiles(fileItems, webbisIndex, session); // parse and save the images on the temp area for (FileItem item : fileItems) { if (!item.isFormField()) { if (item.getSize() > 0) { MediaType mediaType = MediaType.IMAGE; if (item.getContentType().startsWith("video")) { mediaType = MediaType.VIDEO; } // Add temp image String contentType = item.getContentType(); String suffix = item.getName().substring(item.getName().lastIndexOf('.')); if (suffix != null) { suffix = suffix.toLowerCase(); } String filename = generateGUID() + suffix; fileHandler.writeTempFile(filename, session.getId(), item.getInputStream()); if (MediaType.IMAGE.equals(mediaType)) { // Add to list, we need to resize later... imageFiles.add("temp/" + session.getId() + "/" + filename); } // Set temp path on webbis setMediaFileOnWebbisInSession(webbisIndex, session, filename, contentType, mediaType); // If main image not set if (MediaType.IMAGE.equals(mediaType) && !isMainImageSet(webbisIndex, request)) { setMainImage(webbisIndex, Integer.parseInt( item.getFieldName().substring(item.getFieldName().length() - 1)), request); } } } } return imageFiles; } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } catch (FTPException e) { e.printStackTrace(); throw new RuntimeException(e); } catch (FileUploadException e) { e.printStackTrace(); throw new RuntimeException(e); } }
From source file:vn.hss.etrans.yeucauvantai.YeuCauVanTaiPortlet.java
private ActionRequest extractFields(ActionRequest request, boolean edit) throws FileUploadException { FileItemFactory factory = new DiskFileItemFactory(); PortletFileUpload uploadItems = new PortletFileUpload(factory); List<FileItem> allItems = uploadItems.parseRequest(request); //Separate formFields <-> fileItems for (FileItem item : allItems) { String formField = item.getFieldName(); if (item.isFormField()) { //Non-file items //Push all to request object String portletName = "_" + request.getAttribute(WebKeys.PORTLET_ID) + "_"; if (formField.startsWith(YeuCauVanTaiUpload.HIDDEN)) { uploadManager.addHidden(formField, Long.parseLong(item.getString())); } else if (formField.endsWith(YeuCauVanTaiUpload.DOCUMENT_DELETE)) { int pos = formField.indexOf(YeuCauVanTaiUpload.DOCUMENT_DELETE); formField = formField.substring(0, pos - 1); formField = formField.replaceAll(portletName, ""); if (item.getString().equals("true")) uploadManager.addDeleted(formField); } else { formField = formField.replaceAll(portletName, ""); try { request.setAttribute(formField, item.getString("UTF-8").trim()); } catch (Exception e) { }//from www . ja va 2 s.c o m } } else { uploadManager.add(item); } } return request; }