List of usage examples for org.apache.commons.fileupload FileUploadException printStackTrace
public void printStackTrace()
From source file:org.air.standard.web.presentation.FileUploadHandler.java
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response)//w w w . j a v a2s .co m */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { _logger.debug("FileUploadhandler fired!"); String initParameterFileType = getServletConfig().getInitParameter("fileType"); String ooExecPath = null; String ooSpreadsheetPath = null; File uploadedFile = null; try { InitialContext context = new InitialContext(); ooExecPath = request.getSession().getServletContext().getInitParameter("ooExecPath"); ooSpreadsheetPath = request.getSession().getServletContext().getInitParameter("ooSpreadsheetPath"); // ooExecPath = container.getInitParameter("ooExecPath"); // ooSpreadsheetPath = container.getInitParameter("ooSpreadsheetPath"); // ooExecPath = (String) context.lookup("java:comp/env/ooExecPath"); // ooSpreadsheetPath = (String) context // .lookup("java:comp/env/ooSpreadsheetPath"); boolean isMultipart = ServletFileUpload.isMultipartContent(request); // LoggerFactory.LogInfo("TEST File upload MANAGER", getClass()); if (isMultipart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { // Parse the request _logger.debug("Before parseRequest"); List items = upload.parseRequest(request); Iterator iterator = items.iterator(); BufferedInputStream buf = null; ServletOutputStream stream = null; while (iterator.hasNext()) { FileItem item = (FileItem) iterator.next(); if (!item.isFormField()) { String fileName = item.getName(); if (fileName.isEmpty()) throw new InvalidArgumentException("File to Upload ", "not empty"); _logger.debug("Parsed file file " + fileName); File uploadDirectory = new File(ooSpreadsheetPath); if (!uploadDirectory.exists()) { boolean status = uploadDirectory.mkdirs(); } if (!uploadDirectory.exists()) throw new ContentStandardException( "Problems accessing " + ooSpreadsheetPath + "server directory"); // just so that we do not have a name clash // we will prefix the current time stamp to the file // name. Date date = new Date(); String filePath = ooSpreadsheetPath + "/" + date.getTime() + fileName; uploadedFile = new File(filePath); /*if (!uploadedFile.canWrite() || !uploadedFile.canRead()) throw new ContentStandardException( "Problem with read or write access to files in " + ooSpreadsheetPath + " server directory"); */ /* * System.out.println(uploadedFile.getAbsolutePath()) * ; */ item.write(uploadedFile); _logger.debug("Wrote temp file " + uploadedFile.getAbsolutePath()); } } } catch (SecurityException se) { // can be thrown by canWrite, canRead, exists, mkdirs calls // if server is not configured with correct access rights _logger.error("Problem with access rights to " + ooSpreadsheetPath + " service directory. " + se.getMessage()); displayError(se, response); return; } catch (ContentStandardException cse) { _logger.error(cse.getMessage()); displayError(cse, response); return; } catch (InvalidArgumentException iae) { // EF: do not use displayError because it sets // SC_INTERNAL_SERVLET_ERROR and this is not the case! _logger.error("FileUploadException: " + iae.getMessage()); ReturnStatus<Exception> status = new ReturnStatus<Exception>("failed"); status.setPayload(null); status.appendToErrors(iae.getMessage()); ObjectMapper mapper = new ObjectMapper(); String statusJson = mapper.writeValueAsString(status); // serialize the status object. response.setContentType("application/json"); response.getOutputStream().print(statusJson); return; } catch (FileUploadException e) { e.printStackTrace(); _logger.error("FileUpload Exception: " + e.getMessage()); displayError(e, response); return; } catch (Exception e) { _logger.error("Problem parsing request/creating temp file : " + e.getMessage()); e.printStackTrace(); displayError(e, response); return; } } /* System.out.println("CONFIG FILE:::" + ooExecPath); */ } catch (NamingException ex) { /* System.out.println("exception in jndi lookup"); */ _logger.error("NamingException in jndi lookup" + ex.getMessage()); displayError(ex, response); return; } ObjectMapper mapper = new ObjectMapper(); String statusJson = null; try { ReturnStatus<String> status = new ReturnStatus<String>("success"); //TODO Shiva how to get the bean factory here so that we can remove (new WebUserInformation()) and call the bean instead? String sessionKey = (new WebUserInformation()).getSessionKey(); // clear out existing staging tables for this session key. LoaderTablesDAO dao = new LoaderTablesDAO(); dao.loaderClear(sessionKey); // tell DB what kind of upload we are doing - full or partial. PublicationDAO publicationDAO = new PublicationDAO(); if (initParameterFileType.equalsIgnoreCase("full")) { publicationDAO.importPublication(sessionKey); } else if (initParameterFileType.equalsIgnoreCase("partial")) { publicationDAO.partialImportPublication(sessionKey); } _logger.debug("About to call importFromFile for " + uploadedFile.getAbsolutePath()); OpenOfficeImporter openOfficeImporter = new OpenOfficeImporter(); openOfficeImporter.importFromFile(ooExecPath, uploadedFile.getAbsolutePath(), sessionKey, status); _logger.debug("Finished importFromFile for" + uploadedFile.getAbsolutePath() + " status is " + status.getStatus()); statusJson = mapper.writeValueAsString(status); // serialize the status object. response.setContentType("application/json"); response.getOutputStream().print(statusJson); _logger.debug("Sent json response "); } catch (Exception exp) { _logger.error("Exception after temp file created " + exp.getMessage()); exp.printStackTrace(); displayError(exp, response); } }
From source file:org.carcv.web.servlet.UploadServlet.java
/** * @param request the HttpServletRequest * @param response the HttpServletResponse * @throws IOException//from w w w . j a v a2s . co m */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException { Path batchDir = storageBean.createBatchDirectory(); ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory()); List<FileItem> items; try { items = servletFileUpload.parseRequest(request); } catch (FileUploadException e) { response.sendError(500, e.getMessage()); e.printStackTrace(); return; } for (FileItem item : items) { if (item.isFormField()) { // ignore regular form fields } else { // process files String fileName = FilenameUtils.getName(item.getName()); InputStream fileContent = item.getInputStream(); storageBean.storeToDirectory(fileContent, fileName, batchDir); } } Path infoProps = Paths.get(batchDir.toString(), DirectoryLoader.infoFileName); if (!Files.exists(infoProps)) { // if the info file wasn't uploaded, generate a random demo one Properties demo = Main.createDemoProperties(); Path props = Paths.get(batchDir.toString(), DirectoryLoader.infoFileName); demo.store(Files.newOutputStream(props), "Demo properties"); } }
From source file:org.cerberus.refactor.importFile.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (ServletFileUpload.isMultipartContent(request)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try {//from ww w. jav a2 s . c o m List items = upload.parseRequest(request); Iterator iterator = items.iterator(); File uploadedFile = null; String test = ""; String testcase = ""; String step = ""; String load = ""; while (iterator.hasNext()) { FileItem item = (FileItem) iterator.next(); if (!item.isFormField()) { String fileName = item.getName(); String root = getServletContext().getRealPath("/"); File pathFile = new File(root + "/cerberusFiles"); if (!pathFile.exists()) { //boolean status = pathFile.mkdirs(); pathFile.mkdirs(); } uploadedFile = new File(pathFile + "/" + fileName); System.out.println(uploadedFile.getAbsolutePath()); item.write(uploadedFile); } else { String name = item.getFieldName(); if (name.equals("Test")) { test = item.getString(); } else if (name.equals("Testcase")) { testcase = item.getString(); } else if (name.equals("Step")) { step = item.getString(); } else if (name.equals("Load")) { load = item.getString(); } } } response.sendRedirect("ImportHTML.jsp?Test=" + test + "&Testcase=" + testcase + "&Step=" + step + "&Load=" + load + "&FilePath=" + uploadedFile.getAbsolutePath()); } catch (FileUploadException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }
From source file:org.cerberus.servlet.crud.countryenvironment.CreateApplicationObject.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// w ww . j a v a2 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 * @throws CerberusException * @throws JSONException */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, CerberusException, JSONException { JSONObject jsonResponse = new JSONObject(); Answer ans = new Answer(); MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED); msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", "")); ans.setResultMessage(msg); PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS); String charset = request.getCharacterEncoding(); response.setContentType("application/json"); // Calling Servlet Transversal Util. ServletUtil.servletStart(request); Map<String, String> fileData = new HashMap<String, String>(); FileItem file = null; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> fields = upload.parseRequest(request); Iterator<FileItem> it = fields.iterator(); if (!it.hasNext()) { return; } while (it.hasNext()) { FileItem fileItem = it.next(); boolean isFormField = fileItem.isFormField(); if (isFormField) { fileData.put(fileItem.getFieldName(), ParameterParserUtil .parseStringParamAndDecode(fileItem.getString("UTF-8"), null, charset)); } else { file = fileItem; } } } catch (FileUploadException e) { e.printStackTrace(); } /** * Parsing and securing all required parameters. */ // Parameter that are already controled by GUI (no need to decode) --> We SECURE them // Parameter that needs to be secured --> We SECURE+DECODE them String application = fileData.get("application"); String object = fileData.get("object"); String value = fileData.get("value"); String usrcreated = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getRemoteUser(), "", charset); String datecreated = new Timestamp(new java.util.Date().getTime()).toString(); String usrmodif = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getRemoteUser(), "", charset); String datemodif = new Timestamp(new java.util.Date().getTime()).toString(); // Parameter that we cannot secure as we need the html --> We DECODE them /** * Checking all constrains before calling the services. */ if (StringUtil.isNullOrEmpty(application)) { msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED); msg.setDescription(msg.getDescription().replace("%ITEM%", "ApplicationObject") .replace("%OPERATION%", "Create").replace("%REASON%", "Application name is missing!")); ans.setResultMessage(msg); } else if (StringUtil.isNullOrEmpty(object)) { msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED); msg.setDescription(msg.getDescription().replace("%ITEM%", "ApplicationObject") .replace("%OPERATION%", "Create").replace("%REASON%", "Object name is missing!")); ans.setResultMessage(msg); } else { /** * All data seems cleans so we can call the services. */ ApplicationContext appContext = WebApplicationContextUtils .getWebApplicationContext(this.getServletContext()); IApplicationObjectService applicationobjectService = appContext .getBean(IApplicationObjectService.class); IFactoryApplicationObject factoryApplicationobject = appContext .getBean(IFactoryApplicationObject.class); String fileName = ""; if (file != null) { fileName = file.getName(); } ApplicationObject applicationData = factoryApplicationobject.create(-1, application, object, value, fileName, usrcreated, datecreated, usrmodif, datemodif); ans = applicationobjectService.create(applicationData); if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) { /** * Object created. Adding Log entry. */ ILogEventService logEventService = appContext.getBean(LogEventService.class); logEventService.createPrivateCalls("/CreateApplicationObject", "CREATE", "Create Application Object: ['" + application + "','" + object + "']", request); if (file != null) { AnswerItem an = applicationobjectService.readByKey(application, object); if (an.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && an.getItem() != null) { applicationData = (ApplicationObject) an.getItem(); ans = applicationobjectService.uploadFile(applicationData.getID(), file); if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) { } } } } } /** * Formating and returning the json result. */ jsonResponse.put("messageType", ans.getResultMessage().getMessage().getCodeString()); jsonResponse.put("message", ans.getResultMessage().getDescription()); response.getWriter().print(jsonResponse); response.getWriter().flush(); }
From source file:org.cerberus.servlet.crud.countryenvironment.UpdateApplicationObject.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w ww. 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 */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, CerberusException, JSONException { JSONObject jsonResponse = new JSONObject(); ApplicationContext appContext = WebApplicationContextUtils .getWebApplicationContext(this.getServletContext()); Answer ans = new Answer(); MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED); msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", "")); ans.setResultMessage(msg); String charset = request.getCharacterEncoding(); response.setContentType("application/json"); // Calling Servlet Transversal Util. ServletUtil.servletStart(request); Map<String, String> fileData = new HashMap<String, String>(); FileItem file = null; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> fields = upload.parseRequest(request); Iterator<FileItem> it = fields.iterator(); if (!it.hasNext()) { return; } while (it.hasNext()) { FileItem fileItem = it.next(); boolean isFormField = fileItem.isFormField(); if (isFormField) { fileData.put(fileItem.getFieldName(), ParameterParserUtil .parseStringParamAndDecode(fileItem.getString("UTF-8"), null, charset)); } else { file = fileItem; } } } catch (FileUploadException e) { e.printStackTrace(); } /** * Parsing and securing all required parameters. */ // Parameter that are already controled by GUI (no need to decode) --> We SECURE them // Parameter that needs to be secured --> We SECURE+DECODE them String application = fileData.get("application"); String object = fileData.get("object"); String value = fileData.get("value"); String usrmodif = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getRemoteUser(), "", charset); String datemodif = new Timestamp(new java.util.Date().getTime()).toString(); // Parameter that we cannot secure as we need the html --> We DECODE them // Getting list of application from JSON Call // Prepare the final answer. MessageEvent msg1 = new MessageEvent(MessageEventEnum.GENERIC_OK); Answer finalAnswer = new Answer(msg1); /** * Checking all constrains before calling the services. */ if (StringUtil.isNullOrEmpty(application)) { msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED); msg.setDescription( msg.getDescription().replace("%ITEM%", "ApplicationObject").replace("%OPERATION%", "Update") .replace("%REASON%", "Application name (applicationobject) is missing.")); ans.setResultMessage(msg); } else if (StringUtil.isNullOrEmpty(object)) { msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED); msg.setDescription( msg.getDescription().replace("%ITEM%", "ApplicationObject").replace("%OPERATION%", "Update") .replace("%REASON%", "Object name (applicationobject) is missing.")); ans.setResultMessage(msg); } else { /** * All data seems cleans so we can call the services. */ IApplicationObjectService applicationObjectService = appContext .getBean(IApplicationObjectService.class); AnswerItem resp = applicationObjectService.readByKey(application, object); if (!(resp.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && resp.getItem() != null)) { /** * Object could not be found. We stop here and report the error. */ finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) resp); } else { /** * The service was able to perform the query and confirm the * object exist, then we can update it. */ ApplicationObject applicationData = (ApplicationObject) resp.getItem(); String fileName = applicationData.getScreenShotFileName(); if (file != null) { ans = applicationObjectService.uploadFile(applicationData.getID(), file); if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) { fileName = file.getName(); } } applicationData.setValue(value); applicationData.setScreenShotFileName(fileName); applicationData.setUsrModif(usrmodif); applicationData.setDateModif(datemodif); ans = applicationObjectService.update(applicationData); finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans); if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) { /** * Update was succesfull. Adding Log entry. */ ILogEventService logEventService = appContext.getBean(LogEventService.class); logEventService.createPrivateCalls("/UpdateApplication", "UPDATE", "Updated Application : ['" + application + "']", request); } finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans); } } /** * Formating and returning the json result. */ jsonResponse.put("messageType", finalAnswer.getResultMessage().getMessage().getCodeString()); jsonResponse.put("message", finalAnswer.getResultMessage().getDescription()); response.getWriter().print(jsonResponse); response.getWriter().flush(); }
From source file:org.cerberus.servlet.crud.test.importFile.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (ServletFileUpload.isMultipartContent(request)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try {//from w w w . j a va 2 s . c o m List items = upload.parseRequest(request); Iterator iterator = items.iterator(); File uploadedFile = null; String test = ""; String testcase = ""; String step = ""; String load = ""; while (iterator.hasNext()) { FileItem item = (FileItem) iterator.next(); if (!item.isFormField()) { String fileName = item.getName(); String root = getServletContext().getRealPath("/"); File pathFile = new File(root + "/cerberusFiles"); if (!pathFile.exists()) { //boolean status = pathFile.mkdirs(); pathFile.mkdirs(); } uploadedFile = new File(pathFile + "/" + fileName); LOG.debug(uploadedFile.getAbsolutePath()); item.write(uploadedFile); } else { String name = item.getFieldName(); if (name.equals("Test")) { test = item.getString(); } else if (name.equals("Testcase")) { testcase = item.getString(); } else if (name.equals("Step")) { step = item.getString(); } else if (name.equals("Load")) { load = item.getString(); } } } response.sendRedirect("ImportHTML.jsp?Test=" + test + "&Testcase=" + testcase + "&Step=" + step + "&Load=" + load + "&FilePath=" + uploadedFile.getAbsolutePath()); } catch (FileUploadException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }
From source file:org.cerberus.servlet.crud.test.ImportTestCaseFromJson.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w. j a va 2 s . 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 */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String test = ""; String testcase = ""; JSONObject jo = null; FileItem item = null; if (ServletFileUpload.isMultipartContent(request)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List items = upload.parseRequest(request); Iterator iterator = items.iterator(); while (iterator.hasNext()) { item = (FileItem) iterator.next(); if (item.isFormField()) { String name = item.getFieldName(); if (name.equals("test")) { test = item.getString("UTF-8"); } if (name.equals("testcase")) { testcase = item.getString("UTF-8"); } } else { InputStream inputStream = item.getInputStream(); BufferedReader streamReader = new BufferedReader( new InputStreamReader(inputStream, "UTF-8")); StringBuilder responseStrBuilder = new StringBuilder(); String inputStr; while ((inputStr = streamReader.readLine()) != null) { responseStrBuilder.append(inputStr); } inputStream.close(); streamReader.close(); jo = new JSONObject(responseStrBuilder.toString()); } } ApplicationContext appContext = WebApplicationContextUtils .getWebApplicationContext(this.getServletContext()); ITestCaseService tcService = appContext.getBean(ITestCaseService.class); TestCase tcInfo = new TestCase(); tcInfo.setTest(test); tcInfo.setTestCase(testcase); tcInfo.setOrigine(jo.getString("origin") == null ? "" : jo.getString("origin")); tcInfo.setImplementer(jo.getString("implementer") == null ? "123TOTO" : "1234TOTO"); tcInfo.setBehaviorOrValueExpected(jo.getString("description") == null ? "1293TOTO" : "12394TOTO"); tcService.updateTestCaseInformation(tcInfo); response.sendRedirect("TestCase.jsp"); } catch (FileUploadException e) { e.printStackTrace(); } catch (JSONException ex) { Logger.getLogger(ImportTestCaseFromJson.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception e) { e.printStackTrace(); } } }
From source file:org.cerberus.servlet.testCase.ImportTestCaseFromJson.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./* w w w .j ava 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 */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String test = ""; String testcase = ""; JSONObject jo = null; FileItem item = null; if (ServletFileUpload.isMultipartContent(request)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List items = upload.parseRequest(request); Iterator iterator = items.iterator(); while (iterator.hasNext()) { item = (FileItem) iterator.next(); if (item.isFormField()) { String name = item.getFieldName(); if (name.equals("test")) { test = item.getString("UTF-8"); System.out.println(test); } if (name.equals("testcase")) { testcase = item.getString("UTF-8"); System.out.println(testcase); } } else { InputStream inputStream = item.getInputStream(); BufferedReader streamReader = new BufferedReader( new InputStreamReader(inputStream, "UTF-8")); StringBuilder responseStrBuilder = new StringBuilder(); String inputStr; while ((inputStr = streamReader.readLine()) != null) { responseStrBuilder.append(inputStr); } inputStream.close(); streamReader.close(); jo = new JSONObject(responseStrBuilder.toString()); } } ApplicationContext appContext = WebApplicationContextUtils .getWebApplicationContext(this.getServletContext()); ITestCaseService tcService = appContext.getBean(ITestCaseService.class); TestCase tcInfo = new TestCase(); tcInfo.setTest(test); tcInfo.setTestCase(testcase); tcInfo.setOrigin(jo.getString("origin") == null ? "" : jo.getString("origin")); tcInfo.setImplementer(jo.getString("implementer") == null ? "123TOTO" : "1234TOTO"); tcInfo.setDescription(jo.getString("description") == null ? "1293TOTO" : "12394TOTO"); tcService.updateTestCaseInformation(tcInfo); response.sendRedirect("TestCase.jsp"); } catch (FileUploadException e) { e.printStackTrace(); } catch (JSONException ex) { Logger.getLogger(ImportTestCaseFromJson.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception e) { e.printStackTrace(); } } }
From source file:org.codelabor.system.file.web.servlet.FileUploadServlet.java
/** * ?? .</br> ? ? ?? ? , (: ?) ? mapId . ? * ?? ? repositoryType , ?/* w ww .jav a 2s .c o m*/ * org.codelabor.system.file.RepositoryType . * * @param request * * @param response * ? * @throws Exception * */ @SuppressWarnings("unchecked") protected void upload(HttpServletRequest request, HttpServletResponse response) throws Exception { WebApplicationContext ctx = WebApplicationContextUtils .getRequiredWebApplicationContext(this.getServletContext()); FileManager fileManager = (FileManager) ctx.getBean("fileManager"); boolean isMultipart = ServletFileUpload.isMultipartContent(request); Map<String, Object> paramMap = RequestUtils.getParameterMap(request); logger.debug("paramMap: {}", paramMap.toString()); String mapId = (String) paramMap.get("mapId"); RepositoryType acceptedRepositoryType = repositoryType; String requestedRepositoryType = (String) paramMap.get("repositoryType"); if (StringUtils.isNotEmpty(requestedRepositoryType)) { acceptedRepositoryType = RepositoryType.valueOf(requestedRepositoryType); } if (isMultipart) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(sizeThreshold); factory.setRepository(new File(tempRepositoryPath)); factory.setFileCleaningTracker(FileCleanerCleanup.getFileCleaningTracker(this.getServletContext())); ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(fileSizeMax); upload.setSizeMax(requestSizeMax); upload.setHeaderEncoding(characterEncoding); upload.setProgressListener(new FileUploadProgressListener()); try { List<FileItem> fileItemList = upload.parseRequest(request); Iterator<FileItem> iter = fileItemList.iterator(); while (iter.hasNext()) { FileItem fileItem = iter.next(); logger.debug("fileItem: {}", fileItem.toString()); FileDTO fileDTO = null; if (fileItem.isFormField()) { paramMap.put(fileItem.getFieldName(), fileItem.getString(characterEncoding)); } else { if (fileItem.getName() == null || fileItem.getName().length() == 0) continue; // set DTO fileDTO = new FileDTO(); fileDTO.setMapId(mapId); fileDTO.setRealFilename(FilenameUtils.getName(fileItem.getName())); if (acceptedRepositoryType == RepositoryType.FILE_SYSTEM) { fileDTO.setUniqueFilename(getUniqueFilename()); } fileDTO.setContentType(fileItem.getContentType()); fileDTO.setRepositoryPath(realRepositoryPath); logger.debug("fileDTO: {}", fileDTO.toString()); UploadUtils.processFile(acceptedRepositoryType, fileItem.getInputStream(), fileDTO); } if (fileDTO != null) fileManager.insertFile(fileDTO); } } catch (FileUploadException e) { e.printStackTrace(); logger.error(e.getMessage()); throw e; } catch (Exception e) { e.printStackTrace(); logger.error(e.getMessage()); throw e; } } else { paramMap = RequestUtils.getParameterMap(request); } try { processParameters(paramMap); } catch (Exception e) { e.printStackTrace(); logger.error(e.getMessage()); throw e; } dispatch(request, response, forwardPathUpload); }
From source file:org.codelabor.system.file.web.servlet.FileUploadStreamServlet.java
@Override protected void upload(HttpServletRequest request, HttpServletResponse response) throws Exception { WebApplicationContext ctx = WebApplicationContextUtils .getRequiredWebApplicationContext(this.getServletContext()); FileManager fileManager = (FileManager) ctx.getBean("fileManager"); boolean isMultipart = ServletFileUpload.isMultipartContent(request); Map<String, Object> paramMap = RequestUtils.getParameterMap(request); if (logger.isDebugEnabled()) { logger.debug(paramMap.toString()); }/*w w w. j a v a 2 s .c om*/ String mapId = (String) paramMap.get("mapId"); RepositoryType acceptedRepositoryType = repositoryType; String requestedRepositoryType = (String) paramMap.get("repositoryType"); if (StringUtils.isNotEmpty(requestedRepositoryType)) { acceptedRepositoryType = RepositoryType.valueOf(requestedRepositoryType); } if (isMultipart) { ServletFileUpload upload = new ServletFileUpload(); upload.setFileSizeMax(fileSizeMax); upload.setSizeMax(requestSizeMax); upload.setHeaderEncoding(characterEncoding); upload.setProgressListener(new FileUploadProgressListener()); try { FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream fileItemSteam = iter.next(); if (logger.isDebugEnabled()) { logger.debug(fileItemSteam.toString()); } FileDTO fileDTO = null; if (fileItemSteam.isFormField()) { paramMap.put(fileItemSteam.getFieldName(), Streams.asString(fileItemSteam.openStream(), characterEncoding)); } else { if (fileItemSteam.getName() == null || fileItemSteam.getName().length() == 0) continue; // set DTO fileDTO = new FileDTO(); fileDTO.setMapId(mapId); fileDTO.setRealFilename(FilenameUtils.getName(fileItemSteam.getName())); if (acceptedRepositoryType == RepositoryType.FILE_SYSTEM) { fileDTO.setUniqueFilename(getUniqueFilename()); } fileDTO.setContentType(fileItemSteam.getContentType()); fileDTO.setRepositoryPath(realRepositoryPath); if (logger.isDebugEnabled()) { logger.debug(fileDTO.toString()); } UploadUtils.processFile(acceptedRepositoryType, fileItemSteam.openStream(), fileDTO); } if (fileDTO != null) fileManager.insertFile(fileDTO); } } catch (FileUploadException e) { e.printStackTrace(); logger.error(e.getMessage()); } catch (Exception e) { e.printStackTrace(); logger.error(e.getMessage()); } } else { paramMap = RequestUtils.getParameterMap(request); } try { processParameters(paramMap); } catch (Exception e) { e.printStackTrace(); logger.error(e.getMessage()); } dispatch(request, response, forwardPathUpload); }