List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload ServletFileUpload
public ServletFileUpload(FileItemFactory fileItemFactory)
FileItem
instances. From source file:gov.nih.nci.queue.servlet.FileUploadServlet.java
/** * ************************************************* * URL: /upload doPost(): upload the files and other parameters * * @param request/*ww w. j a v a 2s .c o m*/ * @param response * @throws javax.servlet.ServletException * @throws java.io.IOException * ************************************************** */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Create an object for JSON response. ResponseModel rm = new ResponseModel(); // Set response type to json response.setContentType("application/json"); PrintWriter writer = response.getWriter(); // Get property values. // SOCcer related. final Double estimatedThreshhold = Double .valueOf(PropertiesUtil.getProperty("gov.nih.nci.soccer.computing.time.threshhold").trim()); // FileUpload Settings. final String repositoryPath = PropertiesUtil.getProperty("gov.nih.nci.queue.repository.dir"); final String strOutputDir = PropertiesUtil.getProperty("gov.nih.cit.soccer.output.dir").trim(); final long fileSizeMax = 10000000000L; // 10G LOGGER.log(Level.INFO, "repository.dir: {0}, filesize.max: {1}, time.threshhold: {2}", new Object[] { repositoryPath, fileSizeMax, estimatedThreshhold }); // Check that we have a file upload request // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(request); // Ensuring that the request is actually a file upload request. if (isMultipart) { // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); //upload file dirctory. If it does not exist, create one. File f = new File(repositoryPath); if (!f.exists()) { f.mkdir(); } // Set factory constraints // factory.setSizeThreshold(yourMaxMemorySize); // Configure a repository factory.setRepository(new File(repositoryPath)); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(fileSizeMax); try { // Parse the request List<FileItem> items = upload.parseRequest(request); // Process the uploaded items Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (!item.isFormField()) { // Handle file field. String fileName = item.getName(); rm.setFileName(fileName); String contentType = item.getContentType(); rm.setFileType(contentType); long sizeInBytes = item.getSize(); rm.setFileSize(String.valueOf(sizeInBytes)); String inputFileId = new UniqueIdUtil(fileName).getInputUniqueID(); rm.setInputFileId(inputFileId); String absoluteInputFileName = repositoryPath + File.separator + inputFileId; rm.setRepositoryPath(repositoryPath); // Write file to the destination folder. File inputFile = new File(absoluteInputFileName); item.write(inputFile); // Validation. InputFileValidator validator = new InputFileValidator(); List<String> validationErrors = validator.validateFile(inputFile); if (validationErrors == null) { // Pass validation // check estimatedProcessingTime. SoccerServiceHelper soccerHelper = new SoccerServiceHelper(strOutputDir); Double estimatedTime = soccerHelper.getEstimatedTime(absoluteInputFileName); rm.setEstimatedTime(String.valueOf(estimatedTime)); if (estimatedTime > estimatedThreshhold) { // STATUS: QUEUE (Ask client for email) // Construct Response String in JSON format. rm.setStatus("queue"); } else { // STATUS: PASS (Ask client to confirm calculate) // all good. Process the output and Go to result page directly. rm.setStatus("pass"); } } else { // STATUS: FAIL // Did not pass validation. // Construct Response String in JSON format. rm.setStatus("invalid"); rm.setDetails(validationErrors); } } else { // TODO: Handle Form Fields such as SOC_SYSTEM. } // End of isFormField } } catch (Exception e) { LOGGER.log(Level.SEVERE, "FileUploadException or FileNotFoundException. Error Message: {0}", new Object[] { e.getMessage() }); rm.setStatus("fail"); rm.setErrorMessage( "Oops! We met with problems when uploading your file. Error Message: " + e.getMessage()); } // Send the response. ObjectMapper jsonMapper = new ObjectMapper(); LOGGER.log(Level.INFO, "Response: {0}", new Object[] { jsonMapper.writeValueAsString(rm) }); // Generate metadata file new MetadataFileUtil(rm.getInputFileId(), repositoryPath) .generateMetadataFile(jsonMapper.writeValueAsString(rm)); // Responde to the client. writer.print(jsonMapper.writeValueAsString(rm)); } else { // The request is NOT actually a file upload request writer.print("You hit the wrong file upload page. The request is NOT actually a file upload request."); } }
From source file:prop_add_serv.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./* www.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, FileUploadException { response.setContentType("text/html;charset=UTF-8"); HttpSession hs = request.getSession(); PrintWriter out = response.getWriter(); try { if (hs.getAttribute("user") != null) { Login ln = (Login) hs.getAttribute("user"); System.out.println(ln.getUId()); String pradd1 = ""; String pradd2 = ""; String prage = ""; String prarea = ""; String prbhk = ""; String prdescrip = ""; String prprice = ""; String prcity = ""; String prstate = ""; String prname = ""; String prtype = ""; String prfarea = ""; String prphoto1 = ""; String prphoto2 = ""; String prphoto3 = ""; String prphoto4 = ""; // // creates FileItem instances which keep their content in a temporary file on disk FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); //get the list of all fields from request List<FileItem> fields = upload.parseRequest(request); // iterates the object of list Iterator<FileItem> it = fields.iterator(); //getting objects one by one while (it.hasNext()) { //assigning coming object if list to object of FileItem FileItem fileItem = it.next(); //check whether field is form field or not boolean isFormField = fileItem.isFormField(); if (isFormField) { //get the filed name String fieldName = fileItem.getFieldName(); if (fieldName.equals("pname")) { //getting value of field prname = fileItem.getString(); System.out.println(prname); } else if (fieldName.equals("price")) { //getting value of field prprice = fileItem.getString(); System.out.println(prprice); } else if (fieldName.equals("city")) { prcity = fileItem.getString(); System.out.println(prcity); } else if (fieldName.equals("state")) { prstate = fileItem.getString(); System.out.println(prstate); } else if (fieldName.equals("area")) { prarea = fileItem.getString(); System.out.println(prarea); } else if (fieldName.equals("pbhk")) { prbhk = fileItem.getString(); System.out.println(prbhk); } else if (fieldName.equals("pdescription")) { prdescrip = fileItem.getString(); System.out.println(prdescrip); } else if (fieldName.equals("ptype")) { prtype = fileItem.getString(); System.out.println(prtype); } else if (fieldName.equals("paddress1")) { pradd1 = fileItem.getString(); System.out.println(pradd1); } else if (fieldName.equals("paddress2")) { pradd2 = fileItem.getString(); System.out.println(pradd2); } else if (fieldName.equals("page")) { prage = fileItem.getString(); System.out.println(prage); } else if (fieldName.equals("pfarea")) { prfarea = fileItem.getString(); System.out.println(prfarea); } } else { String fieldName = fileItem.getFieldName(); if (fieldName.equals("photo1")) { //getting name of file prphoto1 = new File(fileItem.getName()).getName(); //get the extension of file by diving name into substring // String extension=prphoto.substring(prphoto.indexOf(".")+1,prphoto.length());; //rename file...concate name and extension //prphoto=prname+"."+extension; //System.out.println(prphoto); try { String fp = "/home/rushin/NetBeansProjects/The_Asset_Consultancy/web/images/property/"; // FOR UBUNTU add GETRESOURCE and GETPATH // String filePath = this.getServletContext().getResource("/images").getPath() + "\\"; fileItem.write(new File(fp + prphoto1)); } catch (Exception ex) { out.println(ex.toString()); } } //PHOTO 2 else if (fieldName.equals("photo2")) { prphoto2 = new File(fileItem.getName()).getName(); try { String fp = "/home/rushin/NetBeansProjects/The_Asset_Consultancy/web/images/property/"; fileItem.write(new File(fp + prphoto2)); } catch (Exception ex) { out.println(ex.toString()); } } //PHOTO 3 else if (fieldName.equals("photo3")) { prphoto3 = new File(fileItem.getName()).getName(); try { String fp = "/home/rushin/NetBeansProjects/The_Asset_Consultancy/web/images/property/"; fileItem.write(new File(fp + prphoto3)); } catch (Exception ex) { out.println(ex.toString()); } } //PHOTO 4 else if (fieldName.equals("photo4")) { prphoto4 = new File(fileItem.getName()).getName(); try { String fp = "/home/rushin/NetBeansProjects/The_Asset_Consultancy/web/images/property/"; fileItem.write(new File(fp + prphoto4)); } catch (Exception ex) { out.println(ex.toString()); } } } } SessionFactory sf = NewHibernateUtil.getSessionFactory(); Session ss = sf.openSession(); Transaction tr = ss.beginTransaction(); String op = ""; Criteria cr = ss.createCriteria(StateMaster.class); cr.add(Restrictions.eq("sId", Integer.parseInt(prstate))); ArrayList<StateMaster> ar = (ArrayList<StateMaster>) cr.list(); if (ar.isEmpty()) { } else { StateMaster sm = ar.get(0); op = sm.getSName(); } String city = ""; Criteria cr2 = ss.createCriteria(CityMaster.class); cr2.add(Restrictions.eq("cityId", Integer.parseInt(prcity))); ArrayList<CityMaster> ar2 = (ArrayList<CityMaster>) cr2.list(); System.out.println("----------" + ar2.size()); if (ar2.isEmpty()) { } else { city = ar2.get(0).getCityName(); System.out.println("-------" + city); } String area = ""; Criteria cr3 = ss.createCriteria(AreaMaster.class); cr3.add(Restrictions.eq("areaId", Integer.parseInt(prarea))); ArrayList<AreaMaster> ar3 = (ArrayList<AreaMaster>) cr3.list(); System.out.println("----------" + ar3.size()); if (ar3.isEmpty()) { } else { area = ar3.get(0).getAreaName(); System.out.println("-------" + area); } PropDetail pd = new PropDetail(); pd.setUId(ln); pd.setPAge(Integer.parseInt(prage)); pd.setPBhk(prbhk); pd.setPDescription(prdescrip.trim()); pd.setPAdd1(pradd1); pd.setPAdd2(pradd2); pd.setPPrice(Integer.parseInt(prprice)); pd.setPCity(city); pd.setPState(op); pd.setPArea(area); pd.setPName(prname); pd.setPType(prtype); pd.setPImg1(prphoto1); System.out.println(prphoto1); System.out.println(prphoto2); pd.setPImg2(prphoto2); pd.setPImg3(prphoto3); pd.setPImg4(prphoto4); pd.setPFloor(Integer.parseInt(prfarea)); ss.save(pd); tr.commit(); RequestDispatcher rd = request.getRequestDispatcher("property_search_1.jsp"); rd.forward(request, response); } } catch (HibernateException e) { out.println(e.getMessage()); } }
From source file:com.github.davidcarboni.encryptedfileupload.SizesTest.java
/** Checks, whether limiting the file size works. *//*from w w w. ja va 2s.co m*/ @Test public void testFileSizeLimit() 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" + "\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())); upload = new ServletFileUpload(new EncryptedFileItemFactory()); upload.setFileSizeMax(30); req = new MockHttpServletRequest(request.getBytes("US-ASCII"), CONTENT_TYPE); try { upload.parseRequest(req); fail("Expected exception."); } catch (FileUploadBase.FileSizeLimitExceededException e) { assertEquals(30, e.getPermittedSize()); } }
From source file:com.manning.cmis.theblend.servlets.AddServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response, Session session) throws ServletException, IOException, TheBlendException { // check for multipart content boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { // we expected content -> return to add page dispatch("add.jsp", "Add something new. The Blend.", request, response); }/*from w ww.j a v a 2s . com*/ Map<String, Object> properties = new HashMap<String, Object>(); File uploadedFile = null; String parentId = null; String parentPath = null; ObjectId newId = null; // process the request try { DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(50 * 1024 * 1024); @SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) { String name = item.getFieldName(); if (PARAM_PARENT_ID.equalsIgnoreCase(name)) { parentId = item.getString(); } else if (PARAM_PARENT_PATH.equalsIgnoreCase(name)) { parentPath = item.getString(); } else if (PARAM_TYPE_ID.equalsIgnoreCase(name)) { properties.put(PropertyIds.OBJECT_TYPE_ID, item.getString()); } } else { String name = item.getName(); if (name == null) { name = "file"; } else { // if the browser provided a path instead of a file name, // strip off the path int x = name.lastIndexOf('/'); if (x > -1) { name = name.substring(x + 1); } x = name.lastIndexOf('\\'); if (x > -1) { name = name.substring(x + 1); } name = name.trim(); if (name.length() == 0) { name = "file"; } } properties.put(PropertyIds.NAME, name); uploadedFile = File.createTempFile("blend", "tmp"); item.write(uploadedFile); } } } catch (Exception e) { throw new TheBlendException("Upload failed: " + e, e); } if (uploadedFile == null) { throw new TheBlendException("No content!"); } try { // prepare the content stream ContentStream contentStream = null; try { String objectTypeId = (String) properties.get(PropertyIds.OBJECT_TYPE_ID); contentStream = prepareContentStream(session, uploadedFile, objectTypeId, properties); } catch (Exception e) { throw new TheBlendException("Upload failed: " + e, e); } // find the parent folder // (we don't deal with unfiled documents here) Folder parent = null; if (parentId != null) { parent = CMISHelper.getFolder(session, parentId, CMISHelper.LIGHT_OPERATION_CONTEXT, "parent folder"); } else { parent = CMISHelper.getFolderByPath(session, parentPath, CMISHelper.LIGHT_OPERATION_CONTEXT, "parent folder"); } // create the document try { newId = session.createDocument(properties, parent, contentStream, null); } catch (CmisBaseException cbe) { throw new TheBlendException("Could not create document: " + cbe.getMessage(), cbe); } finally { try { contentStream.getStream().close(); } catch (IOException ioe) { // ignore } } } finally { // delete temp file uploadedFile.delete(); } // show the newly created document redirect(HTMLHelper.encodeUrlWithId(request, "show", newId.getId()), request, response); }
From source file:at.ac.tuwien.dsg.cloudlyra.utils.Uploader.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request//from w ww . jav 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 */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { InputStream dafFileContent = null; String dafName = ""; String dafType = ""; if (ServletFileUpload.isMultipartContent(request)) { try { List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : multiparts) { if (!item.isFormField()) { dafName = new File(item.getName()).getName(); dafFileContent = item.getInputStream(); } else { String fieldName = item.getFieldName(); String fieldValue = item.getString(); if (fieldName.equals("type")) { dafType = fieldValue; } // String log = "att name: " + fieldname + " - value: " + fieldvalue; // Logger.getLogger(Uploader.class.getName()).log(Level.INFO, log); } } //File uploaded successfully request.setAttribute("message", "File Uploaded Successfully"); } catch (Exception ex) { request.setAttribute("message", "File Upload Failed due to " + ex); } } else { request.setAttribute("message", "Sorry this Servlet only handles file upload request"); } if (!dafName.equals("")) { DafStore dafStore = new DafStore(); dafStore.insertDAF(dafName, dafType, dafFileContent); Logger.getLogger(Uploader.class.getName()).log(Level.INFO, dafName); } response.sendRedirect("daf.jsp"); }
From source file:com.mycom.products.mywebsite.backend.util.UploadHandler.java
@Override @ResponseBody/*from w w w . j a v a 2s. co m*/ @RequestMapping(method = RequestMethod.POST) protected final void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory()); PrintWriter writer = response.getWriter(); // checks if the request actually contains upload file if (!ServletFileUpload.isMultipartContent(request)) { // if not, we stop here writer.println("Error: Form must has enctype=multipart/form-data."); writer.flush(); return; } JSONObject json = new JSONObject(); SimpleDateFormat fmtYMD = new SimpleDateFormat("/" + "yyyyMMdd"); Date today = new Date(); String uploadPath = EntryPoint.getUploadPath() + "/"; try { List<FileItem> items = uploadHandler.parseRequest(request); if (items != null && items.size() > 0) { String saveDir = "", fileCategory = ""; for (FileItem item : items) { if (item.isFormField()) { fileCategory = item.getString(); } } saveDir = fileCategory + fmtYMD.format(today); // creates the directory if it does not exist File uploadDir = new File(uploadPath + saveDir); if (!uploadDir.exists()) { uploadDir.mkdirs(); } List<HashMap<String, String>> uploadFiles = new ArrayList<>(); for (FileItem item : items) { // processes only fields that are not form fields if (!item.isFormField()) { if (saveDir.length() == 0) { json.put("messageCode", "V1001"); json.put("messageParams", "File upload type"); json.put("status", HttpStatus.BAD_REQUEST); response.setContentType("application/json"); writer.write(json.toString()); writer.flush(); } String originalFileName = "", saveFileName = "", format = "", fileSize = ""; // set the default format to png when it is profileImage if (fileCategory.equals("profilePicture")) { format = ".png"; } // can't predict fileName and format would be included. // For instance, blob won't be. try { originalFileName = item.getName().substring(0, item.getName().lastIndexOf(".")); } catch (Exception e) { // Nothing to do. Skip } try { format = item.getName().substring(item.getName().lastIndexOf("."), item.getName().length()); } catch (Exception e) { // Nothing to do. Skip } fileSize = getReadableFileSize(item.getSize()); UUID uuid = UUID.randomUUID(); saveFileName = new File(uuid.toString() + format).getName(); String filePath = uploadPath + saveDir + "/" + saveFileName; if (fileCategory.equals("profilePicture")) { saveProfileImage(item, filePath); } // Time to save in DB LoggedUserBean loginUser; Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (principal instanceof LoggedUserBean) { loginUser = (LoggedUserBean) principal; } else { throw new SecurityException("Unauthorize File Upload process was attempted."); } StaticContentBean content = new StaticContentBean(); content.setFileName(originalFileName + format); content.setFilePath(filePath); content.setFileSize(fileSize); content.setFileType(FileType.valueOf(getFileType(format))); long lastInsertedId = contentService.insert(content, loginUser.getId()); // else .... other file types go here HashMap<String, String> fileItem = new HashMap<>(); fileItem.put("contentId", "" + lastInsertedId); uploadFiles.add(fileItem); } } json.put("uploadFiles", uploadFiles); json.put("status", HttpStatus.OK); response.setContentType("application/json"); writer.write(json.toString()); writer.flush(); } } catch (FileUploadException e) { throw new RuntimeException("File upload Error !", e); } catch (Exception e) { throw new RuntimeException("File upload Error !", e); } finally { writer.close(); } }
From source file:com.tasktop.c2c.server.tasks.web.service.AttachmentUploadController.java
@RequestMapping(value = "", method = RequestMethod.POST) public void upload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, TextHtmlContentExceptionWrapper { try {//www . j a v a 2 s . c o m FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<Attachment> attachments = new ArrayList<Attachment>(); Map<String, String> formValues = new HashMap<String, String>(); try { List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { if (item.isFormField()) { formValues.put(item.getFieldName(), item.getString()); } else { Attachment attachment = new Attachment(); attachment.setAttachmentData(readInputStream(item.getInputStream())); attachment.setFilename(item.getName()); attachment.setMimeType(item.getContentType()); attachments.add(attachment); } } } catch (FileUploadException e) { e.printStackTrace(); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); // FIXME better code return; } for (int i = 0; i < attachments.size(); i++) { String description = formValues .get(AttachmentUploadUtil.ATTACHMENT_DESCRIPTION_FORM_NAME_PREFIX + i); if (description == null) { throw new IllegalArgumentException( "Missing description " + i + 1 + " of " + attachments.size()); } attachments.get(0).setDescription(description); } TaskHandle taskHandle = getTaskHandle(formValues); UploadResult result = doUpload(response, attachments, taskHandle); response.setContentType("text/html"); response.getWriter() .write(jsonMapper.writeValueAsString(Collections.singletonMap("uploadResult", result))); } catch (Exception e) { throw new TextHtmlContentExceptionWrapper(e.getMessage(), e); } }
From source file:com.raissi.utils.CustomFileUploadFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { if (bypass) { filterChain.doFilter(request, response); return;/*from w w w.j a va2 s .co m*/ } HttpServletRequest httpServletRequest = (HttpServletRequest) request; boolean isMultipart = ServletFileUpload.isMultipartContent(httpServletRequest); if (isMultipart) { logger.debug("Parsing file upload request"); FileCleaningTracker fileCleaningTracker = FileCleanerCleanup .getFileCleaningTracker(request.getServletContext()); DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setFileCleaningTracker(fileCleaningTracker); if (thresholdSize != null) { diskFileItemFactory.setSizeThreshold(Integer.valueOf(thresholdSize)); } if (uploadDir != null) { diskFileItemFactory.setRepository(new File(uploadDir)); } ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); MultipartRequest multipartRequest = new MultipartRequest(httpServletRequest, servletFileUpload); logger.debug( "File upload request parsed succesfully, continuing with filter chain with a wrapped multipart request"); filterChain.doFilter(multipartRequest, response); } else { filterChain.doFilter(request, response); } }
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 {//w w w.j av a 2 s . co 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:Game_DataS.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w . j a v a 2s. 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, ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException { String datetime = null, field = null, visitors = null, hteamname = null, fteamname = null; Integer Ivisitors = null; response.setContentType("text/html;charset=UTF-8"); PrintWriter out = null; try { out = response.getWriter(); //First do the Proccesing of data . Data received from URL-POST method.. // // Check that we have a file upload request boolean isMultipartContent = ServletFileUpload.isMultipartContent(request); FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); //Parse the request to get file items. List<FileItem> fields = upload.parseRequest(request); // Process the uploaded file items Iterator<FileItem> it = fields.iterator(); //loop while (it.hasNext()) { FileItem fileItem = it.next(); boolean isFormField = fileItem.isFormField(); //Form Field if (isFormField) { String tmp = fileItem.getFieldName(); if (tmp.equals("datetime")) { datetime = fileItem.getString(); } else if (tmp.equals("field")) { field = fileItem.getString(); } else if (tmp.equals("visitors")) { visitors = fileItem.getString(); //cast to Integer Ivisitors = Integer.parseInt(visitors); } else if (tmp.equals("hteamname")) { hteamname = fileItem.getString(); } else if (tmp.equals("fteamname")) { fteamname = fileItem.getString(); } } //extracted all STATIC INFO, now go to txt;s else { //Call Method that parses txt and do the inserts TXT_FILES_PROCESS(fileItem.getString(), fileItem.getFieldName(), out, hteamname, fteamname, datetime, field, Ivisitors); } } //------------------------------------- out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>EuroLeague Page</title>"); out.println("</head>"); out.println("<body>"); out.println("<div><h1>Successfull Registry in DataBase !!</h1>"); out.println("<br></br>"); out.println("<br>"); out.println("<form name=\"myForm\" action=\"http://localhost:8080/Test_Project\">"); out.println("Home Page for further action ---> <input type=\"submit\" value=\"Home Page!\">"); out.println("</form>"); out.println("</div>"); out.println("</body>"); out.println("</html>"); } catch (FileUploadException FUE) { System.out.println("debugg " + FUE.getLocalizedMessage()); out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title> EuroLeague Page</title>"); out.println("</head>"); out.println("<body style = \"background-color: #720;\">"); out.println( "<div><h1> Sorry...Something went wrong with the TXT uploading.Please go to home page and try again uploading a valid txt !!</h1>"); out.println("<br> </br>"); out.println("<br>"); out.println("<form name=\"myForm\" action=\"http://localhost:8080/Test_Project\">"); out.println("Press here -> <input type = \"submit\" value = \"Home Page!\">"); out.println("</form>"); out.println("</div>"); out.println("</body>"); out.println("</html>"); } catch (IOException IOE) { out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title> EuroLeague Page</title>"); out.println("</head>"); out.println("<body style = \"background-color: #720;\">"); out.println( "<div><h1> Sorry...Something went wrong.Maybe a network error.Please go to home page !!</h1>"); out.println("<br> </br>"); out.println("<br>"); out.println("<form name=\"myForm\" action=\"http://localhost:8080/Test_Project\">"); out.println("Press here -> <input type = \"submit\" value = \"Home Page!\">"); out.println("</form>"); out.println("</div>"); out.println("</body>"); out.println("</html>"); } }