List of usage examples for org.apache.commons.fileupload.portlet PortletFileUpload PortletFileUpload
public PortletFileUpload(FileItemFactory fileItemFactory)
FileItem
instances. From source file:org.apache.geronimo.console.MultiPagePortlet.java
public void processAction(ActionRequest actionRequest, ActionResponse actionResponse) throws PortletException, IOException { String mode = null;// www. j a va2s.c o m Map<String, FileItem> files = null; Map<String, String> fields = null; if (actionRequest.getContentType() != null && actionRequest.getContentType().startsWith("multipart/form-data")) { files = new HashMap<String, FileItem>(); fields = new HashMap<String, String>(); PortletFileUpload request = new PortletFileUpload(new DiskFileItemFactory()); try { List<FileItem> items = request.parseRequest(actionRequest); for (FileItem item : items) { if (item.isFormField()) { if (item.getFieldName().equals(MODE_KEY)) { mode = item.getString(); } fields.put(item.getFieldName(), item.getString()); } else { files.put(item.getFieldName(), item); } } } catch (FileUploadException e) { log.error("Unable to process form including a file upload", e); } } else { mode = actionRequest.getParameter(MODE_KEY); } MultiPageModel model = getModel(actionRequest); while (true) { if (mode == null) { break; } int pos = mode.lastIndexOf('-'); if (pos == -1) { // Assume it's a render request break; } else { String type = mode.substring(pos + 1); mode = mode.substring(0, pos); MultiPageAbstractHandler handler = helpers.get(mode); if (handler == null) { log.error("No handler for action mode '" + mode + "'"); break; } if (files == null) { handler.getUploadFields().clear(); handler.getUploadFiles().clear(); } else { handler.getUploadFields().putAll(fields); handler.getUploadFiles().putAll(files); } log.debug("Using action handler '" + handler.getClass().getName() + "'"); if (type.equals("before")) { mode = handler.actionBeforeView(actionRequest, actionResponse, model); } else if (type.equals("after")) { mode = handler.actionAfterView(actionRequest, actionResponse, model); } else { log.error("Unrecognized portlet action '" + mode + "'"); mode = null; } } } if (mode != null) { actionResponse.setRenderParameter(MODE_KEY, mode); } if (model != null) { model.save(actionResponse, actionRequest.getPortletSession(true)); } }
From source file:org.apache.geronimo.console.repository.RepositoryViewPortlet.java
public void processAction(ActionRequest actionRequest, ActionResponse actionResponse) throws PortletException, IOException { actionResponse.setRenderParameter("message", ""); // set to blank first String action = actionRequest.getParameter("action"); if (action != null && action.equals("usage")) { // User clicked on a repository entry to view usage String res = actionRequest.getParameter("res"); actionResponse.setRenderParameter("mode", "usage"); actionResponse.setRenderParameter("res", res); return;/*from www . j av a2 s . com*/ } try { File file = null; String name = null; String basename = null; String specify = null; String groupId = null; String artifactId = null; String version = null; String fileType = null; String replacedArtifactString = null; PortletFileUpload uploader = new PortletFileUpload(new DiskFileItemFactory()); try { List items = uploader.parseRequest(actionRequest); for (Iterator i = items.iterator(); i.hasNext();) { FileItem item = (FileItem) i.next(); if (!item.isFormField()) { name = item.getName().trim(); if (name.length() == 0) { file = null; } else { // IE sends full path while Firefox sends just basename // in the case of "FullName" we may be able to infer the group // Note, we can't use File.separatorChar because the file separator // is dependent upon the client and not the server. String fileChar = "\\"; int fileNameIndex = name.lastIndexOf(fileChar); if (fileNameIndex == -1) { fileChar = "/"; fileNameIndex = name.lastIndexOf(fileChar); } if (fileNameIndex != -1) { basename = name.substring(fileNameIndex + 1); } else { basename = name; } // Create the temporary file to be used for import to the server file = File.createTempFile("geronimo-import", ""); file.deleteOnExit(); log.debug("Writing repository import file to " + file.getAbsolutePath()); } if (file != null) { try { item.write(file); } catch (Exception e) { throw new PortletException(e); } } // This is not the file itself, but one of the form fields for the URI } else { String fieldName = item.getFieldName().trim(); if ("group".equals(fieldName)) { groupId = item.getString().trim(); } else if ("artifact".equals(fieldName)) { artifactId = item.getString().trim(); } else if ("version".equals(fieldName)) { version = item.getString().trim(); } else if ("fileType".equals(fieldName)) { fileType = item.getString().trim(); } else if ("jarName".equals(fieldName)) { replacedArtifactString = item.getString().trim(); } else if ("specify".equals(fieldName)) { specify = item.getString().trim(); } } } if (groupId == null || groupId.isEmpty()) groupId = "default"; PluginInstallerGBean installer = KernelRegistry.getSingleKernel() .getGBean(PluginInstallerGBean.class); Artifact artifact = null; if ("yes".equals(specify)) { artifact = new Artifact(groupId, artifactId, version, fileType); } else { artifact = installer.calculateArtifact(file, basename, groupId); } if (artifact == null) { addErrorMessage(actionRequest, "Can not calculate the Artifact string automatically. Please manually specify one."); return; } installer.installLibrary(file, artifact); addInfoMessage(actionRequest, "File is successfully added to repository with artifact string: " + artifact.toString()); // add alias if (replacedArtifactString != null && replacedArtifactString.length() > 0) { ExplicitDefaultArtifactResolver instance = KernelRegistry.getSingleKernel() .getGBean(ExplicitDefaultArtifactResolver.class); Properties set = new Properties(); set.put(replacedArtifactString, artifact.toString()); instance.addAliases(set); addInfoMessage(actionRequest, "Replaced artifact: " + replacedArtifactString + " with: " + artifact.toString()); } } catch (FileUploadException e) { throw new PortletException(e); } catch (GBeanNotFoundException e) { throw new PortletException(e); } catch (InternalKernelException e) { throw new PortletException(e); } catch (IllegalStateException e) { throw new PortletException(e); } } catch (PortletException e) { throw e; } }
From source file:org.apache.tapestry5.portlet.multipart.PortletMultipartDecoderImpl.java
private PortletFileUpload createFileUpload() { PortletFileUpload upload = new PortletFileUpload(_fileItemFactory); // set maximum file upload size upload.setSizeMax(_maxRequestSize);/*from w w w . j a va2s.c o m*/ upload.setFileSizeMax(_maxFileSize); return upload; }
From source file:org.apache.tapestry5.portlet.upload.internal.services.PortletMultipartDecoderImpl.java
private PortletFileUpload createPortletFileUpload() { PortletFileUpload upload = new PortletFileUpload(fileItemFactory); // set maximum file upload size upload.setSizeMax(maxRequestSize);//from w w w .j ava 2 s .c o m upload.setFileSizeMax(maxFileSize); return upload; }
From source file:org.danann.cernunnos.runtime.web.CernunnosPortlet.java
@SuppressWarnings("unchecked") private void runScript(URL u, PortletRequest req, PortletResponse res, RuntimeRequestResponse rrr) { // Choose the right Task... Task k = getTask(u);//ww w . j a v a 2 s . c o m // Basic, guaranteed request attributes... rrr.setAttribute(WebAttributes.REQUEST, req); rrr.setAttribute(WebAttributes.RESPONSE, res); // Also let's check the request for multi-part form // data & convert to request attributes if we find any... List<InputStream> streams = new LinkedList<InputStream>(); if (req instanceof ActionRequest && PortletFileUpload.isMultipartContent((ActionRequest) req)) { if (log.isDebugEnabled()) { log.debug("Multipart form data detected (preparing to process)."); } try { final DiskFileItemFactory fac = new DiskFileItemFactory(); final PortletFileUpload pfu = new PortletFileUpload(fac); final long maxSize = pfu.getFileSizeMax(); // FixMe!! pfu.setFileSizeMax(maxSize); pfu.setSizeMax(maxSize); fac.setSizeThreshold((int) (maxSize + 1L)); List<FileItem> items = pfu.parseRequest((ActionRequest) req); for (FileItem f : items) { if (log.isDebugEnabled()) { log.debug("Processing file upload: name='" + f.getName() + "',fieldName='" + f.getFieldName() + "'"); } InputStream inpt = f.getInputStream(); rrr.setAttribute(f.getFieldName(), inpt); rrr.setAttribute(f.getFieldName() + "_FileItem", f); streams.add(inpt); } } catch (Throwable t) { String msg = "Cernunnos portlet failed to process multipart " + "form data from the request."; throw new RuntimeException(msg, t); } } else { if (log.isDebugEnabled()) { log.debug("Multipart form data was not detected."); } } // Anything that should be included from the spring_context? if (spring_context != null && spring_context.containsBean("requestAttributes")) { Map<String, Object> requestAttributes = (Map<String, Object>) spring_context .getBean("requestAttributes"); for (Map.Entry entry : requestAttributes.entrySet()) { rrr.setAttribute((String) entry.getKey(), entry.getValue()); } } runner.run(k, rrr); // Clean up resources... if (streams.size() > 0) { try { for (InputStream inpt : streams) { inpt.close(); } } catch (Throwable t) { String msg = "Cernunnos portlet failed to release resources."; throw new RuntimeException(msg, t); } } }
From source file:org.dihedron.strutlets.ActionContext.java
/** * Initialise the attributes map used to emulate the per-request attributes; * this map will simulate action-scoped request parameters, and will be populated * with attributes that must be visible to all the render, serve resource and * event handling requests coming after an action processing request. These * parameters will be reset by the <code>ActionController</code>as soon as a * new action processing request comes. * //from www.ja va 2s. co m * @param response * the portlet response. * @param invocation * the optional <code>ActionInvocation</code> object, only available in the * context of an action or event processing, not in the render phase. * @throws StrutletsException */ static void bindContext(GenericPortlet portlet, PortletRequest request, PortletResponse response, Properties configuration, ApplicationServer server, PortalServer portal, FileUploadConfiguration uploadInfo) throws StrutletsException { logger.debug("initialising the action context for thread {}", Thread.currentThread().getId()); getContext().portlet = portlet; getContext().request = request; getContext().response = response; getContext().configuration = configuration; getContext().server = server; getContext().portal = portal; getContext().renderParametersChanged = false; // check if a map for REQUEST-scoped attributes is already available in // the PORTLET, if not instantiate it and load it into PORTLET scope PortletSession session = request.getPortletSession(); @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>) session.getAttribute(getRequestScopedAttributesKey(), PortletSession.PORTLET_SCOPE); if (map == null) { logger.trace("installing REQUEST scoped attributes map into PORTLET scope"); session.setAttribute(getRequestScopedAttributesKey(), new HashMap<String, Object>(), PortletSession.PORTLET_SCOPE); } // this might be a multipart/form-data request, in which case we enable // support for file uploads and read them from the input stream using // a tweaked version of Apache Commons FileUpload facilities (in order // to support file uploads in AJAX requests too!). if (request instanceof ClientDataRequest) { // this is where we try to retrieve all files (if there are any that were // uploaded) and store them as temporary files on disk; these objects will // be accessible as ordinary values under the "FORM" scope through a // custom "filename-to-file" map, which will be clened up when the context // is unbound String encoding = ((ClientDataRequest) request).getCharacterEncoding(); getContext().encoding = Strings.isValid(encoding) ? encoding : DEFAULT_ENCODING; logger.trace("request encoding is: '{}'", getContext().encoding); try { RequestContext context = new ClientDataRequestContext((ClientDataRequest) request); // check that we have a file upload request if (PortletFileUpload.isMultipartContent(context)) { getContext().parts = new HashMap<String, FileItem>(); logger.trace("handling multipart/form-data request"); // create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // register a tracker to perform automatic file cleanup // FileCleaningTracker tracker = FileCleanerCleanup.getFileCleaningTracker(getContext().filter.getServletContext()); // factory.setFileCleaningTracker(tracker); // configure the repository (to ensure a secure temporary location // is used and the size of the ) factory.setRepository(uploadInfo.getRepository()); factory.setSizeThreshold(uploadInfo.getInMemorySizeThreshold()); // create a new file upload handler PortletFileUpload upload = new PortletFileUpload(factory); upload.setSizeMax(uploadInfo.getMaxUploadableTotalSize()); upload.setFileSizeMax(uploadInfo.getMaxUploadableFileSize()); // parse the request & process the uploaded items List<FileItem> items = upload.parseRequest(context); logger.trace("{} items in the multipart/form-data request", items.size()); for (FileItem item : items) { // parameters would be stored with their fully-qualified // name if we didn't remove the portlet namespace String fieldName = item.getFieldName().replaceFirst(getPortletNamespace(), ""); logger.trace("storing field '{}' (type: '{}') into parts map", fieldName, item.isFormField() ? "field" : "file"); getContext().parts.put(fieldName, item); } } else { logger.trace("handling plain form request"); } } catch (FileUploadException e) { logger.warn("error handling uploaded file", e); throw new StrutletsException("Error handling uploaded file", e); } } }
From source file:org.gatein.wcm.portlet.editor.views.ManagerActions.java
public String actionNewImport(ActionRequest request, ActionResponse response, UserWcm userWcm) { log.info("WCM Import: STARTED"); String tmpDir = System.getProperty(Wcm.UPLOADS.TMP_DIR); FileItemFactory factory = new DiskFileItemFactory(Wcm.UPLOADS.MAX_FILE_SIZE, new File(tmpDir)); PortletFileUpload importUpload = new PortletFileUpload(factory); try {//from ww w .j av a 2 s .c om List<FileItem> items = importUpload.parseRequest(request); FileItem file = null; String importStrategy = String.valueOf(Wcm.IMPORT.STRATEGY.NEW); for (FileItem item : items) { if (!item.isFormField()) { file = item; } else { importStrategy = item.getString(); } } // .zip validation if (file != null && file.getContentType() != null && !"application/zip".equalsIgnoreCase(file.getContentType())) { throw new WcmException("File: " + file.getName() + " is not application/zip."); } // log.info("Importing ... " + file.getName() + " with strategy " + importStrategy); wcm.importRepository(file.getInputStream(), importStrategy.charAt(0), userWcm); } catch (Exception e) { log.warning("Error importing file"); e.printStackTrace(); response.setRenderParameter("errorWcm", "Error importing file: " + e.toString()); } log.info("WCM Import: FINISHED"); return Wcm.VIEWS.MANAGER; }
From source file:org.gatein.wcm.portlet.editor.views.UploadsActions.java
public String actionNewUpload(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 {//w ww. j a v a 2 s . c o m List<FileItem> items = upload.parseRequest(request); FileItem file = null; String description = ""; for (FileItem item : items) { if (!item.isFormField()) { file = item; } else { description = item.getString(); } } Upload newUpload = new Upload(); newUpload.setFileName(file.getName()); newUpload.setMimeType(file.getContentType()); newUpload.setDescription(description); wcm.create(newUpload, file.getInputStream(), 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.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 w w .j av a 2 s . co m 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.infoglue.calendar.actions.CalendarUploadAbstractAction.java
public File getFile() { try {//from ww w. jav a2 s. c om 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); return uploadedFile; } } } catch (Exception e) { e.printStackTrace(); } return file; }