List of usage examples for org.apache.commons.fileupload FileItem getInputStream
InputStream getInputStream() throws IOException;
From source file:com.znsx.cms.web.controller.TmDeviceController.java
@InterfaceDescription(logon = false, method = "Save_Vms_Command", cmd = "1015") @RequestMapping("/save_vms_command.xml") public void saveVmsCommand(HttpServletRequest request, HttpServletResponse response) throws Exception { Image image = null;/* ww w. jav a2s. c o m*/ // ? boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { // ResourceVO resource = null; // ?Filedata? boolean uploadFlag = false; // ?? List<InputStream> ins = new LinkedList<InputStream>(); // ? DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items = upload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); String fieldName = item.getFieldName(); // ??sessionId if ("sessionId".equals(fieldName)) { String sessionId = item.getString(); if (StringUtils.isBlank(sessionId)) { throw new BusinessException(ErrorCode.PARAMETER_NOT_FOUND, "missing [sessionId]"); } // ?sessionId resource = userManager.checkSession(sessionId); } // ? if (fieldName.startsWith("Filedata")) { uploadFlag = true; InputStream in = item.getInputStream(); ins.add(in); } } if (!uploadFlag) { throw new BusinessException(ErrorCode.MISSING_PARAMETER_FILEDATA, "Parameter [Filedata] not found !"); } // ???? List<String> ids = tmDeviceManager.saveVmsCommand(ins); BaseDTO dto = new BaseDTO(); dto.setCmd("1015"); dto.setMethod("Save_Vms_Command"); Document doc = new Document(); Element root = ElementUtil.createElement("Response", dto); doc.setRootElement(root); int seq = 0; for (String id : ids) { Element command = new Element("Command"); command.setAttribute("Id", id); command.setAttribute("Seq", seq++ + ""); root.addContent(command); } writePageWithContentLength(response, doc); } else { throw new BusinessException(ErrorCode.NOT_MULTIPART_REQUEST, "Not multipart request !"); } }
From source file:edu.ucsd.library.dams.api.DAMSAPIServlet.java
private InputBundle multipartInput(HttpServletRequest req, String objid, String cmpid, String fileid) throws IOException, SizeLimitExceededException { // process parts Map<String, String[]> params = new HashMap<String, String[]>(); params.putAll(req.getParameterMap()); InputStream in = null;// w w w . j a v a 2 s . c o m FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); if (maxUploadSize != -1L) { upload.setSizeMax(maxUploadSize); } List items = null; try { items = upload.parseRequest(req); } catch (SizeLimitExceededException ex) { throw ex; } catch (Exception ex) { ex.printStackTrace(); } for (int i = 0; items != null && i < items.size(); i++) { FileItem item = (FileItem) items.get(i); // form fields go in parameter map if (item.isFormField()) { params.put(item.getFieldName(), new String[] { item.getString() }); log.debug("Parameter: " + item.getFieldName() + " = " + item.getString()); } // file gets opened as an input stream else { in = item.getInputStream(); log.debug("File: " + item.getFieldName() + ", " + item.getName()); params.put("sourceFileName", new String[] { item.getName() }); } } // if no file upload found, check for locally-staged file if (in == null) { in = alternateStream(params, objid, cmpid, fileid); } return new InputBundle(params, in); }
From source file:ffsutils.TaskUtils.java
public static ArrayList<TaskImage> getTaskUpImag(Connection connconn, String tranid1, UserAccount userName, String Description, String filetype, FileItem thisfile) throws SQLException { String tranid2;//from w w w.ja va2 s.c om Integer comp = 2; Integer tranlen = tranid1.length(); int retval = comp.compareTo(tranlen); if (retval > 0) { tranid2 = "0" + tranid1; } else if (retval < 0) { tranid2 = tranid1.substring(tranid1.length() - 2); } else { tranid2 = tranid1; } System.out.println( "getTaskUpImag " + userName + " size " + String.valueOf(thisfile.getSize()) + " " + tranid2); PreparedStatement pstm2 = null; FileInputStream fis; pstm2 = connconn.prepareStatement("insert into " + userName.getcompany() + ".taskimag" + tranid2 + " (user, dateup,imagedesc, taskid, imagetype, imag1) values (?, current_timestamp, ? , '" + tranid1 + "' ,'" + filetype + "', ?)"); //PreparedStatement pstm2 = connconn.prepareStatement(sql2); OutputStream inputstream = null; try { inputstream = thisfile.getOutputStream(); } catch (Exception ex) { ex.printStackTrace(); } pstm2.setString(1, userName.getUserName()); pstm2.setString(2, Description); //pstm2.setBlob(3,inputstream); try { pstm2.setBinaryStream(3, thisfile.getInputStream(), (int) thisfile.getSize()); } catch (IOException e) { e.printStackTrace(); } // pstm2.setString(1, tranid1); Integer temp1 = pstm2.executeUpdate(); String sql = "Select * from " + userName.getcompany() + ".taskimag" + tranid2 + " a where a.taskid =?"; PreparedStatement pstm = connconn.prepareStatement(sql); pstm.setString(1, tranid1); ResultSet rs = pstm.executeQuery(); ArrayList<TaskImage> list = new ArrayList<TaskImage>(); while (rs.next()) { String Tranid = rs.getString("tranid"); String User = rs.getString("user"); String ImageDesc = rs.getString("imagedesc"); String ImageType = rs.getString("imagetype"); Date date = new Date(); Calendar calendar = new GregorianCalendar(); calendar.setTime(rs.getTimestamp("dateup")); String year = Integer.toString(calendar.get(Calendar.YEAR)); String month = Integer.toString(calendar.get(Calendar.MONTH) + 1); String day = Integer.toString(calendar.get(Calendar.DAY_OF_MONTH)); String hour = Integer.toString(calendar.get(Calendar.HOUR_OF_DAY)); String minute = Integer.toString(calendar.get(Calendar.MINUTE)); int length = month.length(); if (length == 1) { month = "0" + month; } int length2 = day.length(); if (length2 == 1) { day = "0" + day; } int length3 = hour.length(); if (length3 == 1) { hour = "0" + hour; } int length4 = minute.length(); if (length4 == 1) { minute = "0" + minute; } String thistime = year + "/" + month + "/" + day + " " + hour + ":" + minute; String DateUp = thistime; TaskImage taskimage = new TaskImage(); taskimage.setTranid(Tranid); taskimage.setUser(User); taskimage.setImageDesc(ImageDesc); taskimage.setImageType(ImageType); taskimage.setDateUp(DateUp); list.add(taskimage); } return list; }
From source file:com.permeance.utility.scriptinghelper.portlets.ScriptingHelperPortlet.java
public void execute(ActionRequest actionRequest, ActionResponse actionResponse) { try {// w w w .j a v a 2 s . co m sCheckPermissions(actionRequest); String portletId = "_" + PortalUtil.getPortletId(actionRequest) + "_"; DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(100 * 1024 * 1024); PortletFileUpload upload = new PortletFileUpload(factory); FileItem fileUploaded = null; List<FileItem> items = upload.parseRequest(actionRequest); for (FileItem fi : items) { if (fi.isFormField()) { actionRequest.setAttribute(fi.getFieldName(), fi.getString()); if (fi.getFieldName().startsWith(portletId)) { actionRequest.setAttribute(fi.getFieldName().substring(portletId.length()), fi.getString()); } } else { fileUploaded = fi; } } String cmd = (String) actionRequest.getAttribute("cmd"); String language = (String) actionRequest.getAttribute("language"); String script = (String) actionRequest.getAttribute("script"); String editorheight = (String) actionRequest.getAttribute("editorheight"); String themesel = (String) actionRequest.getAttribute("themesel"); if (language == null) { language = getDefaultLanguage(); } if (script == null) { script = StringPool.BLANK; } actionResponse.setRenderParameter("language", language); actionResponse.setRenderParameter("script", script); actionResponse.setRenderParameter("editorheight", editorheight); actionResponse.setRenderParameter("themesel", themesel); if ("execute".equals(cmd)) { Map<String, Object> portletObjects = ScriptingHelperUtil.getPortletObjects(getPortletConfig(), getPortletContext(), actionRequest, actionResponse); UnsyncByteArrayOutputStream unsyncByteArrayOutputStream = new UnsyncByteArrayOutputStream(); UnsyncPrintWriter unsyncPrintWriter = UnsyncPrintWriterPool.borrow(unsyncByteArrayOutputStream); portletObjects.put("out", unsyncPrintWriter); _log.info("Executing script"); ScriptingUtil.exec(null, portletObjects, language, script, StringPool.EMPTY_ARRAY); unsyncPrintWriter.flush(); actionResponse.setRenderParameter("script_output", unsyncByteArrayOutputStream.toString()); } else if ("save".equals(cmd)) { String newscriptname = (String) actionRequest.getAttribute("newscriptname"); if (newscriptname == null || newscriptname.trim().length() == 0) { actionResponse.setRenderParameter("script_trace", "No script name specified to save into!"); SessionErrors.add(actionRequest, "error"); return; } _log.info("Saving new script: " + newscriptname.trim()); PortletPreferences prefs = actionRequest.getPreferences(); prefs.setValue("savedscript." + newscriptname.trim(), script); prefs.setValue("lang." + newscriptname.trim(), language); prefs.store(); } else if ("saveinto".equals(cmd)) { String scriptname = (String) actionRequest.getAttribute("savedscript"); if (scriptname == null) { actionResponse.setRenderParameter("script_trace", "No script specified to save into!"); SessionErrors.add(actionRequest, "error"); return; } _log.info("Saving saved script: " + scriptname); PortletPreferences prefs = actionRequest.getPreferences(); prefs.setValue("savedscript." + scriptname, script); prefs.setValue("lang." + scriptname, language); prefs.store(); } else if ("loadfrom".equals(cmd)) { String scriptname = (String) actionRequest.getAttribute("savedscript"); if (scriptname == null) { actionResponse.setRenderParameter("script_trace", "No script specified to load from!"); SessionErrors.add(actionRequest, "error"); return; } _log.info("Loading saved script: " + scriptname); PortletPreferences prefs = actionRequest.getPreferences(); language = prefs.getValue("lang." + scriptname, getDefaultLanguage()); script = prefs.getValue("savedscript." + scriptname, StringPool.BLANK); actionResponse.setRenderParameter("language", language); actionResponse.setRenderParameter("script", script); } else if ("delete".equals(cmd)) { String scriptname = (String) actionRequest.getAttribute("savedscript"); if (scriptname == null) { actionResponse.setRenderParameter("script_trace", "No script specified to delete!"); SessionErrors.add(actionRequest, "error"); return; } _log.info("Deleting saved script: " + scriptname); PortletPreferences prefs = actionRequest.getPreferences(); prefs.reset("savedscript." + scriptname); prefs.reset("lang." + scriptname); prefs.store(); } else if ("import".equals(cmd)) { if (fileUploaded == null) { actionResponse.setRenderParameter("script_trace", "No file was uploaded for import!"); SessionErrors.add(actionRequest, "error"); return; } StringBuilder output = new StringBuilder(); InputStream instream = fileUploaded.getInputStream(); ZipInputStream zipstream = null; try { zipstream = new ZipInputStream(instream); ZipEntry entry = zipstream.getNextEntry(); while (entry != null) { String filename = entry.getName(); if (filename.contains("/")) { int qs = filename.lastIndexOf("/"); if (qs != -1) { filename = filename.substring(qs + 1); } } if (filename.contains("\\")) { int qs = filename.lastIndexOf("\\"); if (qs != -1) { filename = filename.substring(qs + 1); } } String ext = StringPool.BLANK; if (filename.length() > 0) { int qs = filename.lastIndexOf("."); if (qs > 0) { ext = filename.substring(qs + 1); filename = filename.substring(0, qs); } } String lang = resolveLanguage(ext); String imscript = getStreamAsString(zipstream, "utf-8", false); if (imscript != null && imscript.length() > 0) { _log.info("Importing script \"" + filename + "\" of type " + lang); output.append("Importing script \"" + filename + "\" of type " + lang + "\n"); PortletPreferences prefs = actionRequest.getPreferences(); prefs.setValue("savedscript." + filename, imscript); prefs.setValue("lang." + filename, lang); prefs.store(); } entry = zipstream.getNextEntry(); } actionResponse.setRenderParameter("script_output", output.toString()); } finally { try { if (zipstream != null) { zipstream.close(); } } catch (Exception e) { } try { if (instream != null) { instream.close(); } } catch (Exception e) { } } _log.info(fileUploaded.getName()); } SessionMessages.add(actionRequest, "success"); } catch (Exception e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); pw.close(); actionResponse.setRenderParameter("script_trace", sw.toString()); _log.error(e); SessionErrors.add(actionRequest, e.toString()); } }
From source file:fr.paris.lutece.plugins.directory.web.DirectoryJspBean.java
/** * ImportDirectory record//from ww w . j ava 2 s . c o m * @param request the Http Request * @throws AccessDeniedException the {@link AccessDeniedException} * @return The URL to go after performing the action */ public String doImportField(HttpServletRequest request) throws AccessDeniedException { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; FileItem fileItem = multipartRequest.getFile(PARAMETER_FILE_IMPORT); String strMimeType = FileSystemUtil.getMIMEType(FileUploadService.getFileNameOnly(fileItem)); if ((fileItem == null) || (fileItem.getName() == null) || DirectoryUtils.EMPTY_STRING.equals(fileItem.getName())) { Object[] tabRequiredFields = { I18nService.getLocalizedString(FIELD_FILE_IMPORT, getLocale()) }; return AdminMessageService.getMessageUrl(request, MESSAGE_MANDATORY_FIELD, tabRequiredFields, AdminMessage.TYPE_STOP); } if ((!strMimeType.equals(CONSTANT_MIME_TYPE_CSV) && !strMimeType.equals(CONSTANT_MIME_TYPE_OCTETSTREAM) && !strMimeType.equals(CONSTANT_MIME_TYPE_TEXT_CSV)) || !fileItem.getName().toLowerCase().endsWith(CONSTANT_EXTENSION_CSV_FILE)) { return AdminMessageService.getMessageUrl(request, MESSAGE_ERROR_CSV_FILE_IMPORT, AdminMessage.TYPE_STOP); } String strIdEntry = request.getParameter(PARAMETER_ID_ENTRY); int nIdEntry = DirectoryUtils.convertStringToInt(strIdEntry); IEntry entry = EntryHome.findByPrimaryKey(nIdEntry, getPlugin()); String strIdDirectory = request.getParameter(PARAMETER_ID_DIRECTORY); int nIdDirectory = DirectoryUtils.convertStringToInt(strIdDirectory); Directory directory = DirectoryHome.findByPrimaryKey(nIdDirectory, getPlugin()); if ((entry == null) || (directory == null) || !RBACService.isAuthorized(Directory.RESOURCE_TYPE, strIdDirectory, DirectoryResourceIdService.PERMISSION_MODIFY, getUser())) { throw new AccessDeniedException(MESSAGE_ACCESS_DENIED); } Character strCsvSeparator = AppPropertiesService.getProperty(PROPERTY_IMPORT_CSV_DELIMITER).charAt(0); _searchFields.setError(new StringBuffer()); try { InputStreamReader inputStreamReader = new InputStreamReader(fileItem.getInputStream()); CSVReader csvReader = new CSVReader(inputStreamReader, strCsvSeparator, '\"'); String[] nextLine; _searchFields.setCountLine(0); _searchFields.setCountLineFailure(0); while ((nextLine = csvReader.readNext()) != null) { _searchFields.setCountLine(_searchFields.getCountLine() + 1); if (nextLine.length != IMPORT_FIELD_NB_COLUMN_MAX) { _searchFields.getError().append(I18nService.getLocalizedString(PROPERTY_LINE, getLocale())); _searchFields.getError().append(_searchFields.getCountLine()); _searchFields.getError().append(" > "); _searchFields.getError().append( I18nService.getLocalizedString(MESSAGE_ERROR_CSV_NUMBER_SEPARATOR, getLocale())); _searchFields.getError().append("<br/>"); _searchFields.setCountLineFailure(_searchFields.getCountLineFailure() + 1); } else { Field field = new Field(); field.setEntry(entry); try { getImportFieldData(request, field, nextLine); FieldHome.create(field, getPlugin()); } catch (DirectoryErrorException error) { _searchFields.getError().append(I18nService.getLocalizedString(PROPERTY_LINE, getLocale())); _searchFields.getError().append(_searchFields.getCountLine()); _searchFields.getError().append(" > "); if (error.isMandatoryError()) { Object[] tabRequiredFields = { error.getTitleField() }; _searchFields.getError().append(I18nService.getLocalizedString( MESSAGE_DIRECTORY_ERROR_MANDATORY_FIELD, tabRequiredFields, getLocale())); } else { Object[] tabRequiredFields = { error.getTitleField(), error.getErrorMessage() }; _searchFields.getError().append(I18nService.getLocalizedString(MESSAGE_DIRECTORY_ERROR, tabRequiredFields, getLocale())); } _searchFields.getError().append("<br/>"); _searchFields.setCountLineFailure(_searchFields.getCountLineFailure() + 1); } } } } catch (IOException e) { AppLogService.error(e); } return AppPathService.getBaseUrl(request) + JSP_IMPORT_FIELD + DirectoryUtils.CONSTANT_INTERROGATION_MARK + PARAMETER_ID_DIRECTORY + DirectoryUtils.CONSTANT_EQUAL + nIdDirectory + DirectoryUtils.CONSTANT_AMPERSAND + PARAMETER_ID_ENTRY + DirectoryUtils.CONSTANT_EQUAL + nIdEntry + DirectoryUtils.CONSTANT_AMPERSAND + PARAMETER_SESSION + "=" + PARAMETER_SESSION; }
From source file:de.ingrid.portal.portlets.ContactPortlet.java
public void processAction(ActionRequest request, ActionResponse actionResponse) throws PortletException, IOException { List<FileItem> items = null; File uploadFile = null;//from w ww . ja v a 2s. com boolean uploadEnable = PortalConfig.getInstance().getBoolean(PortalConfig.PORTAL_CONTACT_UPLOAD_ENABLE, Boolean.FALSE); int uploadSize = PortalConfig.getInstance().getInt(PortalConfig.PORTAL_CONTACT_UPLOAD_SIZE, 10); RequestContext requestContext = (RequestContext) request.getAttribute(RequestContext.REQUEST_PORTALENV); HttpServletRequest servletRequest = requestContext.getRequest(); if (ServletFileUpload.isMultipartContent(servletRequest)) { DiskFileItemFactory factory = new DiskFileItemFactory(); // Set factory constraints factory.setSizeThreshold(uploadSize * 1000 * 1000); File file = new File("."); factory.setRepository(file); ServletFileUpload.isMultipartContent(servletRequest); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(uploadSize * 1000 * 1000); // Parse the request try { items = upload.parseRequest(servletRequest); } catch (FileUploadException e) { // TODO Auto-generated catch block } } if (items != null) { // check form input if (request.getParameter(PARAMV_ACTION_DB_DO_REFRESH) != null) { ContactForm cf = (ContactForm) Utils.getActionForm(request, ContactForm.SESSION_KEY, ContactForm.class); cf.populate(items); String urlViewParam = "?" + Utils.toURLParam(Settings.PARAM_ACTION, Settings.MSGV_TRUE); actionResponse.sendRedirect(actionResponse.encodeURL(Settings.PAGE_CONTACT + urlViewParam)); return; } else { Boolean isResponseCorrect = false; ContactForm cf = (ContactForm) Utils.getActionForm(request, ContactForm.SESSION_KEY, ContactForm.class); cf.populate(items); if (!cf.validate()) { // add URL parameter indicating that portlet action was called // before render request String urlViewParam = "?" + Utils.toURLParam(Settings.PARAM_ACTION, Settings.MSGV_TRUE); actionResponse.sendRedirect(actionResponse.encodeURL(Settings.PAGE_CONTACT + urlViewParam)); return; } //remenber that we need an id to validate! String sessionId = request.getPortletSession().getId(); //retrieve the response boolean enableCaptcha = PortalConfig.getInstance().getBoolean("portal.contact.enable.captcha", Boolean.TRUE); if (enableCaptcha) { String response = request.getParameter("jcaptcha"); for (FileItem item : items) { if (item.getFieldName() != null) { if (item.getFieldName().equals("jcaptcha")) { response = item.getString(); break; } } } // Call the Service method try { isResponseCorrect = CaptchaServiceSingleton.getInstance().validateResponseForID(sessionId, response); } catch (CaptchaServiceException e) { //should not happen, may be thrown if the id is not valid } } if (isResponseCorrect || !enableCaptcha) { try { IngridResourceBundle messages = new IngridResourceBundle( getPortletConfig().getResourceBundle(request.getLocale()), request.getLocale()); HashMap mailData = new HashMap(); mailData.put("user.name.given", cf.getInput(ContactForm.FIELD_FIRSTNAME)); mailData.put("user.name.family", cf.getInput(ContactForm.FIELD_LASTNAME)); mailData.put("user.employer", cf.getInput(ContactForm.FIELD_COMPANY)); mailData.put("user.business-info.telecom.telephone", cf.getInput(ContactForm.FIELD_PHONE)); mailData.put("user.business-info.online.email", cf.getInput(ContactForm.FIELD_EMAIL)); mailData.put("user.area.of.profession", messages.getString("contact.report.email.area.of.profession." + cf.getInput(ContactForm.FIELD_ACTIVITY))); mailData.put("user.interest.in.enviroment.info", messages.getString("contact.report.email.interest.in.enviroment.info." + cf.getInput(ContactForm.FIELD_INTEREST))); if (cf.hasInput(ContactForm.FIELD_NEWSLETTER)) { Session session = HibernateUtil.currentSession(); Transaction tx = null; try { mailData.put("user.subscribed.to.newsletter", "yes"); // check for email address in newsletter list tx = session.beginTransaction(); List newsletterDataList = session.createCriteria(IngridNewsletterData.class) .add(Restrictions.eq("emailAddress", cf.getInput(ContactForm.FIELD_EMAIL))) .list(); tx.commit(); // register for newsletter if not already registered if (newsletterDataList.isEmpty()) { IngridNewsletterData data = new IngridNewsletterData(); data.setFirstName(cf.getInput(ContactForm.FIELD_FIRSTNAME)); data.setLastName(cf.getInput(ContactForm.FIELD_LASTNAME)); data.setEmailAddress(cf.getInput(ContactForm.FIELD_EMAIL)); data.setDateCreated(new Date()); tx = session.beginTransaction(); session.save(data); tx.commit(); } } catch (Throwable t) { if (tx != null) { tx.rollback(); } throw new PortletException(t.getMessage()); } finally { HibernateUtil.closeSession(); } } else { mailData.put("user.subscribed.to.newsletter", "no"); } mailData.put("message.body", cf.getInput(ContactForm.FIELD_MESSAGE)); Locale locale = request.getLocale(); String language = locale.getLanguage(); String localizedTemplatePath = EMAIL_TEMPLATE; int period = localizedTemplatePath.lastIndexOf("."); if (period > 0) { String fixedTempl = localizedTemplatePath.substring(0, period) + "_" + language + "." + localizedTemplatePath.substring(period + 1); if (new File(getPortletContext().getRealPath(fixedTempl)).exists()) { localizedTemplatePath = fixedTempl; } } String emailSubject = messages.getString("contact.report.email.subject"); if (PortalConfig.getInstance().getBoolean("email.contact.subject.add.topic", Boolean.FALSE)) { if (cf.getInput(ContactForm.FIELD_ACTIVITY) != null && !cf.getInput(ContactForm.FIELD_ACTIVITY).equals("none")) { emailSubject = emailSubject + " - " + messages.getString("contact.report.email.area.of.profession." + cf.getInput(ContactForm.FIELD_ACTIVITY)); } } String from = cf.getInput(ContactForm.FIELD_EMAIL); String to = PortalConfig.getInstance().getString(PortalConfig.EMAIL_CONTACT_FORM_RECEIVER, "foo@bar.com"); String text = Utils.mergeTemplate(getPortletConfig(), mailData, "map", localizedTemplatePath); if (uploadEnable) { if (uploadEnable) { for (FileItem item : items) { if (item.getFieldName() != null) { if (item.getFieldName().equals("upload")) { uploadFile = new File(sessionId + "_" + item.getName()); // read this file into InputStream InputStream inputStream = item.getInputStream(); // write the inputStream to a FileOutputStream OutputStream out = new FileOutputStream(uploadFile); int read = 0; byte[] bytes = new byte[1024]; while ((read = inputStream.read(bytes)) != -1) { out.write(bytes, 0, read); } inputStream.close(); out.flush(); out.close(); break; } } } } Utils.sendEmail(from, emailSubject, new String[] { to }, text, null, uploadFile); } else { Utils.sendEmail(from, emailSubject, new String[] { to }, text, null); } } catch (Throwable t) { cf.setError("", "Error sending mail from contact form."); log.error("Error sending mail from contact form.", t); } // temporarily show same page with content String urlViewParam = "?" + Utils.toURLParam(Settings.PARAM_ACTION, PARAMV_ACTION_SUCCESS); actionResponse.sendRedirect(actionResponse.encodeURL(Settings.PAGE_CONTACT + urlViewParam)); } else { cf.setErrorCaptcha(); String urlViewParam = "?" + Utils.toURLParam(Settings.PARAM_ACTION, Settings.MSGV_TRUE); actionResponse.sendRedirect(actionResponse.encodeURL(Settings.PAGE_CONTACT + urlViewParam)); return; } } } else { ContactForm cf = (ContactForm) Utils.getActionForm(request, ContactForm.SESSION_KEY, ContactForm.class); cf.setErrorUpload(); String urlViewParam = "?" + Utils.toURLParam(Settings.PARAM_ACTION, Settings.MSGV_TRUE); actionResponse.sendRedirect(actionResponse.encodeURL(Settings.PAGE_CONTACT + urlViewParam)); return; } }
From source file:fr.paris.lutece.plugins.directory.web.DirectoryJspBean.java
/** * ImportDirectory record/* w w w .j a v a 2s . c o m*/ * @param request the Http Request * @throws AccessDeniedException the {@link AccessDeniedException} * @return The URL to go after performing the action */ public String doImportDirectoryRecord(HttpServletRequest request) throws AccessDeniedException { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; FileItem fileItem = multipartRequest.getFile(PARAMETER_FILE_IMPORT); String strMimeType = FileSystemUtil.getMIMEType(FileUploadService.getFileNameOnly(fileItem)); if ((fileItem == null) || (fileItem.getName() == null) || DirectoryUtils.EMPTY_STRING.equals(fileItem.getName())) { Object[] tabRequiredFields = { I18nService.getLocalizedString(FIELD_FILE_IMPORT, getLocale()) }; return AdminMessageService.getMessageUrl(request, MESSAGE_MANDATORY_FIELD, tabRequiredFields, AdminMessage.TYPE_STOP); } if ((!strMimeType.equals(CONSTANT_MIME_TYPE_CSV) && !strMimeType.equals(CONSTANT_MIME_TYPE_OCTETSTREAM) && !strMimeType.equals(CONSTANT_MIME_TYPE_TEXT_CSV)) || !fileItem.getName().toLowerCase().endsWith(CONSTANT_EXTENSION_CSV_FILE)) { return AdminMessageService.getMessageUrl(request, MESSAGE_ERROR_CSV_FILE_IMPORT, AdminMessage.TYPE_STOP); } String strIdDirectory = request.getParameter(PARAMETER_ID_DIRECTORY); int nIdDirectory = DirectoryUtils.convertStringToInt(strIdDirectory); Directory directory = DirectoryHome.findByPrimaryKey(nIdDirectory, getPlugin()); if ((directory == null) || !RBACService.isAuthorized(Directory.RESOURCE_TYPE, strIdDirectory, DirectoryResourceIdService.PERMISSION_MANAGE_RECORD, getUser())) { throw new AccessDeniedException(MESSAGE_ACCESS_DENIED); } Character strCsvSeparator = AppPropertiesService.getProperty(PROPERTY_IMPORT_CSV_DELIMITER).charAt(0); _searchFields.setError(new StringBuffer()); EntryFilter filter = new EntryFilter(); filter.setIdDirectory(nIdDirectory); filter.setIsComment(EntryFilter.FILTER_FALSE); filter.setIsEntryParentNull(EntryFilter.FILTER_TRUE); List<IEntry> listEntry = new ArrayList<IEntry>(); List<IEntry> listEntryFirstLevel = EntryHome.getEntryList(filter, getPlugin()); filter.setIsEntryParentNull(EntryFilter.ALL_INT); for (IEntry entry : listEntryFirstLevel) { if (!entry.getEntryType().getGroup()) { listEntry.add(EntryHome.findByPrimaryKey(entry.getIdEntry(), getPlugin())); } filter.setIdEntryParent(entry.getIdEntry()); List<IEntry> listChildren = EntryHome.getEntryList(filter, getPlugin()); for (IEntry entryChild : listChildren) { listEntry.add(EntryHome.findByPrimaryKey(entryChild.getIdEntry(), getPlugin())); } } Object[] tabEntry = listEntry.toArray(); try { InputStreamReader inputStreamReader = new InputStreamReader(fileItem.getInputStream()); CSVReader csvReader = new CSVReader(inputStreamReader, strCsvSeparator, '\"'); String[] nextLine; _searchFields.setCountLine(0); _searchFields.setCountLineFailure(0); while ((nextLine = csvReader.readNext()) != null) { _searchFields.setCountLine(_searchFields.getCountLine() + 1); if (nextLine.length != tabEntry.length) { _searchFields.getError().append(I18nService.getLocalizedString(PROPERTY_LINE, getLocale())); _searchFields.getError().append(_searchFields.getCountLine()); _searchFields.getError().append(" > "); _searchFields.getError().append( I18nService.getLocalizedString(MESSAGE_ERROR_CSV_NUMBER_SEPARATOR, getLocale())); _searchFields.getError().append("<br/>"); _searchFields.setCountLineFailure(_searchFields.getCountLineFailure() + 1); } else { Record record = new Record(); record.setDirectory(directory); List<RecordField> listRecordField = new ArrayList<RecordField>(); try { for (int i = 0; i < nextLine.length; i++) { ((IEntry) tabEntry[i]).getImportRecordFieldData(record, nextLine[i], true, listRecordField, getLocale()); } record.setListRecordField(listRecordField); record.setDateCreation(DirectoryUtils.getCurrentTimestamp()); //Autopublication record.setEnabled(true); _recordService.create(record, getPlugin()); } catch (DirectoryErrorException error) { _searchFields.getError().append(I18nService.getLocalizedString(PROPERTY_LINE, getLocale())); _searchFields.getError().append(_searchFields.getCountLine()); _searchFields.getError().append(" > "); if (error.isMandatoryError()) { Object[] tabRequiredFields = { error.getTitleField() }; _searchFields.getError().append(I18nService.getLocalizedString( MESSAGE_DIRECTORY_ERROR_MANDATORY_FIELD, tabRequiredFields, getLocale())); } else { Object[] tabRequiredFields = { error.getTitleField(), error.getErrorMessage() }; _searchFields.getError().append(I18nService.getLocalizedString(MESSAGE_DIRECTORY_ERROR, tabRequiredFields, getLocale())); } _searchFields.getError().append("<br/>"); _searchFields.setCountLineFailure(_searchFields.getCountLineFailure() + 1); } } } } catch (IOException e) { AppLogService.error(e); } return getJspImportDirectoryRecord(request, nIdDirectory); }
From source file:com.portfolio.data.provider.MysqlDataProvider.java
@Override public Object postPortfolioZip(MimeType mimeType, MimeType mimeType2, HttpServletRequest httpServletRequest, int userId, int groupId, String modelId, int substid) throws IOException { if (!credential.isAdmin(userId) && !credential.isCreator(userId)) throw new RestWebApplicationException(Status.FORBIDDEN, "No admin right"); boolean isMultipart = ServletFileUpload.isMultipartContent(httpServletRequest); // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Configure a repository (to ensure a secure temp location is used) ServletContext servletContext = httpServletRequest.getSession().getServletContext(); File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir"); factory.setRepository(repository);/*www . j a v a 2 s. c om*/ // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); DataInputStream inZip = null; // Parse the request try { List<FileItem> items = upload.parseRequest(httpServletRequest); // Process the uploaded items Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (!item.isFormField()) { inZip = new DataInputStream(item.getInputStream()); break; } } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } String foldersfiles = null; String filename; String[] xmlFiles; String[] allFiles; // int formDataLength = httpServletRequest.getContentLength(); byte[] buff = new byte[0x100000]; // 1MB buffer // Recuperation de l'heure laquelle le zip est cr //Calendar cal = Calendar.getInstance(); //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss_S"); //String now = sdf.format(cal.getTime()); this.genererPortfolioUuidPreliminaire(); javax.servlet.http.HttpSession session = httpServletRequest.getSession(true); String ppath = session.getServletContext().getRealPath("/"); String outsideDir = ppath.substring(0, ppath.lastIndexOf(File.separator)) + "_files" + File.separator; File outsideDirectoryFile = new File(outsideDir); System.out.println(outsideDir); // if the directory does not exist, create it if (!outsideDirectoryFile.exists()) { outsideDirectoryFile.mkdir(); } //Creation du zip filename = outsideDir + "xml_" + this.portfolioUuidPreliminaire + ".zip"; FileOutputStream outZip = new FileOutputStream(filename); int len; while ((len = inZip.read(buff)) != -1) { outZip.write(buff, 0, len); } inZip.close(); outZip.close(); //-- unzip -- foldersfiles = unzip(filename, outsideDir + this.portfolioUuidPreliminaire + File.separator); //TODO Attention si plusieurs XML dans le fichier xmlFiles = findFiles(outsideDir + this.portfolioUuidPreliminaire + File.separator, "xml"); allFiles = findFiles(outsideDir + this.portfolioUuidPreliminaire + File.separator, null); ////// Lecture du fichier de portfolio StringBuffer outTrace = new StringBuffer(); //// Importation du portfolio //--- Read xml fileL ---- ///// Pour associer l'ancien uuid -> nouveau, pour les fichiers HashMap<String, String> resolve = new HashMap<String, String>(); String portfolioUuid = "erreur"; boolean hasLoaded = false; try { for (int i = 0; i < xmlFiles.length; i++) { String xmlFilepath = xmlFiles[i]; String xmlFilename = xmlFilepath.substring(xmlFilepath.lastIndexOf(File.separator)); if (xmlFilename.contains("_")) continue; // Case when we add an xml in the portfolio BufferedReader br = new BufferedReader(new FileReader(new File(xmlFilepath))); String line; StringBuilder sb = new StringBuilder(); while ((line = br.readLine()) != null) { sb.append(line.trim()); } String xml = "?"; xml = sb.toString(); portfolioUuid = UUID.randomUUID().toString(); if (xml.contains("<portfolio")) // Le porfolio (peux mieux faire) { Document doc = DomUtils.xmlString2Document(xml, outTrace); Node rootNode = (doc.getElementsByTagName("portfolio")).item(0); if (rootNode == null) throw new Exception("Root Node (portfolio) not found !"); else { rootNode = (doc.getElementsByTagName("asmRoot")).item(0); String uuid = UUID.randomUUID().toString(); insertMysqlPortfolio(portfolioUuid, uuid, 0, userId); writeNode(rootNode, portfolioUuid, null, userId, 0, uuid, null, 0, 0, false, resolve); } updateMysqlPortfolioActive(portfolioUuid, true); /// Finalement on cre un rle designer int groupid = postCreateRole(portfolioUuid, "designer", userId); /// Ajoute la personne dans ce groupe putUserGroup(Integer.toString(groupid), Integer.toString(userId)); hasLoaded = true; } } } catch (Exception e) { e.printStackTrace(); } if (hasLoaded) for (int i = 0; i < allFiles.length; i++) { String fullPath = allFiles[i]; String tmpFileName = allFiles[i].substring(allFiles[i].lastIndexOf(File.separator) + 1); int index = tmpFileName.indexOf("_"); if (index == -1) index = tmpFileName.indexOf("."); int last = tmpFileName.lastIndexOf(File.separator); if (last == -1) last = 0; String uuid = tmpFileName.substring(last, index); // tmpFileName = allFiles[i].substring(allFiles[i].lastIndexOf(File.separator)+1); String lang; try { // int tmpPos = tmpFileName.indexOf("_"); lang = tmpFileName.substring(index + 1, index + 3); if ("un".equals(lang)) // Hack sort of fixing previous implementation lang = "en"; } catch (Exception ex) { lang = ""; } InputStream is = new FileInputStream(allFiles[i]); byte b[] = new byte[is.available()]; is.read(b); String extension; try { extension = tmpFileName.substring(tmpFileName.lastIndexOf(".") + 1); } catch (Exception ex) { extension = null; } // trop long //String tmpMimeType = FileUtils.getMimeType("file://"+allFiles[i]); String tmpMimeType = FileUtils.getMimeTypeFromExtension(extension); // Attention on initialise la ligne file // avec l'UUID d'origine de l'asmContext parent // Il sera mis jour avec l'UUID asmContext final dans writeNode try { UUID tmpUuid = UUID.fromString(uuid); /// base uuid String resolved = resolve.get(uuid); /// New uuid String sessionval = session.getId(); String user = (String) session.getAttribute("user"); // String test = outsideDir+File.separator+this.portfolioUuidPreliminaire+File.separator+tmpFileName; // File file = new File(outsideDir+File.separator+this.portfolioUuidPreliminaire+File.separator+tmpFileName); File file = new File(fullPath); // server backend // fileserver String backend = session.getServletContext().getInitParameter("backendserver"); if (resolved != null) { /// Have to send it in FORM, compatibility with regular file posting PostForm.sendFile(sessionval, backend, user, resolved, lang, file); /// No need to fetch resulting ID, since we provided it /* InputStream objReturn = connect.getInputStream(); StringWriter idResponse = new StringWriter(); IOUtils.copy(objReturn, idResponse); fileid = idResponse.toString(); //*/ } /* if(tmpUuid.toString().equals(uuid)) this.putFile(uuid,lang,tmpFileName,outsideDir,tmpMimeType,extension,b.length,b,userId); //*/ } catch (Exception ex) { // Le nom du fichier ne commence pas par un UUID, // ce n'est donc pas une ressource ex.printStackTrace(); } } File zipfile = new File(filename); zipfile.delete(); File zipdir = new File(outsideDir + this.portfolioUuidPreliminaire + File.separator); zipdir.delete(); return portfolioUuid; }
From source file:net.sourceforge.stripes.controller.multipart.CommonsMultipartWrapper.java
/** * Responsible for constructing a FileBean object for the named file parameter. If there is no * file parameter with the specified name this method should return null. * * @param name the name of the file parameter * @return a FileBean object wrapping the uploaded file *//* w ww .jav a 2 s . co m*/ public FileBean getFileParameterValue(String name) { final FileItem item = this.files.get(name); if (item == null || ((item.getName() == null || item.getName().length() == 0) && item.getSize() == 0)) { return null; } else { // Attempt to ensure the file name is just the basename with no path included String filename = item.getName(); int index; if (WINDOWS_PATH_PREFIX_PATTERN.matcher(filename).find()) index = filename.lastIndexOf('\\'); else index = filename.lastIndexOf('/'); if (index >= 0 && index + 1 < filename.length() - 1) filename = filename.substring(index + 1); // Use an anonymous inner subclass of FileBean that overrides all the // methods that rely on having a File present, to use the FileItem // created by commons upload instead. return new FileBean(null, item.getContentType(), filename, this.charset) { @Override public long getSize() { return item.getSize(); } @Override public InputStream getInputStream() throws IOException { return item.getInputStream(); } @Override public void save(File toFile) throws IOException { try { item.write(toFile); delete(); } catch (Exception e) { if (e instanceof IOException) throw (IOException) e; else { IOException ioe = new IOException("Problem saving uploaded file."); ioe.initCause(e); throw ioe; } } } @Override public void delete() throws IOException { item.delete(); } }; } }
From source file:net.sourceforge.subsonic.controller.ImportPlaylistController.java
@Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { Map<String, Object> map = new HashMap<String, Object>(); try {//from ww w . j a va2s. c o m if (ServletFileUpload.isMultipartContent(request)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<?> items = upload.parseRequest(request); for (Object o : items) { FileItem item = (FileItem) o; if ("file".equals(item.getFieldName()) && !StringUtils.isBlank(item.getName())) { if (item.getSize() > MAX_PLAYLIST_SIZE_MB * 1024L * 1024L) { throw new Exception("The playlist file is too large. Max file size is " + MAX_PLAYLIST_SIZE_MB + " MB."); } String playlistName = FilenameUtils.getBaseName(item.getName()); String fileName = FilenameUtils.getName(item.getName()); String format = StringUtils.lowerCase(FilenameUtils.getExtension(item.getName())); String username = securityService.getCurrentUsername(request); Playlist playlist = playlistService.importPlaylist(username, playlistName, fileName, format, item.getInputStream()); map.put("playlist", playlist); } } } } catch (Exception e) { map.put("error", e.getMessage()); } ModelAndView result = super.handleRequestInternal(request, response); result.addObject("model", map); return result; }