List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload parseRequest
public List parseRequest(HttpServletRequest request) throws FileUploadException
From source file:admin.controller.ServletEditPersonality.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w . java2s . 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 */ @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:it.geosolutions.servicebox.FileUploadCallback.java
/** * Handle a POST request/*from w ww.j av a 2 s .c o m*/ * * @param request * @param response * * @return CallbackResult * * @throws IOException */ @SuppressWarnings("unchecked") public ServiceBoxActionParameters onPost(HttpServletRequest request, HttpServletResponse response, ServiceBoxActionParameters callbackResult) throws IOException { // Get items if already initialized List<FileItem> items = null; if (callbackResult == null) { callbackResult = new ServiceBoxActionParameters(); } else { items = callbackResult.getItems(); } String temp = callbackConfiguration.getTempFolder(); int buffSize = callbackConfiguration.getBuffSize(); int itemSize = 0; long maxSize = 0; String itemName = null; boolean fileTypeMatch = true; File tempDir = new File(temp); try { if (items == null && ServletFileUpload.isMultipartContent(request) && tempDir != null && tempDir.exists()) { // items are not initialized. Read it from the request DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); /* * Set the size threshold, above which content will be stored on * disk. */ fileItemFactory.setSizeThreshold(buffSize); // 1 MB /* * Set the temporary directory to store the uploaded files of * size above threshold. */ fileItemFactory.setRepository(tempDir); ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); /* * Parse the request */ items = uploadHandler.parseRequest(request); } // Read items if (items != null) { itemSize = items.size(); callbackResult.setItems(items); if (itemSize <= this.callbackConfiguration.getMaxItems()) { // only if item size not exceeded max for (FileItem item : items) { itemName = item.getName(); if (item.getSize() > maxSize) { maxSize = item.getSize(); if (maxSize > this.callbackConfiguration.getMaxSize()) { // max size exceeded break; } else if (this.callbackConfiguration.getFileTypePatterns() != null) { fileTypeMatch = false; int index = 0; while (!fileTypeMatch && index < this.callbackConfiguration.getFileTypePatterns().size()) { Pattern pattern = this.callbackConfiguration.getFileTypePatterns().get(index++); fileTypeMatch = pattern.matcher(itemName).matches(); } if (!fileTypeMatch) { break; } } } } } } else { itemSize = 1; maxSize = request.getContentLength(); // TODO: Handle file type } } catch (Exception ex) { if (LOGGER.isLoggable(Level.SEVERE)) LOGGER.log(Level.SEVERE, "Error encountered while parsing the request"); response.setContentType("text/html"); JSONObject jsonObj = new JSONObject(); jsonObj.put("success", false); jsonObj.put("errorMessage", ex.getLocalizedMessage()); Utilities.writeResponse(response, jsonObj.toString(), LOGGER); } // prepare and send error if exists boolean error = false; int errorCode = -1; String message = null; Map<String, Object> errorDetails = null; if (itemSize > this.callbackConfiguration.getMaxItems()) { errorDetails = new HashMap<String, Object>(); error = true; errorDetails.put("expected", this.callbackConfiguration.getMaxItems()); errorDetails.put("found", itemSize); errorCode = Utilities.JSON_MODEL.KNOWN_ERRORS.MAX_ITEMS.ordinal(); message = "Max items size exceeded (expected: '" + this.callbackConfiguration.getMaxItems() + "', found: '" + itemSize + "')."; } else if (maxSize > this.callbackConfiguration.getMaxSize()) { errorDetails = new HashMap<String, Object>(); error = true; errorDetails.put("expected", this.callbackConfiguration.getMaxSize()); errorDetails.put("found", maxSize); errorDetails.put("item", itemName); errorCode = Utilities.JSON_MODEL.KNOWN_ERRORS.MAX_ITEM_SIZE.ordinal(); message = "Max item size exceeded (expected: '" + this.callbackConfiguration.getMaxSize() + "', found: '" + maxSize + "' on item '" + itemName + "')."; } else if (fileTypeMatch == false) { errorDetails = new HashMap<String, Object>(); error = true; String expected = this.callbackConfiguration.getFileTypes(); errorDetails.put("expected", expected); errorDetails.put("found", itemName); errorDetails.put("item", itemName); errorCode = Utilities.JSON_MODEL.KNOWN_ERRORS.ITEM_TYPE.ordinal(); message = "File type not maches with known file types: (expected: '" + expected + "', item '" + itemName + "')."; } if (error) { callbackResult.setSuccess(false); Utilities.writeError(response, errorCode, errorDetails, message, LOGGER); } else { callbackResult.setSuccess(true); } return callbackResult; }
From source file:com.github.davidcarboni.encryptedfileupload.SizesTest.java
/** Checks, whether a faked Content-Length header is detected. *//*from ww w .j ava 2s.co m*/ @Test public void testFileSizeLimitWithFakedContentLength() throws IOException, FileUploadException { final String request = "-----1234\r\n" + "Content-Disposition: form-data; name=\"file\"; filename=\"foo.tab\"\r\n" + "Content-Type: text/whatever\r\n" + "Content-Length: 10\r\n" + "\r\n" + "This is the content of the file\n" + "\r\n" + "-----1234--\r\n"; ServletFileUpload upload = new ServletFileUpload(new EncryptedFileItemFactory()); upload.setFileSizeMax(-1); HttpServletRequest req = new MockHttpServletRequest(request.getBytes("US-ASCII"), CONTENT_TYPE); List<FileItem> fileItems = upload.parseRequest(req); assertEquals(1, fileItems.size()); FileItem item = fileItems.get(0); assertEquals("This is the content of the file\n", new String(item.get())); upload = new ServletFileUpload(new EncryptedFileItemFactory()); upload.setFileSizeMax(40); req = new MockHttpServletRequest(request.getBytes("US-ASCII"), CONTENT_TYPE); fileItems = upload.parseRequest(req); assertEquals(1, fileItems.size()); item = fileItems.get(0); assertEquals("This is the content of the file\n", new String(item.get())); // provided Content-Length is larger than the FileSizeMax -> handled by ctor upload = new ServletFileUpload(new EncryptedFileItemFactory()); upload.setFileSizeMax(5); req = new MockHttpServletRequest(request.getBytes("US-ASCII"), CONTENT_TYPE); try { upload.parseRequest(req); fail("Expected exception."); } catch (FileUploadBase.FileSizeLimitExceededException e) { assertEquals(5, e.getPermittedSize()); } // provided Content-Length is wrong, actual content is larger -> handled by LimitedInputStream upload = new ServletFileUpload(new EncryptedFileItemFactory()); upload.setFileSizeMax(15); req = new MockHttpServletRequest(request.getBytes("US-ASCII"), CONTENT_TYPE); try { upload.parseRequest(req); fail("Expected exception."); } catch (FileUploadBase.FileSizeLimitExceededException e) { assertEquals(15, e.getPermittedSize()); } }
From source file:emsa.webcoc.cleanup.servlet.UploadServet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w. ja v a2s . 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 */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { isMultipart = ServletFileUpload.isMultipartContent(request); response.setContentType("text/html"); PrintWriter out = response.getWriter(); if (!isMultipart) { out.println("<html>"); out.println("<head>"); out.println("<title>XML file clean up</title>"); out.println("</head>"); out.println("<body>"); out.println("<p>No file uploaded</p>"); out.println("</body>"); out.println("</html>"); return; } DiskFileItemFactory factory = new DiskFileItemFactory(); //Maximum size that will be stored into memory factory.setSizeThreshold(MAXMEMSIZE); //Path to save file if its size is bigger than MAXMEMSIZE factory.setRepository(new File(REPOSITORY)); ServletFileUpload upload = new ServletFileUpload(factory); out.println("<html>"); out.println("<head>"); out.println("<title>XML file clean up</title>"); out.println("</head>"); out.println("<body>"); try { List<FileItem> fileItems = upload.parseRequest(request); Iterator<FileItem> t = fileItems.iterator(); while (t.hasNext()) { FileItem f = t.next(); if (!f.isFormField()) { if (f.getContentType().equals("text/xml")) { //Check weather or not the uploaded file is an XML file String uniqueFileName = f.getName() + "-" + request.getSession().getId() + ".xml"; //Creates unique name String location = (String) this.getServletContext().getAttribute("newFileLocation"); CoCCleanUp clean = new CoCCleanUp(uniqueFileName, location); if (clean.cleanDocument(f.getInputStream()) == 0) { out.println("<h3>" + f.getName() + " was clean</h3>"); out.println(clean.printHTMLStatistics()); out.println("<br /><form action='download?filename=" + uniqueFileName + "' method='post'><input type='submit' value='Download'/></form></body></html>"); } else { out.println("<h3>" + clean.getErrorMessage() + "</h3>"); out.println( "<br /><form action='index.html' method='post'><input type='submit' value='Go Back'/></form></body></html>"); } } else { out.println("<h3>The file " + f.getName() + " is not an xml file</h3>"); out.println( "<br /><form action='index.html' method='post'><input type='submit' value='Go Back'/></form></body></html>"); logger.warn("The file " + f.getName() + " is not an xml file: " + f.getContentType()); } } } File repository = factory.getRepository(); cleanTmpFiles(repository); } catch (IOException | FileUploadException e) { out.println("<h3>Something went wrong</h3></br>"); out.println( "<br /><form action='index.html' method='post'><input type='submit' value='Go Back'/></form></body></html>"); } }
From source file:admin.controller.ServletUpdateFonts.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w ww. j a v a 2s. com*/ * * @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(); String filePath = null; String fileName = null, fieldName = null, uploadPath = null, deletePath = null, file_name_to_delete = ""; RequestDispatcher request_dispatcher; String fontname = null, fontid = null, lookid; File file; int maxFileSize = 5000 * 1024; int maxMemSize = 5000 * 1024; try { uploadPath = AppConstants.BASE_FONT_UPLOAD_PATH; deletePath = AppConstants.BASE_FONT_UPLOAD_PATH; // 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("fontname")) { fontname = fi.getString(); } if (fieldName.equals("fontid")) { fontid = fi.getString(); file_name_to_delete = font.getFileName(Integer.parseInt(fontid)); } } else { fieldName = fi.getFieldName(); fileName = fi.getName(); if (fileName != "") { File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdirs(); } 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>"); } } } font.changeFont(Integer.parseInt(fontid), fontname, fileName); response.sendRedirect(request.getContextPath() + "/admin/fontsfamily.jsp"); 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 Updating fonts", ex); } finally { try { out.close(); } catch (Exception e) { } } }
From source file:com.javaweb.controller.ThemTinTucServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request servlet request//from w w w . j a va2 s . com * @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(); // session.removeAttribute("errorreg"); String TieuDe = "", NoiDung = "", ngaydang = "", GhiChu = "", fileName = ""; int idloaitin = 0, idTK = 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")); } } } } catch (Exception ex) { System.out.println(ex); } Date NgayDang = new SimpleDateFormat("yyyy-MM-dd").parse(ngaydang); Tintuc tintuc = new Tintuc(idloaitin, idTK, fileName, TieuDe, NoiDung, NgayDang, GhiChu); boolean rs = tintucservice.InsertTintuc(tintuc); if (rs) { session.setAttribute("kiemtra", "1"); String url = "ThemTinTuc.jsp"; response.sendRedirect(url); } else { session.setAttribute("kiemtra", "0"); String url = "ThemTinTuc.jsp"; response.sendRedirect(url); } // 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 ThemTinTucServlet</title>"); // out.println("</head>"); // out.println("<body>"); // out.println("<h1>Servlet ThemTinTucServlet at " + request.getContextPath() + "</h1>"); // out.println("</body>"); // out.println("</html>"); // } }
From source file:com.primeleaf.krystal.web.action.console.CheckInDocumentAction.java
@SuppressWarnings({ "unchecked", "rawtypes" }) public WebView execute(HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); User loggedInUser = (User) session.getAttribute(HTTPConstants.SESSION_KRYSTAL); try {/*from www. j a v a2 s . c o m*/ if ("POST".equalsIgnoreCase(request.getMethod())) { String errorMessage; String tempFilePath = System.getProperty("java.io.tmpdir"); if (!(tempFilePath.endsWith("/") || tempFilePath.endsWith("\\"))) { tempFilePath += System.getProperty("file.separator"); } tempFilePath += loggedInUser.getUserName() + "_" + session.getId(); String revisionId = "", comments = "", fileName = "", ext = "", version = ""; int documentId = 0; // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); List items = upload.parseRequest((HttpServletRequest) request); upload.setHeaderEncoding(HTTPConstants.CHARACTER_ENCODING); //Create a file upload progress listener Iterator iter = items.iterator(); FileItem item = null; File file = null; while (iter.hasNext()) { item = (FileItem) iter.next(); if (item.isFormField()) { String name = item.getFieldName(); String value = item.getString(HTTPConstants.CHARACTER_ENCODING); if (name.equals("documentid")) { try { documentId = Integer.parseInt(value); } catch (Exception ex) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid input"); return (new CheckInDocumentView(request, response)); } } else if (name.equals("revisionid")) { revisionId = value; } else if (name.equals("txtNote")) { comments = value; } else if ("version".equalsIgnoreCase(name)) { version = value; } } else { fileName = item.getName(); ext = fileName.substring(fileName.lastIndexOf(".") + 1).toUpperCase(); file = new File(tempFilePath + "." + ext); item.write(file); } } iter = null; Document document = DocumentDAO.getInstance().readDocumentById(documentId); if (document == null) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid document"); return (new CheckInDocumentView(request, response)); } if (document.getStatus().equalsIgnoreCase(Hit.STATUS_AVAILABLE)) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid check-in"); return (new CheckInDocumentView(request, response)); } revisionId = document.getRevisionId(); DocumentClass documentClass = DocumentClassDAO.getInstance() .readDocumentClassById(document.getClassId()); AccessControlManager aclManager = new AccessControlManager(); ACL acl = aclManager.getACL(documentClass, loggedInUser); if (!acl.canCheckin()) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Access Denied"); return (new CheckInDocumentView(request, response)); } if (file.length() <= 0) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Zero length document"); return (new CheckInDocumentView(request, response)); } if (file.length() > documentClass.getMaximumFileSize()) { //code for checking maximum size of document in a class request.setAttribute(HTTPConstants.REQUEST_ERROR, "Document size exceeded"); return (new CheckInDocumentView(request, response)); } String indexValue = ""; String indexName = ""; Hashtable indexRecord = new Hashtable(); for (IndexDefinition indexDefinition : documentClass.getIndexDefinitions()) { indexName = indexDefinition.getIndexColumnName(); Iterator itemsIterator = items.iterator(); while (itemsIterator.hasNext()) { FileItem fileItem = (FileItem) itemsIterator.next(); if (fileItem.isFormField()) { String name = fileItem.getFieldName(); String value = fileItem.getString(HTTPConstants.CHARACTER_ENCODING); if (name.equals(indexName)) { indexValue = value; if (indexValue != null) { if (indexDefinition.isMandatory()) { if (indexValue.trim().length() <= 0) { errorMessage = "Invalid input for " + indexDefinition.getIndexDisplayName(); request.setAttribute(HTTPConstants.REQUEST_ERROR, errorMessage); return (new CheckInDocumentView(request, response)); } } if (IndexDefinition.INDEXTYPE_NUMBER .equalsIgnoreCase(indexDefinition.getIndexType())) { if (indexValue.trim().length() > 0) { if (!GenericValidator.matchRegexp(indexValue, HTTPConstants.NUMERIC_REGEXP)) { errorMessage = "Invalid input for " + indexDefinition.getIndexDisplayName(); request.setAttribute(HTTPConstants.REQUEST_ERROR, errorMessage); return (new CheckInDocumentView(request, response)); } } } else if (IndexDefinition.INDEXTYPE_DATE .equalsIgnoreCase(indexDefinition.getIndexType())) { if (indexValue.trim().length() > 0) { if (!GenericValidator.isDate(indexValue, "yyyy-MM-dd", true)) { errorMessage = "Invalid input for " + indexDefinition.getIndexDisplayName(); request.setAttribute(HTTPConstants.REQUEST_ERROR, errorMessage); return (new CheckInDocumentView(request, response)); } } } if (indexValue.trim().length() > indexDefinition.getIndexMaxLength()) { //code for checking maximum length of index field errorMessage = "Document index length exceeded. Index Name :" + indexDefinition.getIndexDisplayName() + " [ " + "Index Length : " + indexDefinition.getIndexMaxLength() + " , " + "Actual Length : " + indexValue.length() + " ]"; request.setAttribute(HTTPConstants.REQUEST_ERROR, errorMessage); return (new CheckInDocumentView(request, response)); } } indexRecord.put(indexName, indexValue); } } fileItem = null; } // while iter itemsIterator = null; } // while indexDefinitionItr CheckedOutDocument checkedOutDocument = new CheckedOutDocument(); checkedOutDocument.setDocumentId(documentId); // Added by Viral Visaria. For the Version Control minor and major. // In minor revision increment by 0.1. (No Changes required for the minor revision its handled in the core logic) // In major revision increment by 1.0 (Below chages are incremented by 0.9 and rest 0.1 will be added in the core logic. (0.9 + 0.1 = 1.0) double rev = Double.parseDouble(revisionId); if ("major".equals(version)) { rev = Math.floor(rev); rev = rev + 0.9; revisionId = String.valueOf(rev); } checkedOutDocument.setRevisionId(revisionId); checkedOutDocument.setUserName(loggedInUser.getUserName()); RevisionManager revisionManager = new RevisionManager(); revisionManager.checkIn(checkedOutDocument, documentClass, indexRecord, file, comments, ext, loggedInUser.getUserName()); //revision id incremented by 0.1 for making entry in audit log rev += 0.1; revisionId = String.valueOf(rev); //add to audit log AuditLogManager.log(new AuditLogRecord(documentId, AuditLogRecord.OBJECT_DOCUMENT, AuditLogRecord.ACTION_CHECKIN, loggedInUser.getUserName(), request.getRemoteAddr(), AuditLogRecord.LEVEL_INFO, "Document ID : " + documentId + " Revision ID :" + revisionId, "Checked In")); request.setAttribute(HTTPConstants.REQUEST_MESSAGE, "Document checked in successfully"); return (new CheckInDocumentView(request, response)); } int documentId = 0; try { documentId = Integer.parseInt( request.getParameter("documentid") != null ? request.getParameter("documentid") : "0"); } catch (Exception e) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid input"); return (new CheckInDocumentView(request, response)); } Document document = DocumentDAO.getInstance().readDocumentById(documentId); if (document == null) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid document"); return (new CheckInDocumentView(request, response)); } if (!Hit.STATUS_LOCKED.equalsIgnoreCase(document.getStatus())) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid checkin"); return (new CheckInDocumentView(request, response)); } DocumentClass documentClass = DocumentClassDAO.getInstance() .readDocumentClassById(document.getClassId()); LinkedHashMap<String, String> documentIndexes = IndexRecordManager.getInstance() .readIndexRecord(documentClass, documentId, document.getRevisionId()); request.setAttribute("DOCUMENTCLASS", documentClass); request.setAttribute("DOCUMENT", document); request.setAttribute("DOCUMENTINDEXES", documentIndexes); } catch (Exception e) { e.printStackTrace(); } return (new CheckInDocumentView(request, response)); }
From source file:com.wfms.common.web.ConnectorServlet.java
/** * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br /> * // ww w . j a va 2s . c om * 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); 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); //add code filename = UUID.randomUUID().toString() + "." + extension; if (!ExtensionsHandler.isAllowed(resourceType, extension)) { ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); } //add conde to validate file size else if (uplFile.getSize() > 1024 * 1024) { ur = new UploadResponse(204); } 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:controller.controller.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./* w w w . jav 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 */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); HttpSession session = request.getSession(); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ String action = request.getParameter("action"); String type = request.getParameter("type"); System.out.println(action); if (action.equals("getproduct")) { System.out.println(type); DAO dao = new DAO(); ArrayList<pro> product = dao.getProduct(type); session.setAttribute("product", product); dispatcher(request, response, "tablet.jsp"); } if (action.equals("productDetail")) { int id = Integer.parseInt(request.getParameter("id")); DAO detail = new DAO(); pro productDetail = detail.productDetail(id); session.setAttribute("productdetail", productDetail); dispatcher(request, response, "view.jsp"); } if (action.equals("AddtoCart")) { System.out.println(action); shoppingCart cart = (shoppingCart) session.getAttribute("cart"); if (cart == null) { System.out.println("cart: " + null); cart = new shoppingCart(); } System.out.println("product " + session.getAttribute("productdetail")); pro temp = (pro) session.getAttribute("productdetail"); int qu = temp.getQuantity(); System.out.println("qu " + qu); if (qu > 0) { --qu; System.out.println("qu " + qu); temp.setQuantity(qu); //int quantity = Integer.parseInt(request.getParameter("quantity")); cart.addProduct(temp); System.out.println("cart " + cart.getProducts().size()); } session.setAttribute("cart", cart); } if (action.equals("checkout")) { System.out.println(action); shoppingCart cart = (shoppingCart) session.getAttribute("cart"); if (cart == null) { cart = new shoppingCart(); } session.setAttribute("cart", cart); dispatcher(request, response, "checkout.jsp"); } if (action.equals("order")) { shoppingCart cart = (shoppingCart) session.getAttribute("cart"); String accid = (String) session.getAttribute("login"); DAO dao = new DAO(); dao.order(cart, accid); session.removeAttribute("cart"); response.sendRedirect("index.jsp"); } if (action.equals("upload")) { String dirNames = "D:\\Task\\IU\\Web Application Development\\New\\Final project\\ECommerceProject"; String user = (String) session.getAttribute("login"); String fileName = null; boolean isMultiPArt = ServletFileUpload.isMultipartContent(request); if (isMultiPArt) { System.out.println(1); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items = null; try { items = upload.parseRequest(request); } catch (FileUploadException e) { e.printStackTrace(); } Iterator iter = items.iterator(); Hashtable params = new Hashtable(); File theDir = new File(dirNames + File.separator + user); // if the directory does not exist, create it if (!theDir.exists()) { System.out.println("creating directory: " + user); boolean result = false; try { theDir.mkdir(); result = true; } catch (SecurityException se) { //handle it } if (result) { System.out.println("DIR created"); } } String[] url = new String[5]; int cnt = 0; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { params.put(item.getFieldName(), item.getString()); } else { try { String itemName = item.getName(); fileName = itemName.substring(itemName.lastIndexOf("\\") + 1); System.out.println("path: " + fileName); String realPath = dirNames + File.separator + user + File.separator + fileName; System.out.println("realPath: " + realPath); File savedFile = new File(realPath); item.write(savedFile); url[cnt] = "./database" + File.separator + user + File.separator + fileName; ++cnt; } catch (Exception e) { e.printStackTrace(); } } } String name = (String) params.get("name"); String price = (String) params.get("price"); String quantity = (String) params.get("quantity"); String typepr = (String) params.get("type"); System.out.println(name + " " + price + " " + quantity + " " + typepr); DAO uploadReal = new DAO(); uploadReal.inserPro(name, price, quantity, typepr, url[0]); // newUser = new User(); // newUser.setEmail(Email); out.print(url[0]); String temp = ".\\User" + File.separator + user + File.separator + fileName; System.out.println("Temp " + temp); //Connector.editUser(myProfile.getEmail(), newUser); //response.sendRedirect("index.jsp"); dispatcher(request, response, "index.jsp"); } } } }
From source file:admin.controller.ServletEditCategories.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// w w w.java 2s. 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 { upload_path = 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("category_id")) { category_id = fi.getString(); } if (field_name.equals("organization")) { organization_id = fi.getString(); upload_path = upload_path + File.separator + organization_id; } } else { field_name = fi.getFieldName(); file_name = fi.getName(); if (file_name != "") { File uploadDir = new File(upload_path); if (!uploadDir.exists()) { uploadDir.mkdirs(); } // 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 = upload_path + File.separator + file_name; File storeFile = new File(filePath); fi.write(storeFile); out.println("Uploaded Filename: " + filePath + "<br>"); } } } categories.editCategories(Integer.parseInt(category_id), Integer.parseInt(organization_id), category_name, file_name); response.sendRedirect(request.getContextPath() + "/admin/categories.jsp"); 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 editing categories", ex); } finally { try { out.close(); } catch (Exception e) { } } }