List of usage examples for org.apache.commons.fileupload FileItem getInputStream
InputStream getInputStream() throws IOException;
From source file:hudson.FilePath.java
/** * Place the data from {@link FileItem} into the file location specified by this {@link FilePath} object. *///from w w w. j a va 2 s.co m public void copyFrom(FileItem file) throws IOException, InterruptedException { if (channel == null) { try { file.write(new File(remote)); } catch (IOException e) { throw e; } catch (Exception e) { throw new IOException2(e); } } else { InputStream i = file.getInputStream(); OutputStream o = write(); try { IOUtils.copy(i, o); } finally { o.close(); i.close(); } } }
From source file:com.edgenius.wiki.webapp.servlet.UploadServlet.java
@SuppressWarnings("unchecked") protected void doService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if ("GET".equalsIgnoreCase(request.getMethod())) { //just render blank page for upload String pageUuid = request.getParameter("puuid"); String spaceUname = request.getParameter("uname"); String draft = request.getParameter("draft"); request.setAttribute("pageUuid", pageUuid); request.setAttribute("spaceUname", spaceUname); request.setAttribute("draft", NumberUtils.toInt(draft, PageType.NONE_DRAFT.value())); request.getRequestDispatcher("/WEB-INF/pages/upload.jsp").forward(request, response); return;/*www . java 2 s.c o m*/ } //post - upload // if(WikiUtil.getUser().isAnonymous()){ // //anonymous can not allow to upload any files PageService pageService = getPageService(); ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); List<FileNode> files = new ArrayList<FileNode>(); String pageUuid = null, spaceUname = null; try { int status = PageType.NONE_DRAFT.value(); // index->filename Map<String, FileItem> fileMap = new HashMap<String, FileItem>(); Map<String, String> descMap = new HashMap<String, String>(); // index->index Map<String, String> indexMap = new HashMap<String, String>(); //offline submission, filename put into hidden variable rather than <input type="file> tag Map<String, String> filenameMap = new HashMap<String, String>(); //TODO: offline submission, version also upload together with file, this give a change to do failure tolerance check: //if version is same with online save, then it is OK, if greater, means it maybe duplicated upload, if less, unpexected case Map<String, String> versionMap = new HashMap<String, String>(); Map<String, Boolean> bulkMap = new HashMap<String, Boolean>(); Map<String, Boolean> sharedMap = new HashMap<String, Boolean>(); List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { String name = item.getFieldName(); if (StringUtils.equals(name, "spaceUname")) { spaceUname = item.getString(Constants.UTF8); } else if (StringUtils.equals(name, "pageUuid")) { pageUuid = item.getString(); } else if (name.startsWith("draft")) { // check this upload is from "click save button" or "auto upload in draft status" status = Integer.parseInt(item.getString()); } else if (name.startsWith("file")) { fileMap.put(name.substring(4), item); indexMap.put(name.substring(4), name.substring(4)); } else if (name.startsWith("desc")) { descMap.put(name.substring(4), item.getString(Constants.UTF8)); } else if (name.startsWith("shar")) { sharedMap.put(name.substring(4), Boolean.parseBoolean(item.getString())); } else if (name.startsWith("name")) { filenameMap.put(name.substring(4), item.getString()); } else if (name.startsWith("vers")) { versionMap.put(name.substring(4), item.getString()); } else if (name.startsWith("bulk")) { bulkMap.put(name.substring(4), BooleanUtils.toBoolean(item.getString())); } } if (StringUtils.isBlank(pageUuid)) { log.error("Attachment can not be load because of page does not save successfully."); throw new PageException("Attachment can not be load because of page does not save successfully."); } List<FileNode> bulkFiles = new ArrayList<FileNode>(); String username = request.getRemoteUser(); // put file/desc pair into final Map for (String id : fileMap.keySet()) { FileItem item = fileMap.get(id); if (item == null || item.getInputStream() == null || item.getSize() <= 0) { log.warn("Empty upload item:" + (item != null ? item.getName() : "")); continue; } FileNode node = new FileNode(); node.setComment(descMap.get(id)); node.setShared(sharedMap.get(id) == null ? false : sharedMap.get(id)); node.setFile(item.getInputStream()); String filename = item.getName(); if (StringUtils.isBlank(filename)) { //this could be offline submission, get name from map filename = filenameMap.get(id); } node.setFilename(FileUtil.getFileName(filename)); node.setContentType(item.getContentType()); node.setIndex(indexMap.get(id)); node.setType(RepositoryService.TYPE_ATTACHMENT); node.setIdentifier(pageUuid); node.setCreateor(username); node.setStatus(status); node.setSize(item.getSize()); node.setBulkZip(bulkMap.get(id) == null ? false : bulkMap.get(id)); files.add(node); if (node.isBulkZip()) bulkFiles.add(node); } if (spaceUname != null && pageUuid != null && files.size() > 0) { files = pageService.uploadAttachments(spaceUname, pageUuid, files, false); //only save non-draft uploaded attachment if (status == 0) { try { getActivityLog().logAttachmentUploaded(spaceUname, pageService.getCurrentPageByUuid(pageUuid).getTitle(), WikiUtil.getUser(), files); } catch (Exception e) { log.warn("Activity log save error for attachment upload", e); } } //as bulk files won't in return list in PageService.uploadAttachments(), here need //append to all return list, but only for client side "uploading panel" clean purpose files.addAll(bulkFiles); //TODO: if version come in together, then do check // if(versionMap.size() > 0){ // for (FileNode node: files) { // // } // } } } catch (RepositoryQuotaException e) { FileNode att = new FileNode(); att.setError(getMessageService().getMessage("err.quota.exhaust")); files = Arrays.asList(att); } catch (AuthenticationException e) { String redir = ((RedirectResponseWrapper) response).getRedirect(); if (redir == null) redir = WikiConstants.URL_LOGIN; log.info("Send Authentication redirect URL " + redir); FileNode att = new FileNode(); att.setError(getMessageService().getMessage("err.authentication.required")); files = Arrays.asList(att); } catch (AccessDeniedException e) { String redir = ((RedirectResponseWrapper) response).getRedirect(); if (redir == null) redir = WikiConstants.URL_ACCESS_DENIED; log.info("Send AccessDenied redirect URL " + redir); FileNode att = new FileNode(); att.setError(getMessageService().getMessage("err.access.denied")); files = Arrays.asList(att); } catch (Exception e) { // FileUploadException,RepositoryException log.error("File upload failed ", e); FileNode att = new FileNode(); att.setError(getMessageService().getMessage("err.upload")); files = Arrays.asList(att); } try { String json = FileNode.toAttachmentsJson(files, spaceUname, WikiUtil.getUser(), getMessageService(), getUserReadingService()); //TODO: does not compress request in Gzip, refer to //http://www.google.com/codesearch?hl=en&q=+RemoteServiceServlet+show:PAbNFg2Qpdo:akEoB_bGF1c:4aNSrXYgYQ4&sa=N&cd=1&ct=rc&cs_p=https://ssl.shinobun.org/svn/repos/trunk&cs_f=proprietary/gwt/gwt-user/src/main/java/com/google/gwt/user/server/rpc/RemoteServiceServlet.java#first byte[] reply = json.getBytes(Constants.UTF8); response.setContentLength(reply.length); response.setContentType("text/plain; charset=utf-8"); response.getOutputStream().write(reply); } catch (IOException e) { log.error(e.toString(), e); } }
From source file:com.example.web.Create_story.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); int count = 1; String storyid, storystep;//from w w w.ja v a 2 s.c om String fileName = ""; int f = 0; String action = ""; String first = request.getParameter("first"); String user = null; Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals("user")) user = cookie.getValue(); } } String title = request.getParameter("title"); String header = request.getParameter("header"); String text_field = request.getParameter("text_field"); String latitude = request.getParameter("lat"); String longitude = request.getParameter("lng"); storyid = (request.getParameter("storyid")); storystep = (request.getParameter("storystep")); String message = ""; int valid = 1; String query; ResultSet rs; Connection conn; String url = "jdbc:mysql://localhost:3306/"; String dbName = "tworld"; String driver = "com.mysql.jdbc.Driver"; isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. //factory.setRepository(new File("/var/lib/tomcat7/webapps/www_term_project/temp/")); factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); try { // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); fileName = fi.getName(); String contentType = fi.getContentType(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); String[] spliting = fileName.split("\\."); // Write the file System.out.println(sizeInBytes + " " + maxFileSize); System.out.println(spliting[spliting.length - 1]); if (!fileName.equals("")) { if ((sizeInBytes < maxFileSize) && (spliting[spliting.length - 1].equals("jpg") || spliting[spliting.length - 1].equals("png") || spliting[spliting.length - 1].equals("jpeg"))) { if (fileName.lastIndexOf("\\") >= 0) { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\"))); } else { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1)); } fi.write(file); System.out.println("Uploaded Filename: " + fileName + "<br>"); } else { valid = 0; message = "not a valid image"; } } } BufferedReader br = null; StringBuilder sb = new StringBuilder(); String line; try { br = new BufferedReader(new InputStreamReader(fi.getInputStream())); while ((line = br.readLine()) != null) { sb.append(line); } } catch (IOException e) { } finally { if (br != null) { try { br.close(); } catch (IOException e) { } } } if (f == 0) action = sb.toString(); else if (f == 1) storyid = sb.toString(); else if (f == 2) storystep = sb.toString(); else if (f == 3) title = sb.toString(); else if (f == 4) header = sb.toString(); else if (f == 5) text_field = sb.toString(); else if (f == 6) latitude = sb.toString(); else if (f == 7) longitude = sb.toString(); else if (f == 8) first = sb.toString(); f++; } } catch (Exception ex) { System.out.println("hi"); System.out.println(ex); } } if (latitude == null) latitude = ""; if (latitude.equals("") && first == null) { request.setAttribute("message", "please enter a marker"); request.setAttribute("storyid", storyid); request.setAttribute("s_page", "3"); request.setAttribute("storystep", storystep); request.getRequestDispatcher("/index.jsp").forward(request, response); } else if (valid == 1) { try { Class.forName(driver).newInstance(); conn = DriverManager.getConnection(url + dbName, "admin", "admin"); if (first != null) { if (first.equals("first_step")) { do { query = "select * from story_database where story_id='" + count + "' "; Statement st = conn.createStatement(); rs = st.executeQuery(query); count++; } while (rs.next()); int a = count - 1; request.setAttribute("storyid", a); storyid = Integer.toString(a); request.setAttribute("storystep", 2); } } query = "select * from story_database where `story_id`='" + storyid + "' && `step_num`='" + storystep + "' "; Statement st = conn.createStatement(); rs = st.executeQuery(query); if (!rs.next()) { PreparedStatement pst = (PreparedStatement) conn.prepareStatement( "insert into `tworld`.`story_database`(`story_id`, `step_num`, `content`, `latitude`, `longitude`, `title`, `header`, `max_steps`, `username`,`image_name`) values(?,?,?,?,?,?,?,?,?,?)"); pst.setInt(1, Integer.parseInt(storyid)); pst.setInt(2, Integer.parseInt(storystep)); pst.setString(3, text_field); pst.setString(4, latitude); pst.setString(5, longitude); pst.setString(6, title); pst.setString(7, header); pst.setInt(8, Integer.parseInt(storystep)); pst.setString(9, user); if (fileName.equals("")) pst.setString(10, ""); else pst.setString(10, fileName); pst.executeUpdate(); pst.close(); pst = (PreparedStatement) conn.prepareStatement( "UPDATE `tworld`.`story_database` SET `max_steps` = ? WHERE `story_id` = ?"); pst.setInt(1, Integer.parseInt(storystep)); pst.setInt(2, Integer.parseInt(storyid)); pst.executeUpdate(); pst.close(); } else { PreparedStatement pst = (PreparedStatement) conn.prepareStatement( "UPDATE `tworld`.`story_database` SET `content`=?, `latitude`=?, `longitude`=?, `title`=?, `header`=?, `max_steps`=?, `username`=? WHERE `story_id` = ? && `step_num`=?"); pst.setString(1, text_field); pst.setString(2, latitude); pst.setString(3, longitude); pst.setString(4, title); pst.setString(5, header); pst.setInt(6, Integer.parseInt(storystep)); pst.setString(7, user); pst.setInt(8, Integer.parseInt(storyid)); pst.setInt(9, Integer.parseInt(storystep)); pst.executeUpdate(); pst.close(); pst = (PreparedStatement) conn.prepareStatement( "UPDATE `tworld`.`story_database` SET `max_steps` = ? WHERE `story_id` = ?"); pst.setInt(1, Integer.parseInt(storystep)); pst.setInt(2, Integer.parseInt(storyid)); pst.executeUpdate(); pst.close(); } request.setAttribute("storyid", storyid); storystep = Integer.toString(Integer.parseInt(storystep) + 1); request.setAttribute("storystep", storystep); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException ex) { // Logger.getLogger(MySignInServlet.class.getName()).log(Level.SEVERE, null, ex); } request.setAttribute("s_page", "3"); request.getRequestDispatcher("/index.jsp").forward(request, response); } else { request.setAttribute("storyid", storyid); request.setAttribute("message", message); request.setAttribute("storystep", storystep); request.setAttribute("s_page", "3"); request.getRequestDispatcher("/index.jsp").forward(request, response); } }
From source file:com.blog.fckeditor.ConnectorServlet.java
/** * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br /> * /*ww w . j a v a2 s . com*/ * The servlet accepts commands sent in the following format:<br /> * <code>connector?Command=<FileUpload>&Type=<ResourceType>&CurrentFolder=<FolderPath></code> * with the file in the <code>POST</code> body.<br /> * <br> * It stores an uploaded file (renames a file if another exists with the * same name) and then returns the JavaScript callback. */ @SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.debug("Entering Connector#doPost"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); String commandStr = request.getParameter("Command"); String typeStr = request.getParameter("Type"); String currentFolderStr = request.getParameter("CurrentFolder"); logger.debug("Parameter Command: {}", commandStr); logger.debug("Parameter Type: {}", typeStr); logger.debug("Parameter CurrentFolder: {}", currentFolderStr); UploadResponse ur; // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr' // are empty if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) { commandStr = "QuickUpload"; currentFolderStr = "/"; } if (!RequestCycleHandler.isEnabledForFileUpload(request)) ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null, Messages.NOT_AUTHORIZED_FOR_UPLOAD); else if (!CommandHandler.isValidForPost(commandStr)) ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND); else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr)) ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE); else if (!UtilsFile.isValidPath(currentFolderStr)) ur = UploadResponse.UR_INVALID_CURRENT_FOLDER; else { ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr); String typePath = UtilsFile.constructServerSidePath(request, resourceType); String typeDirPath = getServletContext().getRealPath(typePath); File typeDir = new File(typeDirPath); UtilsFile.checkDirAndCreate(typeDir); File currentDir = new File(typeDir, currentFolderStr); if (!currentDir.exists()) ur = UploadResponse.UR_INVALID_CURRENT_FOLDER; else { String newFilename = null; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); // upload.setHeaderEncoding("UTF-8"); try { List<FileItem> items = upload.parseRequest(request); // We upload only one file at the same time FileItem uplFile = items.get(0); String rawName = UtilsFile.sanitizeFileName(uplFile.getName()); String filename = FilenameUtils.getName(rawName); String baseName = FilenameUtils.removeExtension(filename); String extension = FilenameUtils.getExtension(filename); // filename = UUID.randomUUID().toString() + "." + extension; if (!ExtensionsHandler.isAllowed(resourceType, extension)) ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); else { // construct an unique file name File pathToSave = new File(currentDir, filename); int counter = 1; while (pathToSave.exists()) { newFilename = baseName.concat("(").concat(String.valueOf(counter)).concat(")") .concat(".").concat(extension); pathToSave = new File(currentDir, newFilename); counter++; } if (Utils.isEmpty(newFilename)) ur = new UploadResponse(UploadResponse.SC_OK, UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr, true, ConnectorHandler.isFullUrl()).concat(filename)); else ur = new UploadResponse(UploadResponse.SC_RENAMED, UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr, true, ConnectorHandler.isFullUrl()).concat(newFilename), newFilename); // secure image check if (resourceType.equals(ResourceTypeHandler.IMAGE) && ConnectorHandler.isSecureImageUploads()) { if (UtilsFile.isImage(uplFile.getInputStream())) uplFile.write(pathToSave); else { uplFile.delete(); ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); } } else uplFile.write(pathToSave); } } catch (Exception e) { ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR); } } } out.print(ur); out.flush(); out.close(); logger.debug("Exiting Connector#doPost"); }
From source file:com.zjl.oa.fckeditor.ConnectorServlet.java
/** * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br /> * // w w w .j a va2 s . co m * The servlet accepts commands sent in the following format:<br /> * <code>connector?Command=<FileUpload>&Type=<ResourceType>&CurrentFolder=<FolderPath></code> * with the file in the <code>POST</code> body.<br /> * <br> * It stores an uploaded file (renames a file if another exists with the * same name) and then returns the JavaScript callback. */ @SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.debug("Entering Connector#doPost"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); String commandStr = request.getParameter("Command"); String typeStr = request.getParameter("Type"); String currentFolderStr = request.getParameter("CurrentFolder"); logger.debug("Parameter Command: {}", commandStr); logger.debug("Parameter Type: {}", typeStr); logger.debug("Parameter CurrentFolder: {}", currentFolderStr); UploadResponse ur; // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr' // are empty if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) { commandStr = "QuickUpload"; currentFolderStr = "/"; } if (!RequestCycleHandler.isEnabledForFileUpload(request)) ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null, Messages.NOT_AUTHORIZED_FOR_UPLOAD); else if (!CommandHandler.isValidForPost(commandStr)) ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND); else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr)) ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE); else if (!UtilsFile.isValidPath(currentFolderStr)) ur = UploadResponse.UR_INVALID_CURRENT_FOLDER; else { ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr); String typePath = UtilsFile.constructServerSidePath(request, resourceType); String typeDirPath = getServletContext().getRealPath(typePath); File typeDir = new File(typeDirPath); UtilsFile.checkDirAndCreate(typeDir); File currentDir = new File(typeDir, currentFolderStr); if (!currentDir.exists()) ur = UploadResponse.UR_INVALID_CURRENT_FOLDER; else { String newFilename = null; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); //?? upload.setHeaderEncoding("UTF-8"); try { List<FileItem> items = upload.parseRequest(request); // We upload only one file at the same time FileItem uplFile = items.get(0); String rawName = UtilsFile.sanitizeFileName(uplFile.getName()); String filename = FilenameUtils.getName(rawName); String baseName = FilenameUtils.removeExtension(filename); String extension = FilenameUtils.getExtension(filename); //??? filename = UUID.randomUUID().toString() + "." + extension; if (!ExtensionsHandler.isAllowed(resourceType, extension)) ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); else { // construct an unique file name File pathToSave = new File(currentDir, filename); int counter = 1; while (pathToSave.exists()) { newFilename = baseName.concat("(").concat(String.valueOf(counter)).concat(")") .concat(".").concat(extension); pathToSave = new File(currentDir, newFilename); counter++; } if (Utils.isEmpty(newFilename)) ur = new UploadResponse(UploadResponse.SC_OK, UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr, true, ConnectorHandler.isFullUrl()).concat(filename)); else ur = new UploadResponse(UploadResponse.SC_RENAMED, UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr, true, ConnectorHandler.isFullUrl()).concat(newFilename), newFilename); // secure image check if (resourceType.equals(ResourceTypeHandler.IMAGE) && ConnectorHandler.isSecureImageUploads()) { if (UtilsFile.isImage(uplFile.getInputStream())) uplFile.write(pathToSave); else { uplFile.delete(); ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); } } else uplFile.write(pathToSave); } } catch (Exception e) { ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR); } } } out.print(ur); out.flush(); out.close(); logger.debug("Exiting Connector#doPost"); }
From source file:com.laijie.fckeditor.ConnectorServlet.java
/** * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br /> * /*from ww w .j a v a2 s . co m*/ * The servlet accepts commands sent in the following format:<br /> * <code>connector?Command=<FileUpload>&Type=<ResourceType>&CurrentFolder=<FolderPath></code> * with the file in the <code>POST</code> body.<br /> * <br> * It stores an uploaded file (renames a file if another exists with the * same name) and then returns the JavaScript callback. */ @SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.debug("Entering Connector#doPost"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); String commandStr = request.getParameter("Command"); String typeStr = request.getParameter("Type"); String currentFolderStr = request.getParameter("CurrentFolder"); logger.debug("Parameter Command: {}", commandStr); logger.debug("Parameter Type: {}", typeStr); logger.debug("Parameter CurrentFolder: {}", currentFolderStr); UploadResponse ur; // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr' // are empty if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) { commandStr = "QuickUpload"; currentFolderStr = "/"; } if (!RequestCycleHandler.isEnabledForFileUpload(request)) ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null, Messages.NOT_AUTHORIZED_FOR_UPLOAD); else if (!CommandHandler.isValidForPost(commandStr)) ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND); else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr)) ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE); else if (!UtilsFile.isValidPath(currentFolderStr)) ur = UploadResponse.UR_INVALID_CURRENT_FOLDER; else { ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr); String typePath = UtilsFile.constructServerSidePath(request, resourceType); String typeDirPath = getServletContext().getRealPath(typePath); File typeDir = new File(typeDirPath); UtilsFile.checkDirAndCreate(typeDir); File currentDir = new File(typeDir, currentFolderStr); if (!currentDir.exists()) ur = UploadResponse.UR_INVALID_CURRENT_FOLDER; else { String newFilename = null; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); // upload.setHeaderEncoding("UTF-8"); try { List<FileItem> items = upload.parseRequest(request); // We upload only one file at the same time FileItem uplFile = items.get(0); String rawName = UtilsFile.sanitizeFileName(uplFile.getName()); String filename = FilenameUtils.getName(rawName); String baseName = FilenameUtils.removeExtension(filename); String extension = FilenameUtils.getExtension(filename); // filename = UUID.randomUUID().toString() + "." + extension; if (!ExtensionsHandler.isAllowed(resourceType, extension)) ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); else { // construct an unique file name File pathToSave = new File(currentDir, filename); int counter = 1; while (pathToSave.exists()) { newFilename = baseName.concat("(").concat(String.valueOf(counter)).concat(")") .concat(".").concat(extension); pathToSave = new File(currentDir, newFilename); counter++; } if (Utils.isEmpty(newFilename)) ur = new UploadResponse(UploadResponse.SC_OK, UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr, true, ConnectorHandler.isFullUrl()).concat(filename)); else ur = new UploadResponse(UploadResponse.SC_RENAMED, UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr, true, ConnectorHandler.isFullUrl()).concat(newFilename), newFilename); // secure image check if (resourceType.equals(ResourceTypeHandler.IMAGE) && ConnectorHandler.isSecureImageUploads()) { if (UtilsFile.isImage(uplFile.getInputStream())) uplFile.write(pathToSave); else { uplFile.delete(); ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); } } else uplFile.write(pathToSave); } } catch (Exception e) { ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR); } } } out.print(ur); out.flush(); out.close(); logger.debug("Exiting Connector#doPost"); }
From source file:com.example.web.Update_profile.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ String fileName = ""; int f = 0; String user = null;/*from w w w. j a v a2 s.co m*/ Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals("user")) { user = cookie.getValue(); } } } String email = request.getParameter("email"); String First_name = request.getParameter("First_name"); String Last_name = request.getParameter("Last_name"); String Phone_number_1 = request.getParameter("Phone_number_1"); String Address = request.getParameter("Address"); String message = ""; int valid = 1; String query; ResultSet rs; Connection conn; String url = "jdbc:mysql://localhost:3306/"; String dbName = "tworld"; String driver = "com.mysql.jdbc.Driver"; isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. //factory.setRepository(new File("/var/lib/tomcat7/webapps/www_term_project/temp/")); factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); try { // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); fileName = fi.getName(); String contentType = fi.getContentType(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); String[] spliting = fileName.split("\\."); // Write the file System.out.println(sizeInBytes + " " + maxFileSize); System.out.println(spliting[spliting.length - 1]); if (!fileName.equals("")) { if ((sizeInBytes < maxFileSize) && (spliting[spliting.length - 1].equals("jpg") || spliting[spliting.length - 1].equals("png") || spliting[spliting.length - 1].equals("jpeg"))) { if (fileName.lastIndexOf("\\") >= 0) { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\"))); } else { file = new File( filePath + fileName.substring(fileName.lastIndexOf("\\") + 1)); } fi.write(file); System.out.println("Uploaded Filename: " + fileName + "<br>"); } else { valid = 0; message = "not a valid image"; } } } BufferedReader br = null; StringBuilder sb = new StringBuilder(); String line; try { br = new BufferedReader(new InputStreamReader(fi.getInputStream())); while ((line = br.readLine()) != null) { sb.append(line); } } catch (IOException e) { } finally { if (br != null) { try { br.close(); } catch (IOException e) { } } } if (f == 0) { email = sb.toString(); } else if (f == 1) { First_name = sb.toString(); } else if (f == 2) { Last_name = sb.toString(); } else if (f == 3) { Phone_number_1 = sb.toString(); } else if (f == 4) { Address = sb.toString(); } f++; } } catch (Exception ex) { System.out.println("hi"); System.out.println(ex); } } try { Class.forName(driver).newInstance(); conn = DriverManager.getConnection(url + dbName, "admin", "admin"); if (!email.equals("")) { PreparedStatement pst = (PreparedStatement) conn .prepareStatement("update `tworld`.`users` set `email`=? where `Username`=?"); pst.setString(1, email); pst.setString(2, user); pst.executeUpdate(); pst.close(); } if (!First_name.equals("")) { PreparedStatement pst = (PreparedStatement) conn .prepareStatement("update `tworld`.`users` set `First_name`=? where `Username`=?"); pst.setString(1, First_name); pst.setString(2, user); pst.executeUpdate(); pst.close(); } if (!Last_name.equals("")) { PreparedStatement pst = (PreparedStatement) conn .prepareStatement("update `tworld`.`users` set `Last_name`=? where `Username`=?"); pst.setString(1, Last_name); pst.setString(2, user); pst.executeUpdate(); pst.close(); } if (!Phone_number_1.equals("")) { PreparedStatement pst = (PreparedStatement) conn .prepareStatement("update `tworld`.`users` set `Phone_number_1`=? where `Username`=?"); pst.setString(1, Phone_number_1); pst.setString(2, user); pst.executeUpdate(); pst.close(); } if (!Address.equals("")) { PreparedStatement pst = (PreparedStatement) conn .prepareStatement("update `tworld`.`users` set `Address`=? where `Username`=?"); pst.setString(1, Address); pst.setString(2, user); pst.executeUpdate(); pst.close(); } if (!fileName.equals("")) { PreparedStatement pst = (PreparedStatement) conn .prepareStatement("update `tworld`.`users` set `Fototitle`=? where `Username`=?"); pst.setString(1, fileName); pst.setString(2, user); pst.executeUpdate(); pst.close(); } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException ex) { System.out.println("hi mom"); } request.setAttribute("s_page", "4"); request.getRequestDispatcher("/index.jsp").forward(request, response); } }
From source file:com.trsst.ui.AppServlet.java
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { // FLAG: limit access only to local clients if (restricted && !request.getRemoteAddr().equals(request.getLocalAddr())) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "Non-local clients are not allowed."); return;/*from w w w . ja v a2s . c om*/ } // in case of any posted files InputStream inStream = null; // determine if supported command: pull, push, post String path = request.getPathInfo(); System.err.println(new Date().toString() + " " + path); if (path != null) { // FLAG: limit only to pull and post if (path.startsWith("/pull/") || path.startsWith("/post")) { // FLAG: we're sending the user's keystore // password over the wire (over SSL) List<String> args = new LinkedList<String>(); if (path.startsWith("/pull/")) { path = path.substring("/pull/".length()); response.setContentType("application/atom+xml; type=feed; charset=utf-8"); // System.out.println("doPull: " + // request.getParameterMap()); args.add("pull"); if (request.getParameterMap().size() > 0) { boolean first = true; for (Object name : request.getParameterMap().keySet()) { // FLAG: don't allow "home" (server-abuse) // FLAG: don't allow "attach" (file-system access) if ("decrypt".equals(name) || "pass".equals(name)) { for (String value : request.getParameterValues(name.toString())) { args.add("--" + name.toString()); args.add(value); } } else { for (String value : request.getParameterValues(name.toString())) { if (first) { path = path + '?'; first = false; } else { path = path + '&'; } path = path + name + '=' + value; } } } } args.add(path); } else if (path.startsWith("/post")) { // System.out.println("doPost: " + // request.getParameterMap()); args.add("post"); try { // h/t http://stackoverflow.com/questions/2422468 List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()) .parseRequest(request); for (FileItem item : items) { if (item.isFormField()) { // process regular form field String name = item.getFieldName(); String value = item.getString("UTF-8").trim(); // System.out.println("AppServlet: " + name // + " : " + value); if (value.length() > 0) { // FLAG: don't allow "home" (server-abuse) // FLAG: don't allow "attach" (file-system // access) if ("id".equals(name)) { if (value.startsWith("urn:feed:")) { value = value.substring("urn:feed:".length()); } args.add(value); } else if (!"home".equals(name) && !"attach".equals(name)) { args.add("--" + name); args.add(value); } } else { log.debug("Empty form value for name: " + name); } } else if (item.getSize() > 0) { // process form file field (input type="file"). // String filename = FilenameUtils.getName(item // .getName()); if (item.getSize() > 1024 * 1024 * 10) { throw new FileUploadException("Current maximum upload size is 10MB"); } String name = item.getFieldName(); if ("icon".equals(name) || "logo".equals(name)) { args.add("--" + name); args.add("-"); } inStream = item.getInputStream(); // NOTE: only handles one file! } else { log.debug("Ignored form field: " + item.getFieldName()); } } } catch (FileUploadException e) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Could not parse multipart request: " + e); return; } } // send post data if any to command input stream if (inStream != null) { args.add("--attach"); } //System.out.println(args); // make sure we don't create another local server args.add("--host"); args.add(request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/feed"); PrintStream outStream = new PrintStream(response.getOutputStream(), false, "UTF-8"); int result = new Command().doBegin(args.toArray(new String[0]), outStream, inStream); if (result != 0) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal error code: " + result); } else { outStream.flush(); } return; } // otherwise: determine if static resource request if (path.startsWith("/")) { path = path.substring(1); } byte[] result = resources.get(path); String mimetype = null; if (result == null) { // if ("".equals(path) || path.endsWith(".html")) { // treat all html requests with index doc result = resources.get("index.html"); mimetype = "text/html"; // } } if (result != null) { if (mimetype == null) { if (path.endsWith(".html")) { mimetype = "text/html"; } else if (path.endsWith(".css")) { mimetype = "text/css"; } else if (path.endsWith(".js")) { mimetype = "application/javascript"; } else if (path.endsWith(".png")) { mimetype = "image/png"; } else if (path.endsWith(".jpg")) { mimetype = "image/jpeg"; } else if (path.endsWith(".jpeg")) { mimetype = "image/jpeg"; } else if (path.endsWith(".gif")) { mimetype = "image/gif"; } else { mimetype = new Tika().detect(result); } } if (request.getHeader("If-None-Match:") != null) { // client should always use cached version log.info("sending 304"); response.setStatus(304); // Not Modified return; } // otherwise allow ETag/If-None-Match response.setHeader("ETag", Long.toHexString(path.hashCode())); if (mimetype != null) { response.setContentType(mimetype); } response.setContentLength(result.length); response.getOutputStream().write(result); return; } } // // otherwise: 404 Not Found // response.sendError(HttpServletResponse.SC_NOT_FOUND); }
From source file:com.silverpeas.jobDomainPeas.control.JobDomainPeasSessionController.java
/** * Parse the CSV file.// ww w.ja v a 2 s . c o m * * @param filePart * @param req the current HttpServletRequest * @throws UtilTrappedException * @throws JobDomainPeasTrappedException * @throws JobDomainPeasException */ public void importCsvUsers(FileItem filePart, boolean sendEmail, HttpServletRequest req) throws UtilTrappedException, JobDomainPeasTrappedException, JobDomainPeasException { InputStream is; try { is = filePart.getInputStream(); } catch (IOException e) { JobDomainPeasTrappedException jdpe = new JobDomainPeasTrappedException( "JobDomainPeasSessionController.importCsvUsers", SilverpeasException.ERROR, "jobDomainPeas.EX_CSV_FILE", e); jdpe.setGoBackPage("displayUsersCsvImport"); throw jdpe; } CSVReader csvReader = new CSVReader(getLanguage()); csvReader.initCSVFormat("com.silverpeas.jobDomainPeas.settings.usersCSVFormat", "User", ";", getTargetDomain().getPropFileName(), "property_"); // spcifique domaine Silverpeas (2 colonnes en moins (password et // passwordValid) if ("-1".equals(getTargetDomain().getId()) || "0".equals(getTargetDomain().getId())) {// domaine Silverpeas csvReader.setM_specificNbCols(csvReader.getM_specificNbCols() - 2); } Variant[][] csvValues; try { csvValues = csvReader.parseStream(is); } catch (UtilTrappedException ute) { ute.setGoBackPage("displayUsersCsvImport"); throw ute; } StringBuilder listErrors = new StringBuilder(""); String nom; String prenom; String login; String existingLogin; String email; String droits; UserAccessLevel userAccessLevel; String motDePasse; String title; String company; String position; String boss; String phone; String homePhone; String fax; String cellularPhone; String address; String informationSpecifiqueString; boolean informationSpecifiqueBoolean; for (int i = 0; i < csvValues.length; i++) { // Nom nom = csvValues[i][0].getValueString(); if (nom.length() == 0) {// champ obligatoire listErrors.append(getErrorMessage(i + 1, 1, nom)); listErrors.append(getString("JDP.obligatoire")).append("<br/>"); } else if (nom.length() > 100) {// verifier 100 char max listErrors.append(getErrorMessage(i + 1, 1, nom)); listErrors.append(getString("JDP.nbCarMax")).append(" 100 ").append(getString("JDP.caracteres")) .append("<br/>"); } // Prenom prenom = csvValues[i][1].getValueString(); // verifier 100 char max if (prenom.length() > 100) { listErrors.append(getErrorMessage(i + 1, 2, prenom)); listErrors.append(getString("JDP.nbCarMax")).append(" 100 ").append(getString("JDP.caracteres")) .append("<br/>"); } // Login login = csvValues[i][2].getValueString(); if (login.length() == 0) {// champ obligatoire listErrors.append(getErrorMessage(i + 1, 3, login)); listErrors.append(getString("JDP.obligatoire")).append("<br/>"); } else if (login.length() < JobDomainSettings.m_MinLengthLogin) {// verifier listErrors.append(getErrorMessage(i + 1, 3, login)); listErrors.append(getString("JDP.nbCarMin")).append(" ").append(JobDomainSettings.m_MinLengthLogin) .append(" ").append(getString("JDP.caracteres")).append("<br/>"); } else if (login.length() > 50) {// verifier 50 char max listErrors.append(getErrorMessage(i + 1, 3, login)); listErrors.append(getString("JDP.nbCarMax")).append(" 50 ").append(getString("JDP.caracteres")) .append("<br/>"); } else {// verif login unique existingLogin = m_AdminCtrl.getUserIdByLoginAndDomain(login, targetDomainId); if (existingLogin != null) { listErrors.append(getErrorMessage(i + 1, 3, login)); listErrors.append(getString("JDP.existingLogin")).append("<br/>"); } } // Email email = csvValues[i][3].getValueString(); // verifier 100 char max if (email.length() > 100) { listErrors.append(getErrorMessage(i + 1, 4, email)); listErrors.append(getString("JDP.nbCarMax")).append(" 100 ").append(getString("JDP.caracteres")) .append("<br/>"); } // Droits droits = csvValues[i][4].getValueString(); if (!"".equals(droits) && !"Admin".equals(droits) && !"AdminPdc".equals(droits) && !"AdminDomain".equals(droits) && !"User".equals(droits) && !"Guest".equals(droits)) { listErrors.append(getErrorMessage(i + 1, 5, droits)); listErrors.append(getString("JDP.valeursPossibles")).append("<br/>"); } // MotDePasse motDePasse = csvValues[i][5].getValueString(); // password is not mandatory if (StringUtil.isDefined(motDePasse)) { // Cheking password PasswordCheck passwordCheck = PasswordServiceFactory.getPasswordService().check(motDePasse); if (!passwordCheck.isCorrect()) { listErrors.append(getErrorMessage(i + 1, 6, motDePasse)) .append(passwordCheck.getFormattedErrorMessage(getLanguage())); listErrors.append("<br/>"); } else if (motDePasse.length() > 32) {// verifier 32 char max listErrors.append(getErrorMessage(i + 1, 6, motDePasse)); listErrors.append(getString("JDP.nbCarMax")).append(" 32 ").append(getString("JDP.caracteres")) .append("<br/>"); } } if (csvReader.getM_specificNbCols() > 0) { if ("-1".equals(getTargetDomain().getId()) || "0".equals(getTargetDomain().getId())) {// domaine Silverpeas // title title = csvValues[i][6].getValueString(); // verifier 100 char max if (title.length() > 100) { listErrors.append(getErrorMessage(i + 1, 7, title)); listErrors.append(getString("JDP.nbCarMax")).append(" 100 ") .append(getString("JDP.caracteres")).append("<br/>"); } // company company = csvValues[i][7].getValueString(); // verifier 100 char max if (company.length() > 100) { listErrors.append(getErrorMessage(i + 1, 8, company)); listErrors.append(getString("JDP.nbCarMax")).append(" 100 ") .append(getString("JDP.caracteres")).append("<br/>"); } // position position = csvValues[i][8].getValueString(); // verifier 100 char max if (position.length() > 100) { listErrors.append(getErrorMessage(i + 1, 9, position)); listErrors.append(getString("JDP.nbCarMax")).append(" 100 ") .append(getString("JDP.caracteres")).append("<br/>"); } // boss boss = csvValues[i][9].getValueString(); // verifier 100 char max if (boss.length() > 100) { listErrors.append(getErrorMessage(i + 1, 10, boss)); listErrors.append(getString("JDP.nbCarMax")).append(" 100 ") .append(getString("JDP.caracteres")).append("<br/>"); } // phone phone = csvValues[i][10].getValueString(); // verifier 20 char max if (phone.length() > 20) { listErrors.append(getErrorMessage(i + 1, 11, phone)); listErrors.append(getString("JDP.nbCarMax")).append(" 20 ") .append(getString("JDP.caracteres")).append("<br/>"); } // homePhone homePhone = csvValues[i][11].getValueString(); // verifier 20 char max if (homePhone.length() > 20) { listErrors.append(getErrorMessage(i + 1, 12, homePhone)); listErrors.append(getString("JDP.nbCarMax")).append(" 20 ") .append(getString("JDP.caracteres")).append("<br/>"); } // fax fax = csvValues[i][12].getValueString(); // verifier 20 char max if (fax.length() > 20) { listErrors.append(getErrorMessage(i + 1, 13, fax)); listErrors.append(getString("JDP.nbCarMax")).append(" 20 ") .append(getString("JDP.caracteres")).append("<br/>"); } // cellularPhone cellularPhone = csvValues[i][13].getValueString(); // verifier 20 char // max if (cellularPhone.length() > 20) { listErrors.append(getErrorMessage(i + 1, 14, cellularPhone)); listErrors.append(getString("JDP.nbCarMax")).append(" 20 ") .append(getString("JDP.caracteres")).append("<br/>"); } // address address = csvValues[i][14].getValueString(); // verifier 500 char max if (address.length() > 500) { listErrors.append(getErrorMessage(i + 1, 15, address)); listErrors.append(getString("JDP.nbCarMax")).append(" 500 ") .append(getString("JDP.caracteres")).append("<br/>"); } } else {// domaine SQL for (int j = 0; j < csvReader.getM_specificNbCols(); j++) { if (Variant.TYPE_STRING.equals(csvReader.getM_specificColType(j))) { informationSpecifiqueString = csvValues[i][j + 6].getValueString(); // verify the length if (informationSpecifiqueString.length() > csvReader.getM_specificColMaxLength(j)) { listErrors.append(getErrorMessage(i + 1, j + 6, informationSpecifiqueString)); listErrors.append(getString("JDP.nbCarMax")).append(" ") .append(csvReader.getM_specificColMaxLength(j)).append(" ") .append(getString("JDP.caracteres")).append("<br/>"); } } } } } } if (listErrors.length() > 0) { JobDomainPeasTrappedException jdpe = new JobDomainPeasTrappedException( "JobDomainPeasSessionController.importCsvUsers", SilverpeasException.ERROR, "jobDomainPeas.EX_CSV_FILE", listErrors.toString()); jdpe.setGoBackPage("displayUsersCsvImport"); throw jdpe; } // pas d'erreur, on importe les utilisateurs HashMap<String, String> properties; for (Variant[] csvValue : csvValues) { // Nom nom = csvValue[0].getValueString(); // Prenom prenom = csvValue[1].getValueString(); // Login login = csvValue[2].getValueString(); // Email email = csvValue[3].getValueString(); // Droits droits = csvValue[4].getValueString(); if ("Admin".equals(droits)) { userAccessLevel = UserAccessLevel.ADMINISTRATOR; } else if ("AdminPdc".equals(droits)) { userAccessLevel = UserAccessLevel.PDC_MANAGER; } else if ("AdminDomain".equals(droits)) { userAccessLevel = UserAccessLevel.DOMAIN_ADMINISTRATOR; } else if ("User".equals(droits)) { userAccessLevel = UserAccessLevel.USER; } else if ("Guest".equals(droits)) { userAccessLevel = UserAccessLevel.GUEST; } else { userAccessLevel = UserAccessLevel.USER; } // MotDePasse motDePasse = csvValue[5].getValueString(); // donnes spcifiques properties = new HashMap<String, String>(); if (csvReader.getM_specificNbCols() > 0) { if ("-1".equals(getTargetDomain().getId()) || "0".equals(getTargetDomain().getId())) {// domaine Silverpeas // title title = csvValue[6].getValueString(); properties.put(csvReader.getM_specificParameterName(0), title); // company company = csvValue[7].getValueString(); properties.put(csvReader.getM_specificParameterName(1), company); // position position = csvValue[8].getValueString(); properties.put(csvReader.getM_specificParameterName(2), position); // boss boss = csvValue[9].getValueString(); properties.put(csvReader.getM_specificParameterName(3), boss); // phone phone = csvValue[10].getValueString(); properties.put(csvReader.getM_specificParameterName(4), phone); // homePhone homePhone = csvValue[11].getValueString(); properties.put(csvReader.getM_specificParameterName(5), homePhone); // fax fax = csvValue[12].getValueString(); properties.put(csvReader.getM_specificParameterName(6), fax); // cellularPhone cellularPhone = csvValue[13].getValueString(); properties.put(csvReader.getM_specificParameterName(7), cellularPhone); // address address = csvValue[14].getValueString(); properties.put(csvReader.getM_specificParameterName(8), address); } else {// domaine SQL // informations spcifiques for (int j = 0; j < csvReader.getM_specificNbCols(); j++) { if (Variant.TYPE_STRING.equals(csvReader.getM_specificColType(j))) { informationSpecifiqueString = csvValue[j + 6].getValueString(); properties.put(csvReader.getM_specificParameterName(j), informationSpecifiqueString); } else if (Variant.TYPE_BOOLEAN.equals(csvReader.getM_specificColType(j))) { informationSpecifiqueBoolean = csvValue[j + 6].getValueBoolean(); if (informationSpecifiqueBoolean) { properties.put(csvReader.getM_specificParameterName(j), "1"); } else { properties.put(csvReader.getM_specificParameterName(j), "0"); } } } } } boolean passwordValid = StringUtil.isDefined(motDePasse); // password is not mandatory createUser(login, nom, prenom, email, userAccessLevel, passwordValid, motDePasse, properties, null, req, sendEmail); // l'id User cr est dans m_TargetUserId } }
From source file:com.ecyrd.jspwiki.attachment.SilverpeasAttachmentServlet.java
/** * Uploads a specific mime multipart input set, intercepts exceptions. * @param req The servlet request/*from ww w . j a v a2 s . c o m*/ * @return The page to which we should go next. * @throws RedirectException If there's an error and a redirection is needed * @throws IOException If upload fails * @throws FileUploadException */ @SuppressWarnings("unchecked") protected String upload(HttpServletRequest req) throws RedirectException, IOException { String msg = ""; String attName = "(unknown)"; String errorPage = m_engine.getURL(WikiContext.ERROR, "", null, false); // If something bad // happened, Upload // should be able to // take care of most // stuff String nextPage = errorPage; String progressId = req.getParameter("progressid"); // Check that we have a file upload request if (!ServletFileUpload.isMultipartContent(req)) { throw new RedirectException("Not a file upload", errorPage); } try { FileItemFactory factory = new DiskFileItemFactory(); // Create the context _before_ Multipart operations, otherwise // strict servlet containers may fail when setting encoding. WikiContext context = m_engine.createContext(req, WikiContext.ATTACH); UploadListener pl = new UploadListener(); m_engine.getProgressManager().startProgress(pl, progressId); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); upload.setFileSizeMax(m_maxSize); upload.setProgressListener(pl); List<FileItem> items = upload.parseRequest(req); String wikipage = null; String changeNote = null; FileItem actualFile = null; for (FileItem item : items) { if (item.isFormField()) { if (item.getFieldName().equals("page")) { // // FIXME: Kludge alert. We must end up with the parent page name, // if this is an upload of a new revision // wikipage = item.getString("UTF-8"); int x = wikipage.indexOf("/"); if (x != -1) { wikipage = wikipage.substring(0, x); } } else if (item.getFieldName().equals("changenote")) { changeNote = item.getString("UTF-8"); } else if (item.getFieldName().equals("nextpage")) { nextPage = validateNextPage(item.getString("UTF-8"), errorPage); } } else { actualFile = item; } } if (actualFile == null) { throw new RedirectException("Broken file upload", errorPage); } // // FIXME: Unfortunately, with Apache fileupload we will get the form fields in // order. This means that we have to gather all the metadata from the // request prior to actually touching the uploaded file itself. This // is because the changenote appears after the file upload box, and we // would not have this information when uploading. This also means // that with current structure we can only support a single file upload // at a time. // String filename = actualFile.getName(); long fileSize = actualFile.getSize(); InputStream in = actualFile.getInputStream(); try { executeUpload(context, in, filename, nextPage, wikipage, changeNote, fileSize); } finally { in.close(); } } catch (ProviderException e) { msg = "Upload failed because the provider failed: " + e.getMessage(); log.warn(msg + " (attachment: " + attName + ")", e); throw new IOException(msg); } catch (IOException e) { // Show the submit page again, but with a bit more // intimidating output. msg = "Upload failure: " + e.getMessage(); log.warn(msg + " (attachment: " + attName + ")", e); throw e; } catch (FileUploadException e) { // Show the submit page again, but with a bit more // intimidating output. msg = "Upload failure: " + e.getMessage(); log.warn(msg + " (attachment: " + attName + ")", e); throw new IOException(msg); } finally { m_engine.getProgressManager().stopProgress(progressId); // FIXME: In case of exceptions should absolutely // remove the uploaded file. } return nextPage; }