List of usage examples for org.apache.commons.fileupload FileItem get
byte[] get();
From source file:org.pentaho.platform.web.refactor.SolutionManagerUIComponent.java
public Document doFileUpload() { String baseUrl = PentahoSystem.getApplicationContext() .getSolutionPath(SolutionManagerUIComponent.EMPTY_STR); ISolutionRepository repository = PentahoSystem.get(ISolutionRepository.class, session); String path = this.getParameter(SolutionManagerUIComponent.PATH_STR, null); IParameterProvider request = (IParameterProvider) getParameterProviders() .get(IParameterProvider.SCOPE_REQUEST); HttpServletRequest httpRequest = ((HttpRequestParameterProvider) request).getRequest(); /* /* w ww . j ava2s . c o m*/ String contentType = httpRequest.getContentType(); if ((contentType == null) || ((contentType.indexOf("multipart/form-data") < 0) && (contentType.indexOf("multipart/mixed stream") < 0))) { //$NON-NLS-1$ //$NON-NLS-2$ return doGetSolutionStructure(); } DiskFileUpload uploader = new DiskFileUpload(); */ if (!ServletFileUpload.isMultipartContent(httpRequest)) { return doGetSolutionStructure(); } ServletFileUpload uploader = new ServletFileUpload(new DiskFileItemFactory()); try { List fileList = uploader.parseRequest(httpRequest); Iterator iter = fileList.iterator(); while (iter.hasNext()) { FileItem fi = (FileItem) iter.next(); // Check if not form field so as to only handle the file inputs if (!fi.isFormField()) { File tempFileRef = new File(fi.getName()); repository.addSolutionFile(baseUrl, path, tempFileRef.getName(), fi.get(), true); SolutionManagerUIComponent.logger .info(Messages.getString("SolutionManagerUIComponent.INFO_0001_FILE_SAVED") + path + "/" //$NON-NLS-1$//$NON-NLS-2$ + tempFileRef.getName()); } } } catch (FileUploadException e) { SolutionManagerUIComponent.logger.error(e.toString()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return doGetSolutionStructure(); }
From source file:org.pentaho.platform.web.refactor.SubscriptionAdminUIComponent.java
public Document doImport() { HttpServletRequest request = ((HttpRequestParameterProvider) getParameterProviders() .get(HttpRequestParameterProvider.SCOPE_REQUEST)).getRequest(); String contentType = request.getContentType(); if ((contentType == null) || ((contentType.indexOf("multipart/form-data") < 0) //$NON-NLS-1$ && (contentType.indexOf("multipart/mixed stream") < 0))) { //$NON-NLS-1$ return (showCommandResultUI( getErrorMessage(//from w w w.j a v a2 s . co m Messages.getString("SubscriptionAdminUIComponent.ERROR_IMPORT_FILE_NOT_UPLOADED")), //$NON-NLS-1$ SubscriptionAdminUIComponent.NODE_STATUS_ERROR)); } Enumeration enumer = request.getParameterNames(); while (enumer.hasMoreElements()) { System.out.println(enumer.nextElement().toString()); } try { String publishPassword = null; FileItem publishFile = null; // DiskFileUpload uploader = new DiskFileUpload(); ServletFileUpload uploader = new ServletFileUpload(new DiskFileItemFactory()); List fileList = uploader.parseRequest(request); Iterator iter = fileList.iterator(); while (iter.hasNext()) { FileItem fi = (FileItem) iter.next(); if (fi.isFormField()) { publishPassword = new String(fi.get()); } else { publishFile = fi; } } saveFileItem(publishFile, publishPassword); } catch (Throwable t) { return (showCommandResultUI( getException(Messages.getString("SubscriptionAdminUIComponent.ERROR_UNABLE_TO_PARSE_FILE"), t), //$NON-NLS-1$ SubscriptionAdminUIComponent.NODE_STATUS_ERROR)); } return (showCommandResultUI( getOkMessage(Messages.getString("SubscriptionAdminUIComponent.USER_IMPORT_SUCCESSFUL")), //$NON-NLS-1$ SubscriptionAdminUIComponent.NODE_STATUS_OK)); }
From source file:org.pentaho.platform.web.refactor.SubscriptionAdminUIComponent.java
/** * @param fi// w w w . j a v a2s.co m * @param string */ private int saveFileItem(FileItem fi, String password) { ISolutionRepository repository = PentahoSystem.get(ISolutionRepository.class, getSession()); int status = ISolutionRepository.FILE_ADD_SUCCESSFUL; if (checkPublisherKey(PublisherUtil.getPasswordKey(password))) { String solutionPath = PentahoSystem.getApplicationContext().getSolutionPath(""); //$NON-NLS-1$ try { PentahoSystem.systemEntryPoint(); status = repository.publish(solutionPath, "system", "ScheduleAndContentImport.xml", fi.get(), true); } catch (PentahoAccessControlException e) { status = ISolutionRepository.FILE_ADD_FAILED; if (SubscriptionAdminUIComponent.logger.isErrorEnabled()) { SubscriptionAdminUIComponent.logger.error( Messages.getErrorString("SubscriptionAdminUIComponent.ERROR_0104_USER_ERROR"), e); } } finally { PentahoSystem.systemExitPoint(); } } else { status = ISolutionRepository.FILE_ADD_INVALID_PUBLISH_PASSWORD; } return status; }
From source file:org.pentaho.platform.web.servlet.RepositoryFilePublisher.java
protected int doPublish(final List<FileItem> fileItems, final String publishPath, final String publishKey, final String jndiName, final String jdbcDriver, final String jdbcUrl, final String jdbcUserId, final String jdbcPassword, final boolean overwrite, final boolean mkdirs, final IPentahoSession pentahoSession) { ISolutionRepository repository = PentahoSystem.get(ISolutionRepository.class, pentahoSession); int status = ISolutionRepository.FILE_ADD_SUCCESSFUL; String cleanPublishPath = publishPath; // Fix the publish path to prevent problems with the RDBMS repository. if ((publishPath != null) && (publishPath.endsWith("/") || publishPath.endsWith("\\"))) { //$NON-NLS-1$ //$NON-NLS-2$ cleanPublishPath = publishPath.substring(0, publishPath.length() - 1); }/*from www .jav a 2 s .com*/ cleanPublishPath = cleanPublishPath.replace('\\', ISolutionRepository.SEPARATOR); if (RepositoryFilePublisher.checkPublisherKey(publishKey)) { String solutionPath = PentahoSystem.getApplicationContext().getSolutionPath(""); //$NON-NLS-1$ try { PentahoSystem.systemEntryPoint(); // check to see if the publish path exists ISolutionFile folder = repository.getSolutionFile(cleanPublishPath, ISolutionRepository.ACTION_CREATE); if (folder == null) { if (mkdirs) { // we need to create the folder first StringTokenizer tokenizer = new StringTokenizer(cleanPublishPath, "" + ISolutionRepository.SEPARATOR); //$NON-NLS-1$ StringBuilder testPath = new StringBuilder(); int idx = 1; while (tokenizer.hasMoreTokens()) { String folderName = tokenizer.nextToken(); testPath.append(ISolutionRepository.SEPARATOR).append(folderName); ISolutionFile testFolder = repository.getSolutionFile(testPath.toString(), ISolutionRepository.ACTION_CREATE); if (idx == 1 && testFolder == null) { // we do not allow creation of top-level folders status = ISolutionRepository.FILE_ADD_FAILED; break; } else if (testFolder == null) { // create this one String newFolderPath = PentahoSystem.getApplicationContext() .getSolutionPath(testPath.toString()); File newFolder = new File(newFolderPath); repository.createFolder(newFolder); } idx++; } } else { // the folder does not exist status = ISolutionRepository.FILE_ADD_FAILED; } } if (status == ISolutionRepository.FILE_ADD_SUCCESSFUL) { for (int i = 0; i < fileItems.size() && status == ISolutionRepository.FILE_ADD_SUCCESSFUL; i++) { FileItem fi = fileItems.get(i); String name = URLDecoder.decode(fi.getName(), "UTF-8"); status = repository.publish(solutionPath, cleanPublishPath, name, fi.get(), overwrite); } } } catch (PentahoAccessControlException e) { status = ISolutionRepository.FILE_ADD_FAILED; if (RepositoryFilePublisher.logger.isErrorEnabled()) { RepositoryFilePublisher.logger.error("an error occurred", e); } } catch (IOException e) { status = ISolutionRepository.FILE_ADD_FAILED; if (RepositoryFilePublisher.logger.isErrorEnabled()) { RepositoryFilePublisher.logger.error("an error occurred", e); } } finally { PentahoSystem.systemExitPoint(); } } else { status = ISolutionRepository.FILE_ADD_INVALID_PUBLISH_PASSWORD; } return status; }
From source file:org.rhq.enterprise.gui.common.upload.UploadRenderer.java
public void decode(FacesContext context, UIComponent component) { ExternalContext external = context.getExternalContext(); HttpServletRequest request = (HttpServletRequest) external.getRequest(); String clientId = component.getClientId(context); FileItem item = (FileItem) request.getAttribute(clientId); Object newValue;//from ww w. j av a 2s. c o m ValueExpression valueExpression = component.getValueExpression("value"); if (valueExpression != null) { Class valueType = valueExpression.getType(context.getELContext()); if (valueType == byte[].class) { newValue = item.get(); } else if (valueType == InputStream.class) { try { newValue = item.getInputStream(); } catch (IOException ex) { throw new FacesException(ex); } } else { String encoding = request.getCharacterEncoding(); if (encoding != null) { try { newValue = item.getString(encoding); } catch (UnsupportedEncodingException ex) { newValue = item.getString(); } } else { newValue = item.getString(); } } ((EditableValueHolder) component).setSubmittedValue(newValue); ((EditableValueHolder) component).setValid(true); } Object target = component.getAttributes().get("target"); if (target != null) { File file; if (target instanceof File) { file = (File) target; } else { ServletContext servletContext = (ServletContext) external.getContext(); String realPath = servletContext.getRealPath(target.toString()); file = new File(realPath); } try { item.write(file); } catch (Exception ex) { throw new FacesException(ex); } } }
From source file:org.sakaiproject.access.tool.WebServlet.java
/** * Handle file upload requests./*from w w w . ja va 2s . c om*/ * * @param req * @param res */ protected void postUpload(HttpServletRequest req, HttpServletResponse res) { String path = req.getPathInfo(); // System.out.println("path " + path); if (path == null) path = ""; // assume caller has verified that it is a request for content and that it's multipart // loop over attributes in request, picking out the ones // that are file uploads and doing them for (Enumeration e = req.getAttributeNames(); e.hasMoreElements();) { String iname = (String) e.nextElement(); // System.out.println("Item " + iname); Object o = req.getAttribute(iname); // NOTE: Fileitem is from // org.apache.commons.fileupload.FileItem, not // sakai's parameterparser version if (o != null && o instanceof FileItem) { FileItem fi = (FileItem) o; // System.out.println("found file " + fi.getName()); if (!writeFile(fi.getName(), fi.getContentType(), fi.get(), path, req, res, true)) return; } } }
From source file:org.sakaiproject.coursearchive.tool.jsf.CourseArchiveBean.java
public String processActionSaveSyllabus() { String title = currentSyllabus.getTitle(); if (title == null || title.equals("")) { String message = "Cannot save syllabus without a title"; FacesContext fc = FacesContext.getCurrentInstance(); fc.addMessage("itemDetails", new FacesMessage(FacesMessage.SEVERITY_WARN, message, message)); return "syllabusSaved"; }// w w w . j a v a 2 s . com logic.saveSyllabus(currentSyllabus); if (newAttachment != null) { try { FileItem item = (FileItem) newAttachment; String name = item.getName(); String contentType = item.getContentType(); byte[] content = item.get(); logic.createAttachment(currentSyllabus, name, contentType, content); } catch (Exception e) { e.printStackTrace(); } newAttachment = null; } itemSyllabi = wrapSyllabi(logic.getItemSyllabi(currentItem.getItem())); return "syllabusSaved"; }
From source file:org.sakaiproject.feedback.util.SakaiProxy.java
public void sendEmail(String fromUserId, String senderAddress, String toAddress, boolean addNoContactEmailMessage, String siteId, String feedbackType, String userTitle, String userContent, List<FileItem> fileItems, boolean siteExists, String browserNameAndVersion, String osNameAndVersion, String browserSize, String screenSize, String plugins, String ip, String currentTime) {/*from www . j ava2 s . c om*/ final List<Attachment> attachments = new ArrayList<Attachment>(); if (fileItems.size() > 0) { for (FileItem fileItem : fileItems) { String name = fileItem.getName(); if (name.contains("/")) { name = name.substring(name.lastIndexOf("/") + 1); } else if (name.contains("\\")) { name = name.substring(name.lastIndexOf("\\") + 1); } attachments.add( new Attachment(new ByteArrayDataSource(fileItem.get(), fileItem.getContentType()), name)); } } String fromAddress = senderAddress; String fromName = "User not logged in"; String userId = ""; String userEid = ""; if (fromUserId != null) { User user = getUser(fromUserId); fromAddress = user.getEmail(); fromName = user.getDisplayName(); userId = user.getId(); userEid = user.getEid(); } if (fromAddress == null) { logger.error("No email for reporter: " + fromUserId + ". No email will be sent."); return; } final String siteLocale = getSiteProperty(siteId, "locale_string"); Locale locale = null; if (siteLocale != null) { String[] localeParts = siteLocale.split("_"); if (localeParts.length == 1) { locale = new Locale(localeParts[0]); } else if (localeParts.length == 2) { locale = new Locale(localeParts[0], localeParts[1]); } else { locale = Locale.getDefault(); } } else { locale = Locale.getDefault(); } final ResourceLoader rb = new ResourceLoader("org.sakaiproject.feedback"); String subjectTemplate = null; if (feedbackType.equals(Constants.CONTENT)) { subjectTemplate = rb.getString("content_email_subject_template"); } else if (feedbackType.equals(Constants.HELPDESK)) { subjectTemplate = rb.getString("help_email_subject_template"); } else { subjectTemplate = rb.getString("technical_email_subject_template"); } final String formattedSubject = MessageFormat.format(subjectTemplate, new String[] { fromName }); final Site site = getSite(siteId); final String siteTitle = siteExists ? site.getTitle() : "N/A (Site does not exist)"; final String workerNode = serverConfigurationService.getServerId(); final String siteUrl = serverConfigurationService.getPortalUrl() + "/site/" + (siteExists ? site.getId() : siteId); String noContactEmailMessage = ""; final String instance = serverConfigurationService.getServerIdInstance(); final String bodyTemplate = rb.getString("email_body_template"); String formattedBody = MessageFormat.format(bodyTemplate, new String[] { noContactEmailMessage, userId, userEid, fromName, fromAddress, siteTitle, siteId, siteUrl, instance, userTitle, userContent, "\n", browserNameAndVersion, osNameAndVersion, browserSize, screenSize, plugins, ip, workerNode, currentTime }); if (feedbackType.equals(Constants.CONTENT)) { formattedBody = formattedBody + "\n\n\n" + rb.getString("email_body_template_note"); } if (logger.isDebugEnabled()) { logger.debug("fromName: " + fromName); logger.debug("fromAddress: " + fromAddress); logger.debug("toAddress: " + toAddress); logger.debug("userContent: " + userContent); logger.debug("userTitle: " + userTitle); logger.debug("subjectTemplate: " + subjectTemplate); logger.debug("bodyTemplate: " + bodyTemplate); logger.debug("formattedSubject: " + formattedSubject); logger.debug("formattedBody: " + formattedBody); } final EmailMessage msg = new EmailMessage(); msg.setFrom(new EmailAddress(fromAddress, fromName)); msg.setContentType(ContentType.TEXT_PLAIN); msg.setSubject(formattedSubject); msg.setBody(formattedBody); if (attachments != null) { for (Attachment attachment : attachments) { msg.addAttachment(attachment); } } // Copy the sender in msg.addRecipient(RecipientType.CC, fromName, fromAddress); msg.addRecipient(RecipientType.TO, toAddress); new Thread(new Runnable() { public void run() { try { emailService.send(msg, true); } catch (Exception e) { logger.error("Failed to send email.", e); } } }, "Feedback Email Thread").start(); }
From source file:org.sakaiproject.scorm.ui.upload.components.FileUploadForm.java
public File getFile(FileItem fileItem) { if (null == fileItem || fileItem.getSize() <= 0) { notify("noFile"); return null; }/*w w w. ja va2 s.co m*/ if (!CONTENT_TYPE_APPLICATION_ZIP.equals(fileItem.getContentType())) { notify("wrongContentType"); } String filename = fileItem.getName(); File file = new File(getDirectory(), filename); System.out.println("FILE IS: " + file.getAbsolutePath()); byte[] bytes = fileItem.get(); InputStream in = null; FileOutputStream out = null; try { if (null == bytes) { in = fileItem.getInputStream(); } else { in = new ByteArrayInputStream(bytes); } out = new FileOutputStream(file); byte[] buffer = new byte[1024]; int length; while ((length = in.read(buffer)) > 0) { out.write(buffer, 0, length); } } catch (IOException ioe) { log.error("Caught an io exception retrieving the uploaded content package!", ioe); } finally { if (null != out) try { out.close(); } catch (IOException nioe) { log.info("Caught an io exception closing the output stream!", nioe); } } return file; }
From source file:org.sakaiproject.tool.messageforums.DiscussionForumTool.java
public String processUpload(ValueChangeEvent event) { if (LOG.isDebugEnabled()) LOG.debug("processUpload(ValueChangeEvent event) "); if (attachCaneled == false) { Object newValue = event.getNewValue(); if (newValue instanceof String) { return ""; }/*from ww w. j a v a2 s . c om*/ if (newValue == null) { return ""; } try { FileItem item = (FileItem) event.getNewValue(); if (!validateImageSize(item)) { return null; } String fileName = item.getName(); byte[] fileContents = item.get(); ResourcePropertiesEdit props = contentHostingService.newResourceProperties(); String tempS = fileName; int lastSlash = tempS.lastIndexOf("/") > tempS.lastIndexOf("\\") ? tempS.lastIndexOf("/") : tempS.lastIndexOf("\\"); if (lastSlash > 0) { fileName = tempS.substring(lastSlash + 1); } props.addProperty(ResourceProperties.PROP_DISPLAY_NAME, fileName); ContentResource thisAttach = contentHostingService.addAttachmentResource(fileName, item.getContentType(), fileContents, props); RankImage attachObj = rankManager.createRankImageAttachmentObject(thisAttach.getId(), fileName); attachment = attachObj; } catch (Exception e) { LOG.error(this + ".processUpload() in DiscussionForumTool " + e); e.printStackTrace(); } just_created = true; return VIEW_RANK; } return null; }