List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload ServletFileUpload
public ServletFileUpload(FileItemFactory fileItemFactory)
FileItem
instances. From source file:com.martin.zkedit.controller.Import.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.debug("Importing Action!"); try {/*from w w w . j a v a 2 s. co m*/ Properties globalProps = (Properties) this.getServletContext().getAttribute("globalProps"); Dao dao = new Dao(globalProps); String zkServer = globalProps.getProperty("zkServer"); String[] zkServerLst = zkServer.split(","); StringBuilder sbFile = new StringBuilder(); String scmOverwrite = "false"; String scmServer = ""; String scmFilePath = ""; String scmFileRevision = ""; String uploadFileName = ""; DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1034); ServletFileUpload upload = new ServletFileUpload(factory); List items = upload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { if (item.getFieldName().equals("scmOverwrite")) { scmOverwrite = item.getString(); } if (item.getFieldName().equals("scmServer")) { scmServer = item.getString(); } if (item.getFieldName().equals("scmFilePath")) { scmFilePath = item.getString(); } if (item.getFieldName().equals("scmFileRevision")) { scmFileRevision = item.getString(); } } else { uploadFileName = item.getName(); sbFile.append(item.getString()); } } InputStream inpStream; if (sbFile.toString().length() == 0) { uploadFileName = scmServer + scmFileRevision + "@" + scmFilePath; logger.debug("P4 file Processing " + uploadFileName); dao.insertHistory((String) request.getSession().getAttribute("authName"), request.getRemoteAddr(), "Importing P4 File: " + uploadFileName + "<br/>" + "Overwrite: " + scmOverwrite); URL url = new URL(uploadFileName); URLConnection conn = url.openConnection(); inpStream = conn.getInputStream(); } else { logger.debug("Upload file Processing " + uploadFileName); dao.insertHistory((String) request.getSession().getAttribute("authName"), request.getRemoteAddr(), "Uploading File: " + uploadFileName + "<br/>" + "Overwrite: " + scmOverwrite); inpStream = new ByteArrayInputStream(sbFile.toString().getBytes()); } // open the stream and put it into BufferedReader BufferedReader br = new BufferedReader(new InputStreamReader(inpStream)); String inputLine; List<String> importFile = new ArrayList<>(); Integer lineCnt = 0; while ((inputLine = br.readLine()) != null) { lineCnt++; // Empty or comment? if (inputLine.trim().equals("") || inputLine.trim().startsWith("#")) { continue; } if (inputLine.startsWith("-")) { //DO nothing. } else if (!inputLine.matches("/.+=.+=.*")) { throw new IOException("Invalid format at line " + lineCnt + ": " + inputLine); } importFile.add(inputLine); } br.close(); ZooKeeperUtil.INSTANCE.importData(importFile, Boolean.valueOf(scmOverwrite), ServletUtil.INSTANCE.getZookeeper(request, response, zkServerLst[0])); for (String line : importFile) { if (line.startsWith("-")) { dao.insertHistory((String) request.getSession().getAttribute("authName"), request.getRemoteAddr(), "File: " + uploadFileName + ", Deleting Entry: " + line); } else { dao.insertHistory((String) request.getSession().getAttribute("authName"), request.getRemoteAddr(), "File: " + uploadFileName + ", Adding Entry: " + line); } } request.getSession().setAttribute("flashMsg", "Import Completed!"); response.sendRedirect("/home"); } catch (FileUploadException | IOException | InterruptedException | KeeperException ex) { ServletUtil.INSTANCE.renderError(request, response, ex.getMessage()); } }
From source file:fr.paris.lutece.util.http.MultipartUtil.java
/** * Convert a HTTP request to a {@link MultipartHttpServletRequest} * @param nSizeThreshold the size threshold * @param nRequestSizeMax the request size max * @param bActivateNormalizeFileName true if the file name must be normalized, false otherwise * @param request the HTTP request/*from ww w.ja v a2 s. c om*/ * @return a {@link MultipartHttpServletRequest}, null if the request does not have a multipart content * @throws SizeLimitExceededException exception if the file size is too big * @throws FileUploadException exception if an unknown error has occurred */ public static MultipartHttpServletRequest convert(int nSizeThreshold, long nRequestSizeMax, boolean bActivateNormalizeFileName, HttpServletRequest request) throws SizeLimitExceededException, FileUploadException { if (isMultipart(request)) { // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Set factory constraints factory.setSizeThreshold(nSizeThreshold); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(nRequestSizeMax); // get encoding to be used String strEncoding = request.getCharacterEncoding(); if (strEncoding == null) { strEncoding = EncodingService.getEncoding(); } Map<String, FileItem> mapFiles = new HashMap<String, FileItem>(); Map<String, String[]> mapParameters = new HashMap<String, String[]>(); List<FileItem> listItems = upload.parseRequest(request); // Process the uploaded items for (FileItem item : listItems) { if (item.isFormField()) { String strValue = StringUtils.EMPTY; try { if (item.getSize() > 0) { strValue = item.getString(strEncoding); } } catch (UnsupportedEncodingException ex) { if (item.getSize() > 0) { // if encoding problem, try with system encoding strValue = item.getString(); } } // check if item of same name already in map String[] curParam = mapParameters.get(item.getFieldName()); if (curParam == null) { // simple form field mapParameters.put(item.getFieldName(), new String[] { strValue }); } else { // array of simple form fields String[] newArray = new String[curParam.length + 1]; System.arraycopy(curParam, 0, newArray, 0, curParam.length); newArray[curParam.length] = strValue; mapParameters.put(item.getFieldName(), newArray); } } else { // multipart file field, if the parameter filter ActivateNormalizeFileName is set to true //all file name will be normalize mapFiles.put(item.getFieldName(), bActivateNormalizeFileName ? new NormalizeFileItem(item) : item); } } return new MultipartHttpServletRequest(request, mapFiles, mapParameters); } return null; }
From source file:com.intelligentz.appointmentz.controllers.addSession.java
@SuppressWarnings("Since15") @Override/*www. ja va 2 s. c o m*/ public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try { String room_id = null; String doctor_id = null; String start_time = null; String date_picked = null; ArrayList<SessonCustomer> sessonCustomers = new ArrayList<>(); 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(filePath + "temp")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); // Parse the request to get file items. List fileItems = upload.parseRequest(req); // 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(); String fileName = fi.getName(); String contentType = fi.getContentType(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); // Write the file if (fileName.lastIndexOf("\\") >= 0) { filePath = filePath + fileName.substring(fileName.lastIndexOf("\\")); file = new File(filePath); } else { filePath = filePath + fileName.substring(fileName.lastIndexOf("\\") + 1); file = new File(filePath); } fi.write(file); Files.lines(Paths.get(filePath)).forEach((line) -> { String[] cust = line.split(","); sessonCustomers.add(new SessonCustomer(cust[0].trim(), Integer.parseInt(cust[1].trim()))); }); } else { if (fi.getFieldName().equals("room_id")) room_id = fi.getString(); else if (fi.getFieldName().equals("doctor_id")) doctor_id = fi.getString(); else if (fi.getFieldName().equals("start_time")) start_time = fi.getString(); else if (fi.getFieldName().equals("date_picked")) date_picked = fi.getString(); } } con = new connectToDB(); if (con.connect()) { Connection connection = con.getConnection(); Class.forName("com.mysql.jdbc.Driver"); Statement stmt = connection.createStatement(); String SQL, SQL1, SQL2; SQL1 = "insert into db_bro.session ( doctor_id, room_id, date, start_time) VALUES (?,?,?,?)"; PreparedStatement preparedStmt = connection.prepareStatement(SQL1); preparedStmt.setString(1, doctor_id); preparedStmt.setString(2, room_id); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH:mm"); try { java.util.Date d = formatter.parse(date_picked + "-" + start_time); Date d_sql = new Date(d.getTime()); java.util.Date N = new java.util.Date(); if (N.compareTo(d) > 0) { res.sendRedirect("./error.jsp?error=Invalid Date!"); } //String [] T = start_time.split(":"); //Time t = Time.valueOf(start_time); //Time t = new Time(Integer.parseInt(T[0]),Integer.parseInt(T[1]),0); //java.sql.Time t_sql = new java.sql.Date(d.getTime()); preparedStmt.setString(4, start_time + ":00"); preparedStmt.setDate(3, d_sql); } catch (ParseException e) { displayMessage(res, "Invalid Date!" + e.getLocalizedMessage()); } // execute the preparedstatement preparedStmt.execute(); SQL = "select * from db_bro.session ORDER BY session_id DESC limit 1"; ResultSet rs = stmt.executeQuery(SQL); boolean check = false; while (rs.next()) { String db_doctor_id = rs.getString("doctor_id"); String db_date_picked = rs.getString("date"); String db_start_time = rs.getString("start_time"); String db_room_id = rs.getString("room_id"); if ((doctor_id == null ? db_doctor_id == null : doctor_id.equals(db_doctor_id)) && (start_time == null ? db_start_time == null : (start_time + ":00").equals(db_start_time)) && (room_id == null ? db_room_id == null : room_id.equals(db_room_id)) && (date_picked == null ? db_date_picked == null : date_picked.equals(db_date_picked))) { check = true; //displayMessage(res,"Authentication Success!"); SQL2 = "insert into db_bro.session_customers ( session_id, mobile, appointment_num) VALUES (?,?,?)"; for (SessonCustomer sessonCustomer : sessonCustomers) { preparedStmt = connection.prepareStatement(SQL2); preparedStmt.setString(1, rs.getString("session_id")); preparedStmt.setString(2, sessonCustomer.getMobile()); preparedStmt.setInt(3, sessonCustomer.getAppointment_num()); preparedStmt.execute(); } try { connection.close(); } catch (SQLException e) { displayMessage(res, "SQLException"); } res.sendRedirect("./home"); } } if (!check) { try { connection.close(); } catch (SQLException e) { displayMessage(res, "SQLException"); } displayMessage(res, "SQL query Failed!"); } } else { con.showErrormessage(res); } /*res.setContentType("text/html");//setting the content type PrintWriter pw=res.getWriter();//get the stream to write the data //writing html in the stream pw.println("<html><body>"); pw.println("Welcome to servlet: "+username); pw.println("</body></html>"); pw.close();//closing the stream */ } catch (Exception ex) { Logger.getLogger(authenticate.class.getName()).log(Level.SEVERE, null, ex); displayMessage(res, "Error!" + ex.getLocalizedMessage()); } }
From source file:com.javaweb.controller.SuaTinTucServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request servlet request/*w w w .j a v a 2 s . c om*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, ParseException { response.setContentType("text/html;charset=UTF-8"); request.setCharacterEncoding("UTF-8"); //response.setCharacterEncoding("UTF-8"); HttpSession session = request.getSession(); String TieuDe = "", NoiDung = "", ngaydang = "", GhiChu = "", fileName = ""; int idloaitin = 0, idTK = 0, idtt = 0; TintucService tintucservice = new TintucService(); //File upload String folderupload = getServletContext().getInitParameter("file-upload"); String rootPath = getServletContext().getRealPath("/"); filePath = rootPath + folderupload; isMultipart = ServletFileUpload.isMultipartContent(request); response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter(); 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("C:\\Windows\\Temp\\")); // 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(); //change file name fileName = FileService.ChangeFileName(fileName); // Write the file 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); // out.println("Uploaded Filename: " + fileName + "<br>"); } if (fi.isFormField()) { if (fi.getFieldName().equalsIgnoreCase("TieuDe")) { TieuDe = fi.getString("UTF-8"); } else if (fi.getFieldName().equalsIgnoreCase("NoiDung")) { NoiDung = fi.getString("UTF-8"); } else if (fi.getFieldName().equalsIgnoreCase("NgayDang")) { ngaydang = fi.getString("UTF-8"); } else if (fi.getFieldName().equalsIgnoreCase("GhiChu")) { GhiChu = fi.getString("UTF-8"); } else if (fi.getFieldName().equalsIgnoreCase("loaitin")) { idloaitin = Integer.parseInt(fi.getString("UTF-8")); } else if (fi.getFieldName().equalsIgnoreCase("idtaikhoan")) { idTK = Integer.parseInt(fi.getString("UTF-8")); } else if (fi.getFieldName().equalsIgnoreCase("idtt")) { idtt = Integer.parseInt(fi.getString("UTF-8")); } } } } catch (Exception ex) { System.out.println(ex); } Date NgayDang = new SimpleDateFormat("yyyy-MM-dd").parse(ngaydang); Tintuc tt = tintucservice.GetTintucID(idtt); tt.setIdTaiKhoan(idTK); tt.setTieuDe(TieuDe); tt.setNoiDung(NoiDung); tt.setNgayDang(NgayDang); tt.setGhiChu(GhiChu); if (!fileName.equals("")) { if (tt.getImgLink() != null) { if (!tt.getImgLink().equals(fileName)) { tt.setImgLink(fileName); } } else { tt.setImgLink(fileName); } } boolean rs = tintucservice.InsertTintuc(tt); if (rs) { session.setAttribute("kiemtra", "1"); response.sendRedirect("SuaTinTuc.jsp?idTintuc=" + idtt); } else { session.setAttribute("kiemtra", "0"); response.sendRedirect("SuaTinTuc.jsp?idTintuc=" + idtt); } // try (PrintWriter out = response.getWriter()) { // /* TODO output your page here. You may use following sample code. */ // out.println("<!DOCTYPE html>"); // out.println("<html>"); // out.println("<head>"); // out.println("<title>Servlet SuaTinTucServlet</title>"); // out.println("</head>"); // out.println("<body>"); // out.println("<h1>Servlet SuaTinTucServlet at " + request.getContextPath() + "</h1>"); // out.println("</body>"); // out.println("</html>"); // } }
From source file:com.wakasta.tubes2.AddProductPost.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String item_data = ""; // Check that we have a file upload request isMultipart = ServletFileUpload.isMultipartContent(request); response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter(); if (!isMultipart) { out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); out.println("<p>No file uploaded</p>"); out.println("</body>"); out.println("</html>"); return;/*from w w w . j a va 2 s. c o m*/ } 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("c:\\temp")); // 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(); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); String fileName = fi.getName(); String contentType = fi.getContentType(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); // Write the file if (fileName.lastIndexOf("\\") >= 0) { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\"))); } else { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1)); } item_data = Base64.encodeBase64String(fi.get()); fi.write(file); // out.println("Uploaded Filename: " + fileName + "<br>"); // out.println(file); } } out.println("</body>"); out.println("</html>"); } catch (FileUploadException ex) { Logger.getLogger(AddProductPost.class.getName()).log(Level.SEVERE, null, ex); } catch (java.lang.Exception ex) { Logger.getLogger(AddProductPost.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:admin.controller.ServletEditPersonality.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./* ww w . j a v a 2 s.c o m*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { super.processRequest(request, response); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); File file; int maxFileSize = 5000 * 1024; int maxMemSize = 5000 * 1024; try { uploadPath = AppConstants.BRAND_IMAGES_HOME; deletePath = AppConstants.BRAND_IMAGES_HOME; // Verify the content type String contentType = request.getContentType(); if ((contentType.indexOf("multipart/form-data") >= 0)) { 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(AppConstants.TMP_FOLDER)); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); out.println("<html>"); out.println("<head>"); out.println("<title>JSP File upload</title>"); out.println("</head>"); out.println("<body>"); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (fi.isFormField()) { // Get the uploaded file parameters fieldName = fi.getFieldName(); if (fieldName.equals("brandname")) { brandname = fi.getString(); } if (fieldName.equals("brandid")) { brandid = fi.getString(); } if (fieldName.equals("look")) { lookid = fi.getString(); } file_name_to_delete = brand.getFileName(Integer.parseInt(brandid)); } else { fieldName = fi.getFieldName(); fileName = fi.getName(); File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdirs(); } // int inStr = fileName.indexOf("."); // String Str = fileName.substring(0, inStr); // // fileName = brandname + "_" + Str + ".jpeg"; fileName = brandname + "_" + fileName; boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); String file_path = uploadPath + File.separator + fileName; String delete_path = deletePath + File.separator + file_name_to_delete; File deleteFile = new File(delete_path); deleteFile.delete(); File storeFile = new File(file_path); fi.write(storeFile); out.println("Uploaded Filename: " + filePath + "<br>"); } } brand.editBrands(Integer.parseInt(brandid), brandname, Integer.parseInt(lookid), fileName); response.sendRedirect(request.getContextPath() + "/admin/brandpersonality.jsp"); // request_dispatcher = request.getRequestDispatcher("/admin/looks.jsp"); // request_dispatcher.forward(request, response); out.println("</body>"); out.println("</html>"); } else { out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); out.println("<p>No file uploaded</p>"); out.println("</body>"); out.println("</html>"); } } catch (Exception ex) { logger.log(Level.SEVERE, "", ex); } finally { out.close(); } }
From source file:com.deem.zkui.controller.Import.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.debug("Importing Action!"); try {/*from w ww . ja v a 2s .com*/ Properties globalProps = (Properties) this.getServletContext().getAttribute("globalProps"); Dao dao = new Dao(globalProps); String zkServer = globalProps.getProperty("zkServer"); String[] zkServerLst = zkServer.split(","); StringBuilder sbFile = new StringBuilder(); String scmOverwrite = "false"; String scmServer = ""; String scmFilePath = ""; String scmFileRevision = ""; String uploadFileName = ""; DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1034); ServletFileUpload upload = new ServletFileUpload(factory); List items = upload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { if (item.getFieldName().equals("scmOverwrite")) { scmOverwrite = item.getString(); } if (item.getFieldName().equals("scmServer")) { scmServer = item.getString(); } if (item.getFieldName().equals("scmFilePath")) { scmFilePath = item.getString(); } if (item.getFieldName().equals("scmFileRevision")) { scmFileRevision = item.getString(); } } else { uploadFileName = item.getName(); sbFile.append(item.getString()); } } InputStream inpStream; if (sbFile.toString().length() == 0) { uploadFileName = scmServer + scmFileRevision + "@" + scmFilePath; logger.debug("P4 file Processing " + uploadFileName); dao.insertHistory((String) request.getSession().getAttribute("authName"), request.getRemoteAddr(), "Importing P4 File: " + uploadFileName + "<br/>" + "Overwrite: " + scmOverwrite); URL url = new URL(uploadFileName); URLConnection conn = url.openConnection(); inpStream = conn.getInputStream(); } else { logger.debug("Upload file Processing " + uploadFileName); dao.insertHistory((String) request.getSession().getAttribute("authName"), request.getRemoteAddr(), "Uploading File: " + uploadFileName + "<br/>" + "Overwrite: " + scmOverwrite); inpStream = new ByteArrayInputStream(sbFile.toString().getBytes()); } // open the stream and put it into BufferedReader BufferedReader br = new BufferedReader(new InputStreamReader(inpStream)); String inputLine; List<String> importFile = new ArrayList<>(); Integer lineCnt = 0; while ((inputLine = br.readLine()) != null) { lineCnt++; // Empty or comment? if (inputLine.trim().equals("") || inputLine.trim().startsWith("#")) { continue; } if (inputLine.startsWith("-")) { //DO nothing. } else if (!inputLine.matches("/.+=.+=.*")) { throw new IOException("Invalid format at line " + lineCnt + ": " + inputLine); } importFile.add(inputLine); } br.close(); ZooKeeperUtil.INSTANCE.importData(importFile, Boolean.valueOf(scmOverwrite), ServletUtil.INSTANCE.getZookeeper(request, response, zkServerLst[0], globalProps)); for (String line : importFile) { if (line.startsWith("-")) { dao.insertHistory((String) request.getSession().getAttribute("authName"), request.getRemoteAddr(), "File: " + uploadFileName + ", Deleting Entry: " + line); } else { dao.insertHistory((String) request.getSession().getAttribute("authName"), request.getRemoteAddr(), "File: " + uploadFileName + ", Adding Entry: " + line); } } request.getSession().setAttribute("flashMsg", "Import Completed!"); response.sendRedirect("/home"); } catch (FileUploadException | IOException | InterruptedException | KeeperException ex) { logger.error(Arrays.toString(ex.getStackTrace())); ServletUtil.INSTANCE.renderError(request, response, ex.getMessage()); } }
From source file:admin.controller.ServletAddCategories.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// ww w.j a v a2 s . c om * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { super.processRequest(request, response); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); File file; int maxFileSize = 5000 * 1024; int maxMemSize = 5000 * 1024; try { String uploadPath = AppConstants.ORG_CATEGORIES_HOME; // Verify the content type String contentType = request.getContentType(); if ((contentType.indexOf("multipart/form-data") >= 0)) { 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(AppConstants.TMP_FOLDER)); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); out.println("<html>"); out.println("<head>"); out.println("<title>JSP File upload</title>"); out.println("</head>"); out.println("<body>"); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (fi.isFormField()) { // Get the uploaded file parameters field_name = fi.getFieldName(); if (field_name.equals("category_name")) { category_name = fi.getString(); } if (field_name.equals("organization")) { organization_id = fi.getString(); uploadPath = uploadPath + File.separator + organization_id; } } else { field_name = fi.getFieldName(); file_name = fi.getName(); if (file_name != "") { check = categories.checkAvailability(category_name, Integer.parseInt(organization_id)); if (check == false) { File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdirs(); } //we need to save file name directly // int inStr = file_name.indexOf("."); // String Str = file_name.substring(0, inStr); // file_name = category_name + "_" + Str + ".jpeg"; file_name = category_name + "_" + file_name; boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); String filePath = uploadPath + File.separator + file_name; File storeFile = new File(filePath); fi.write(storeFile); categories.addCategories(Integer.parseInt(organization_id), category_name, file_name); out.println("Uploaded Filename: " + filePath + "<br>"); response.sendRedirect(request.getContextPath() + "/admin/categories.jsp"); } else { response.sendRedirect( request.getContextPath() + "/admin/categories.jsp?exist=exist"); } } } } out.println("</body>"); out.println("</html>"); } else { out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); out.println("<p>No file uploaded</p>"); out.println("</body>"); out.println("</html>"); } } catch (Exception ex) { logger.log(Level.SEVERE, "Exception while adding categories", ex); } finally { out.close(); } }
From source file:com.nartex.FileManager.java
public FileManager(ServletContext servletContext, HttpServletRequest request) { // get document root like in php String contextPath = request.getContextPath(); String documentRoot = servletContext.getRealPath("/").replaceAll("\\\\", "/"); documentRoot = documentRoot.substring(0, documentRoot.indexOf(contextPath)); this.referer = request.getHeader("referer"); this.fileManagerRoot = documentRoot + referer.substring(referer.indexOf(contextPath), referer.indexOf("index.html")); // get uploaded file list FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); if (ServletFileUpload.isMultipartContent(request)) try {//from w w w . j a v a 2 s. co m files = upload.parseRequest(request); } catch (Exception e) { // no error handling} } this.properties.put("Date Created", null); this.properties.put("Date Modified", null); this.properties.put("Height", null); this.properties.put("Width", null); this.properties.put("Size", null); // load config file loadConfig(); if (config.getProperty("doc_root") != null) this.documentRoot = config.getProperty("doc_root"); else this.documentRoot = documentRoot; dateFormat = new SimpleDateFormat(config.getProperty("date")); this.setParams(); loadLanguageFile(); }
From source file:eu.impact_project.iif.t2.client.Helper.java
/** * Extracts all the form input values from a request object. Taverna * workflows are read as strings. Other files are converted to Base64 * strings./*from w w w . j a v a 2 s . c om*/ * * @param request * The request object that will be analyzed * @return Map containing all form values and files as strings. The name of * the form is used as the index */ public static Map<String, String> parseRequest(HttpServletRequest request) { // stores all the strings and encoded files from the html form Map<String, String> htmlFormItems = new HashMap<String, String>(); try { // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List items; items = upload.parseRequest(request); // Process the uploaded items Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); // a normal string field if (item.isFormField()) { // put the string items into the map htmlFormItems.put(item.getFieldName(), item.getString()); // uploaded workflow file } else if (item.getFieldName().startsWith("file_workflow")) { htmlFormItems.put(item.getFieldName(), new String(item.get())); // uploaded file } else { // encode the uploaded file to base64 String currentAttachment = new String(Base64.encode(item.get())); // put the encoded attachment into the map htmlFormItems.put(item.getFieldName(), currentAttachment); } } } catch (FileUploadException e) { e.printStackTrace(); } return htmlFormItems; }