List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload setHeaderEncoding
public void setHeaderEncoding(String encoding)
From source file:com.jl.common.ConnectorServlet.java
/** * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br /> * /* w ww. ja v a 2 s . com*/ * The servlet accepts commands sent in the following format:<br /> * <code>connector?Command=<FileUpload>&Type=<ResourceType>&CurrentFolder=<FolderPath></code> * with the file in the <code>POST</code> body.<br /> * <br> * It stores an uploaded file (renames a file if another exists with the * same name) and then returns the JavaScript callback. */ @SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.debug("Entering Connector#doPost"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); String commandStr = request.getParameter("Command"); String typeStr = request.getParameter("Type"); String currentFolderStr = request.getParameter("CurrentFolder"); logger.debug("Parameter Command: {}", commandStr); logger.debug("Parameter Type: {}", typeStr); logger.debug("Parameter CurrentFolder: {}", currentFolderStr); UploadResponse ur; // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr' // are empty if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) { commandStr = "QuickUpload"; currentFolderStr = "/"; } if (!RequestCycleHandler.isEnabledForFileUpload(request)) ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null, Messages.NOT_AUTHORIZED_FOR_UPLOAD); else if (!CommandHandler.isValidForPost(commandStr)) ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND); else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr)) ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE); else if (!UtilsFile.isValidPath(currentFolderStr)) ur = UploadResponse.UR_INVALID_CURRENT_FOLDER; else { ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr); String typePath = UtilsFile.constructServerSidePath(request, resourceType); String typeDirPath = getServletContext().getRealPath(typePath); File typeDir = new File(typeDirPath); UtilsFile.checkDirAndCreate(typeDir); File currentDir = new File(typeDir, currentFolderStr); if (!currentDir.exists()) ur = UploadResponse.UR_INVALID_CURRENT_FOLDER; else { String newFilename = null; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8");// try { List<FileItem> items = upload.parseRequest(request); // We upload only one file at the same time FileItem uplFile = items.get(0); String rawName = UtilsFile.sanitizeFileName(uplFile.getName()); String filename = FilenameUtils.getName(rawName); String baseName = FilenameUtils.removeExtension(filename); String extension = FilenameUtils.getExtension(filename); filename = UUID.randomUUID().toString() + "." + extension;// // if (!ExtensionsHandler.isAllowed(resourceType, extension)) { ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); } // else if (uplFile.getSize() > 50 * 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:kreidos.diamond.web.action.console.NewDocumentAction.java
@SuppressWarnings("rawtypes") public WebView execute(HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); User loggedInUser = (User) session.getAttribute(HTTPConstants.SESSION_KRYSTAL); String classId = request.getParameter("classid") != null ? request.getParameter("classid") : "0"; if (request.getMethod().equalsIgnoreCase("POST")) { try {//from w w w . ja v a 2 s. c om String userName = loggedInUser.getUserName(); String tempFilePath = System.getProperty("java.io.tmpdir"); if (!(tempFilePath.endsWith("/") || tempFilePath.endsWith("\\"))) { tempFilePath += System.getProperty("file.separator"); } //variables String fileName = "", comments = ""; File file = null; // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding(HTTPConstants.CHARACTER_ENCODING); //Create a file upload progress listener FileUploadProgressListener listener = new FileUploadProgressListener(); upload.setProgressListener(listener); //put the listener in session session.setAttribute("LISTENER", listener); session.setAttribute("UPLOAD_ERROR", null); session.setAttribute("UPLOAD_PERCENT_COMPLETE", new Long(0)); DocumentClass documentClass = null; Hashtable<String, String> indexRecord = new Hashtable<String, String>(); String name = ""; String value = ""; List listItems = upload.parseRequest((HttpServletRequest) request); Iterator iter = listItems.iterator(); FileItem fileItem = null; while (iter.hasNext()) { fileItem = (FileItem) iter.next(); if (fileItem.isFormField()) { name = fileItem.getFieldName(); value = fileItem.getString(HTTPConstants.CHARACTER_ENCODING); if (name.equals("classid")) { classId = value; } if (name.equals("txtNote")) { comments = value; } } else { try { fileName = fileItem.getName(); file = new File(fileName); fileName = file.getName(); file = new File(tempFilePath + fileName); fileItem.write(file); } catch (Exception ex) { session.setAttribute("UPLOAD_ERROR", ex.getLocalizedMessage()); return null; } } } //if if (file.length() <= 0) { //code for checking minimum size of file session.setAttribute("UPLOAD_ERROR", "Zero length document"); return null; } documentClass = DocumentClassDAO.getInstance().readDocumentClassById(Integer.parseInt(classId)); if (documentClass == null) { session.setAttribute("UPLOAD_ERROR", "Invalid document class"); return null; } AccessControlManager aclManager = new AccessControlManager(); ACL acl = aclManager.getACL(documentClass, loggedInUser); if (!acl.canCreate()) { session.setAttribute("UPLOAD_ERROR", "Access Denied"); return null; } String indexValue = ""; String indexName = ""; session.setAttribute("UPLOAD_PERCENT_COMPLETE", new Long(50)); for (IndexDefinition indexDefinition : documentClass.getIndexDefinitions()) { indexName = indexDefinition.getIndexColumnName(); Iterator iter1 = listItems.iterator(); while (iter1.hasNext()) { FileItem item1 = (FileItem) iter1.next(); if (item1.isFormField()) { name = item1.getFieldName(); value = item1.getString(HTTPConstants.CHARACTER_ENCODING); if (name.equals(indexName)) { indexValue = value; String errorMessage = ""; if (indexValue != null) { if (indexDefinition.isMandatory()) { if (indexValue.trim().length() <= 0) { errorMessage = "Invalid input for " + indexDefinition.getIndexDisplayName(); session.setAttribute("UPLOAD_ERROR", errorMessage); return null; } } 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(); session.setAttribute("UPLOAD_ERROR", errorMessage); return null; } } } 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(); session.setAttribute("UPLOAD_ERROR", errorMessage); return null; } } } if (indexValue.trim().length() > indexDefinition.getIndexMaxLength()) { //code for checking index field length errorMessage = "Document index size exceeded for " + "Index Name : " + indexDefinition.getIndexDisplayName() + " [ " + "Index Length : " + indexDefinition.getIndexMaxLength() + " , " + "Actual Length : " + indexValue.length() + " ]"; session.setAttribute("UPLOAD_ERROR", errorMessage); return null; } } indexRecord.put(indexName, indexValue); } } } //while iter } //while indexCfgList session.setAttribute("UPLOAD_PERCENT_COMPLETE", new Long(70)); DocumentRevision documentRevision = new DocumentRevision(); documentRevision.setClassId(documentClass.getClassId()); documentRevision.setDocumentId(0); documentRevision.setRevisionId("1.0"); documentRevision.setDocumentFile(file); documentRevision.setUserName(loggedInUser.getUserName()); documentRevision.setIndexRecord(indexRecord); documentRevision.setComments(comments); DocumentManager documentManager = new DocumentManager(); documentManager.storeDocument(documentRevision, documentClass); //Log the entry to audit logs AuditLogManager.log(new AuditLogRecord(documentRevision.getDocumentId(), AuditLogRecord.OBJECT_DOCUMENT, AuditLogRecord.ACTION_CREATED, userName, request.getRemoteAddr(), AuditLogRecord.LEVEL_INFO, "", "Document created")); session.setAttribute("UPLOAD_PERCENT_COMPLETE", new Long(100)); } catch (Exception e) { e.printStackTrace(System.out); } return null; } else { try { ArrayList<DocumentClass> availableDocumentClasses = DocumentClassDAO.getInstance() .readDocumentClasses(" ACTIVE = 'Y'"); ArrayList<DocumentClass> documentClasses = new ArrayList<DocumentClass>(); AccessControlManager aclManager = new AccessControlManager(); for (DocumentClass documentClass : availableDocumentClasses) { ACL acl = aclManager.getACL(documentClass, loggedInUser); if (acl.canCreate()) { documentClasses.add(documentClass); } } int documentClassId = 0; try { documentClassId = Integer.parseInt(classId); } catch (Exception ex) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid input"); return (new NewDocumentView(request, response)); } if (documentClassId > 0) { DocumentClass selectedDocumentClass = DocumentClassDAO.getInstance() .readDocumentClassById(documentClassId); request.setAttribute("DOCUMENTCLASS", selectedDocumentClass); } request.setAttribute("CLASSID", documentClassId); request.setAttribute("CLASSLIST", documentClasses); } catch (Exception ex) { ex.printStackTrace(); } } return (new NewDocumentView(request, response)); }
From source file:com.exedio.cope.live.Bar.java
void doRequest(final HttpServletRequest request, final HttpSession httpSession, final HttpServletResponse response, final Anchor anchor) throws IOException { if (!Cop.isPost(request)) { try {//from w w w . j a va2 s . co m startTransaction("redirectHome"); anchor.redirectHome(request, response); model.commit(); } finally { model.rollbackIfNotCommitted(); } return; } final String referer; if (isMultipartContent(request)) { final HashMap<String, String> fields = new HashMap<String, String>(); final HashMap<String, FileItem> files = new HashMap<String, FileItem>(); final FileItemFactory factory = new DiskFileItemFactory(); final ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding(UTF_8.name()); try { for (final Iterator<?> i = upload.parseRequest(request).iterator(); i.hasNext();) { final FileItem item = (FileItem) i.next(); if (item.isFormField()) fields.put(item.getFieldName(), item.getString(UTF_8.name())); else files.put(item.getFieldName(), item); } } catch (final FileUploadException e) { throw new RuntimeException(e); } final String featureID = fields.get(FEATURE); if (featureID == null) throw new NullPointerException(); final Media feature = (Media) model.getFeature(featureID); if (feature == null) throw new NullPointerException(featureID); final String itemID = fields.get(ITEM); if (itemID == null) throw new NullPointerException(); final FileItem file = files.get(FILE); try { startTransaction("publishFile(" + featureID + ',' + itemID + ')'); final Item item = model.getItem(itemID); if (fields.get(PUBLISH_NOW) != null) { for (final History history : History.getHistories(item.getCopeType())) { final History.Event event = history.createEvent(item, anchor.getHistoryAuthor(), false); event.createFeature(feature, feature.getName(), feature.isNull(item) ? null : ("file type=" + feature.getContentType(item) + " size=" + feature.getLength(item)), "file name=" + file.getName() + " type=" + file.getContentType() + " size=" + file.getSize()); } // TODO use more efficient setter with File or byte[] feature.set(item, file.getInputStream(), file.getContentType()); } else { anchor.modify(file, feature, item); } model.commit(); } catch (final NoSuchIDException e) { throw new RuntimeException(e); } finally { model.rollbackIfNotCommitted(); } referer = fields.get(REFERER); } else // isMultipartContent { if (request.getParameter(BORDERS_ON) != null || request.getParameter(BORDERS_ON_IMAGE) != null) { anchor.borders = true; } else if (request.getParameter(BORDERS_OFF) != null || request.getParameter(BORDERS_OFF_IMAGE) != null) { anchor.borders = false; } else if (request.getParameter(CLOSE) != null || request.getParameter(CLOSE_IMAGE) != null) { httpSession.removeAttribute(LoginServlet.ANCHOR); } else if (request.getParameter(SWITCH_TARGET) != null) { anchor.setTarget(servlet.getTarget(request.getParameter(SWITCH_TARGET))); } else if (request.getParameter(SAVE_TARGET) != null) { try { startTransaction("saveTarget"); anchor.getTarget().save(anchor); model.commit(); } finally { model.rollbackIfNotCommitted(); } anchor.notifyPublishedAll(); } else { final String featureID = request.getParameter(FEATURE); if (featureID == null) throw new NullPointerException(); final Feature featureO = model.getFeature(featureID); if (featureO == null) throw new NullPointerException(featureID); final String itemID = request.getParameter(ITEM); if (itemID == null) throw new NullPointerException(); if (featureO instanceof StringField) { final StringField feature = (StringField) featureO; final String value = request.getParameter(TEXT); try { startTransaction("barText(" + featureID + ',' + itemID + ')'); final Item item = model.getItem(itemID); if (request.getParameter(PUBLISH_NOW) != null) { String v = value; if ("".equals(v)) v = null; for (final History history : History.getHistories(item.getCopeType())) { final History.Event event = history.createEvent(item, anchor.getHistoryAuthor(), false); event.createFeature(feature, feature.getName(), feature.get(item), v); } feature.set(item, v); anchor.notifyPublished(feature, item); } else { anchor.modify(value, feature, item); } model.commit(); } catch (final NoSuchIDException e) { throw new RuntimeException(e); } finally { model.rollbackIfNotCommitted(); } } else { final IntegerField feature = (IntegerField) featureO; final String itemIDFrom = request.getParameter(ITEM_FROM); if (itemIDFrom == null) throw new NullPointerException(); try { startTransaction("swapPosition(" + featureID + ',' + itemIDFrom + ',' + itemID + ')'); final Item itemFrom = model.getItem(itemIDFrom); final Item itemTo = model.getItem(itemID); final Integer positionFrom = feature.get(itemFrom); final Integer positionTo = feature.get(itemTo); feature.set(itemFrom, feature.getMinimum()); feature.set(itemTo, positionFrom); feature.set(itemFrom, positionTo); for (final History history : History.getHistories(itemFrom.getCopeType())) { final History.Event event = history.createEvent(itemFrom, anchor.getHistoryAuthor(), false); event.createFeature(feature, feature.getName(), positionFrom, positionTo); } for (final History history : History.getHistories(itemTo.getCopeType())) { final History.Event event = history.createEvent(itemTo, anchor.getHistoryAuthor(), false); event.createFeature(feature, feature.getName(), positionTo, positionFrom); } model.commit(); } catch (final NoSuchIDException e) { throw new RuntimeException(e); } finally { model.rollbackIfNotCommitted(); } } } referer = request.getParameter(REFERER); } if (referer != null) response.sendRedirect(response.encodeRedirectURL(referer)); }
From source file:com.blog.fckeditor.ConnectorServlet.java
/** * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br /> * /*www. ja v a 2s .co m*/ * The servlet accepts commands sent in the following format:<br /> * <code>connector?Command=<FileUpload>&Type=<ResourceType>&CurrentFolder=<FolderPath></code> * with the file in the <code>POST</code> body.<br /> * <br> * It stores an uploaded file (renames a file if another exists with the * same name) and then returns the JavaScript callback. */ @SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.debug("Entering Connector#doPost"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); String commandStr = request.getParameter("Command"); String typeStr = request.getParameter("Type"); String currentFolderStr = request.getParameter("CurrentFolder"); logger.debug("Parameter Command: {}", commandStr); logger.debug("Parameter Type: {}", typeStr); logger.debug("Parameter CurrentFolder: {}", currentFolderStr); UploadResponse ur; // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr' // are empty if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) { commandStr = "QuickUpload"; currentFolderStr = "/"; } if (!RequestCycleHandler.isEnabledForFileUpload(request)) ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null, Messages.NOT_AUTHORIZED_FOR_UPLOAD); else if (!CommandHandler.isValidForPost(commandStr)) ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND); else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr)) ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE); else if (!UtilsFile.isValidPath(currentFolderStr)) ur = UploadResponse.UR_INVALID_CURRENT_FOLDER; else { ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr); String typePath = UtilsFile.constructServerSidePath(request, resourceType); String typeDirPath = getServletContext().getRealPath(typePath); File typeDir = new File(typeDirPath); UtilsFile.checkDirAndCreate(typeDir); File currentDir = new File(typeDir, currentFolderStr); if (!currentDir.exists()) ur = UploadResponse.UR_INVALID_CURRENT_FOLDER; else { String newFilename = null; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); // upload.setHeaderEncoding("UTF-8"); try { List<FileItem> items = upload.parseRequest(request); // We upload only one file at the same time FileItem uplFile = items.get(0); String rawName = UtilsFile.sanitizeFileName(uplFile.getName()); String filename = FilenameUtils.getName(rawName); String baseName = FilenameUtils.removeExtension(filename); String extension = FilenameUtils.getExtension(filename); // filename = UUID.randomUUID().toString() + "." + extension; if (!ExtensionsHandler.isAllowed(resourceType, extension)) ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); else { // construct an unique file name File pathToSave = new File(currentDir, filename); int counter = 1; while (pathToSave.exists()) { newFilename = baseName.concat("(").concat(String.valueOf(counter)).concat(")") .concat(".").concat(extension); pathToSave = new File(currentDir, newFilename); counter++; } if (Utils.isEmpty(newFilename)) ur = new UploadResponse(UploadResponse.SC_OK, UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr, true, ConnectorHandler.isFullUrl()).concat(filename)); else ur = new UploadResponse(UploadResponse.SC_RENAMED, UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr, true, ConnectorHandler.isFullUrl()).concat(newFilename), newFilename); // secure image check if (resourceType.equals(ResourceTypeHandler.IMAGE) && ConnectorHandler.isSecureImageUploads()) { if (UtilsFile.isImage(uplFile.getInputStream())) uplFile.write(pathToSave); else { uplFile.delete(); ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); } } else uplFile.write(pathToSave); } } catch (Exception e) { ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR); } } } out.print(ur); out.flush(); out.close(); logger.debug("Exiting Connector#doPost"); }
From source file:kg12.Ex12_2.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*w ww . j av a 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 { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet Ex12_2</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>???</h1>"); // multipart/form-data ?? if (ServletFileUpload.isMultipartContent(request)) { out.println("???<br>"); } else { out.println("?????<br>"); out.close(); return; } // ServletFileUpload?? DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload sfu = new ServletFileUpload(factory); // ??? int fileSizeMax = 1024000; factory.setSizeThreshold(1024); sfu.setSizeMax(fileSizeMax); sfu.setHeaderEncoding("UTF-8"); // ? String format = "%s:%s<br>%n"; // ??????? FileItemIterator fileIt = sfu.getItemIterator(request); while (fileIt.hasNext()) { FileItemStream item = fileIt.next(); if (item.isFormField()) { // out.print("<br>??<br>"); out.printf(format, "??", item.getFieldName()); InputStream is = item.openStream(); // ? byte ?? byte[] b = new byte[255]; // byte? b ???? is.read(b, 0, b.length); // byte? b ? "UTF-8" ??String??? result ? String result = new String(b, "UTF-8"); out.printf(format, "", result); } else { // out.print("<br>??<br>"); out.printf(format, "??", item.getName()); InputStream is = item.openStream(); String fileName = item.getName(); int len = 0; byte[] buffer = new byte[fileSizeMax]; FileOutputStream fos = new FileOutputStream( "D:\\NetBeansProjects\\ap2_www\\web\\kg12\\" + fileName); try { while ((len = is.read(buffer)) > 0) { fos.write(buffer, 0, len); } } finally { fos.close(); } } } out.println("</body>"); out.println("</html>"); } catch (FileUploadException e) { out.println(e + "<br>"); throw new ServletException(e); } catch (Exception e) { out.println(e + "<br>"); throw new ServletException(e); } finally { out.close(); } }
From source file:com.ephesoft.gxt.admin.server.UploadImageFileServlet.java
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { String batchClassId = null;/*from w w w .j a v a 2s . c o m*/ String docName = null; String fileName = null; String isAdvancedTableInfo = null; InputStream instream = null; OutputStream out = null; PrintWriter printWriter = resp.getWriter(); if (ServletFileUpload.isMultipartContent(req)) { // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding(AdminConstants.CHARACTER_ENCODING_UTF8); List<FileItem> items; BatchSchemaService batchSchemaService = this.getSingleBeanOfType(BatchSchemaService.class); String uploadPath = null; try { items = upload.parseRequest(req); if (req.getParameter("isAdvancedTableInfo") != null) { isAdvancedTableInfo = req.getParameter("isAdvancedTableInfo").toString(); } batchClassId = req.getParameter("batchClassId"); docName = req.getParameter("docName"); log.debug("Executing Servlet for batchClassId" + batchClassId + " docName: " + docName); String fileExtension = null; for (FileItem item : items) { // process only file upload - discard other form item types if (!item.isFormField()) { fileName = item.getName(); log.debug("Executing Servlet for fileName from item:" + fileName); // Checks for invalid characters present in uploaded filename. fileName = checkFileNameForInvalidChars(fileName); log.debug("FileName of File after removing invalid characters :" + fileName); if (fileName != null) { fileName = fileName.substring(fileName.lastIndexOf(File.separator) + 1); fileExtension = fileName.substring(fileName.lastIndexOf(EXTENSION_CHAR) + 1); } instream = item.getInputStream(); printWriter.write(fileName); printWriter.write(AdminConstants.PATTERN_DELIMITER); } } if (batchClassId == null || docName == null) { log.error( "Error while loading image... Either batchClassId or doc type is null. Batch Class Id :: " + batchClassId + " Doc Type :: " + docName); printWriter.write("Error while loading image... Either batchClassId or doc type is null."); } else { batchClassId = batchClassId.trim(); docName = docName.trim(); if (isAdvancedTableInfo != null && isAdvancedTableInfo.equalsIgnoreCase(String.valueOf(Boolean.TRUE))) { uploadPath = batchSchemaService.getAdvancedTestTableFolderPath(batchClassId, true); } else { uploadPath = batchSchemaService.getTestAdvancedKvExtractionFolderPath(batchClassId, true); } uploadPath += File.separator + docName.trim() + File.separator; File uploadFolder = new File(uploadPath); if (!uploadFolder.exists()) { try { boolean tempPath = uploadFolder.mkdirs(); if (!tempPath) { log.error( "Unable to create the folders in the temp directory specified. Change the path and permissions in dcma-batch.properties"); printWriter.write( "Unable to create the folders in the temp directory specified. Change the path and permissions in dcma-batch.properties"); return; } } catch (Exception e) { log.error("Unable to create the folders in the temp directory.", e); printWriter .write("Unable to create the folders in the temp directory." + e.getMessage()); return; } } uploadPath += File.separator + fileName; uploadPath = uploadPath.substring(0, uploadPath.lastIndexOf(EXTENSION_CHAR) + 1) .concat(fileExtension.toLowerCase()); out = new FileOutputStream(uploadPath); byte buf[] = new byte[1024]; int len; while ((len = instream.read(buf)) > 0) { out.write(buf, 0, len); } ImageProcessService imageProcessService = this.getSingleBeanOfType(ImageProcessService.class); int numberOfPages = 0; // deleteFiles(uploadFolder,fileName); if (fileExtension.equalsIgnoreCase(FileType.PDF.getExtension())) { numberOfPages = PDFUtil.getPDFPageCount(uploadPath); // code to convert pdf into tiff by checking the OS on which the application is running. BatchInstanceThread batchInstanceThread = new BatchInstanceThread(); if (null != isAdvancedTableInfo && isAdvancedTableInfo.equalsIgnoreCase(String.valueOf(Boolean.TRUE)) && numberOfPages != 1) { printWriter.write(" MultiPage_error not supported for Advanced Table Extraction."); log.error("MultiPage File not supported for Advanced Table Extraction."); } else { imageProcessService.convertPdfToSinglePagePNGOrTifUsingGSAPI(new File(uploadPath), "", new File(uploadPath), batchInstanceThread, numberOfPages == 1, true, false, batchClassId); String outputParams = ApplicationConfigProperties.getApplicationConfigProperties() .getProperty(GHOSTSCRIPT_PNG_PARAMS); imageProcessService.convertPdfToSinglePagePNGOrTifUsingGSAPI(outputParams, new File(uploadPath), "", new File(uploadPath), batchInstanceThread, numberOfPages == 1, false, false); batchInstanceThread.execute(); } } else if (fileExtension.equalsIgnoreCase(FileType.TIF.getExtension()) || fileExtension.equalsIgnoreCase(FileType.TIFF.getExtension())) { numberOfPages = TIFFUtil.getTIFFPageCount(uploadPath); if (null != isAdvancedTableInfo && isAdvancedTableInfo.equalsIgnoreCase(String.valueOf(Boolean.TRUE)) && numberOfPages != 1) { printWriter.write(" MultiPage_error File not supported for Advanced Table Extraction."); log.error("MultiPage File not supported for Advanced Table Extraction."); } else { if (numberOfPages != 1) { BatchInstanceThread batchInstanceThread = new BatchInstanceThread(); imageProcessService.convertPdfOrMultiPageTiffToPNGOrTifUsingIM("", new File(uploadPath), "", new File(uploadPath), batchInstanceThread, false, false); imageProcessService.convertPdfOrMultiPageTiffToPNGOrTifUsingIM("", new File(uploadPath), "", new File(uploadPath), batchInstanceThread, false, true); batchInstanceThread.execute(); } else { imageProcessService.generatePNGForImage(new File(uploadPath)); } } log.info("Png file created successfully for file: " + uploadPath); } } } catch (FileUploadException e) { log.error("Unable to read the form contents." + e, e); printWriter.write("Unable to read the form contents.Please try again."); } catch (DCMAException e) { log.error("Unable to generate PNG." + e, e); printWriter.write("Unable to generate PNG.Please try again."); } catch (DCMAApplicationException exception) { log.error("Unable to upload Multipage file." + exception, exception); printWriter.write("Unable to upload Multipage file."); } finally { if (out != null) { out.close(); } if (instream != null) { instream.close(); } } printWriter.write("file_seperator:" + File.separator); printWriter.write("|"); } }
From source file:com.zjl.oa.fckeditor.ConnectorServlet.java
/** * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br /> * /*from ww w. j a va2 s . 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); //?? upload.setHeaderEncoding("UTF-8"); try { List<FileItem> items = upload.parseRequest(request); // We upload only one file at the same time FileItem uplFile = items.get(0); String rawName = UtilsFile.sanitizeFileName(uplFile.getName()); String filename = FilenameUtils.getName(rawName); String baseName = FilenameUtils.removeExtension(filename); String extension = FilenameUtils.getExtension(filename); //??? filename = UUID.randomUUID().toString() + "." + extension; if (!ExtensionsHandler.isAllowed(resourceType, extension)) ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); else { // construct an unique file name File pathToSave = new File(currentDir, filename); int counter = 1; while (pathToSave.exists()) { newFilename = baseName.concat("(").concat(String.valueOf(counter)).concat(")") .concat(".").concat(extension); pathToSave = new File(currentDir, newFilename); counter++; } if (Utils.isEmpty(newFilename)) ur = new UploadResponse(UploadResponse.SC_OK, UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr, true, ConnectorHandler.isFullUrl()).concat(filename)); else ur = new UploadResponse(UploadResponse.SC_RENAMED, UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr, true, ConnectorHandler.isFullUrl()).concat(newFilename), newFilename); // secure image check if (resourceType.equals(ResourceTypeHandler.IMAGE) && ConnectorHandler.isSecureImageUploads()) { if (UtilsFile.isImage(uplFile.getInputStream())) uplFile.write(pathToSave); else { uplFile.delete(); ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); } } else uplFile.write(pathToSave); } } catch (Exception e) { ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR); } } } out.print(ur); out.flush(); out.close(); logger.debug("Exiting Connector#doPost"); }
From source file:com.laijie.fckeditor.ConnectorServlet.java
/** * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br /> * //from w ww . ja v a2s . co m * The servlet accepts commands sent in the following format:<br /> * <code>connector?Command=<FileUpload>&Type=<ResourceType>&CurrentFolder=<FolderPath></code> * with the file in the <code>POST</code> body.<br /> * <br> * It stores an uploaded file (renames a file if another exists with the * same name) and then returns the JavaScript callback. */ @SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.debug("Entering Connector#doPost"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); String commandStr = request.getParameter("Command"); String typeStr = request.getParameter("Type"); String currentFolderStr = request.getParameter("CurrentFolder"); logger.debug("Parameter Command: {}", commandStr); logger.debug("Parameter Type: {}", typeStr); logger.debug("Parameter CurrentFolder: {}", currentFolderStr); UploadResponse ur; // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr' // are empty if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) { commandStr = "QuickUpload"; currentFolderStr = "/"; } if (!RequestCycleHandler.isEnabledForFileUpload(request)) ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null, Messages.NOT_AUTHORIZED_FOR_UPLOAD); else if (!CommandHandler.isValidForPost(commandStr)) ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND); else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr)) ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE); else if (!UtilsFile.isValidPath(currentFolderStr)) ur = UploadResponse.UR_INVALID_CURRENT_FOLDER; else { ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr); String typePath = UtilsFile.constructServerSidePath(request, resourceType); String typeDirPath = getServletContext().getRealPath(typePath); File typeDir = new File(typeDirPath); UtilsFile.checkDirAndCreate(typeDir); File currentDir = new File(typeDir, currentFolderStr); if (!currentDir.exists()) ur = UploadResponse.UR_INVALID_CURRENT_FOLDER; else { String newFilename = null; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); // upload.setHeaderEncoding("UTF-8"); try { List<FileItem> items = upload.parseRequest(request); // We upload only one file at the same time FileItem uplFile = items.get(0); String rawName = UtilsFile.sanitizeFileName(uplFile.getName()); String filename = FilenameUtils.getName(rawName); String baseName = FilenameUtils.removeExtension(filename); String extension = FilenameUtils.getExtension(filename); // filename = UUID.randomUUID().toString() + "." + extension; if (!ExtensionsHandler.isAllowed(resourceType, extension)) ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); else { // construct an unique file name File pathToSave = new File(currentDir, filename); int counter = 1; while (pathToSave.exists()) { newFilename = baseName.concat("(").concat(String.valueOf(counter)).concat(")") .concat(".").concat(extension); pathToSave = new File(currentDir, newFilename); counter++; } if (Utils.isEmpty(newFilename)) ur = new UploadResponse(UploadResponse.SC_OK, UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr, true, ConnectorHandler.isFullUrl()).concat(filename)); else ur = new UploadResponse(UploadResponse.SC_RENAMED, UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr, true, ConnectorHandler.isFullUrl()).concat(newFilename), newFilename); // secure image check if (resourceType.equals(ResourceTypeHandler.IMAGE) && ConnectorHandler.isSecureImageUploads()) { if (UtilsFile.isImage(uplFile.getInputStream())) uplFile.write(pathToSave); else { uplFile.delete(); ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); } } else uplFile.write(pathToSave); } } catch (Exception e) { ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR); } } } out.print(ur); out.flush(); out.close(); logger.debug("Exiting Connector#doPost"); }
From source file:com.github.thorqin.toolkit.web.utility.UploadManager.java
/** * Save upload file to disk//w w w .ja v a2 s.co m * @param request HttpServletRequest * @param maxSize maximum size of the upload file, in bytes. * @return Saved file info list * @throws ServletException * @throws IOException * @throws FileUploadException */ public List<FileInfo> saveUploadFiles(HttpServletRequest request, int maxSize) throws ServletException, IOException, FileUploadException { List<FileInfo> uploadList = new LinkedList<>(); request.setCharacterEncoding("utf-8"); ServletFileUpload upload = new ServletFileUpload(); upload.setHeaderEncoding("UTF-8"); if (!ServletFileUpload.isMultipartContent(request)) { return uploadList; } upload.setSizeMax(maxSize); FileItemIterator iterator = upload.getItemIterator(request); while (iterator.hasNext()) { FileItemStream item = iterator.next(); try (InputStream stream = item.openStream()) { if (!item.isFormField()) { FileInfo info = new FileInfo(); info.setFileName(item.getName()); if (pattern != null && !pattern.matcher(info.fileName).matches()) { continue; } info = store(stream, info.fileName); uploadList.add(info); } } } return uploadList; }
From source file:com.primeleaf.krystal.web.action.console.NewDocumentAction.java
@SuppressWarnings("rawtypes") public WebView execute(HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); User loggedInUser = (User) session.getAttribute(HTTPConstants.SESSION_KRYSTAL); String classId = request.getParameter("classid") != null ? request.getParameter("classid") : "0"; if (request.getMethod().equalsIgnoreCase("POST")) { try {//from w ww. j a v a 2 s. co m String userName = loggedInUser.getUserName(); String sessionid = (String) session.getId(); String tempFilePath = System.getProperty("java.io.tmpdir"); if (!(tempFilePath.endsWith("/") || tempFilePath.endsWith("\\"))) { tempFilePath += System.getProperty("file.separator"); } tempFilePath += userName + "_" + sessionid; //variables String fileName = "", ext = "", comments = ""; File file = null; // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding(HTTPConstants.CHARACTER_ENCODING); //Create a file upload progress listener FileUploadProgressListener listener = new FileUploadProgressListener(); upload.setProgressListener(listener); //put the listener in session session.setAttribute("LISTENER", listener); session.setAttribute("UPLOAD_ERROR", null); session.setAttribute("UPLOAD_PERCENT_COMPLETE", new Long(0)); DocumentClass documentClass = null; Hashtable<String, String> indexRecord = new Hashtable<String, String>(); String name = ""; String value = ""; List listItems = upload.parseRequest((HttpServletRequest) request); Iterator iter = listItems.iterator(); FileItem fileItem = null; while (iter.hasNext()) { fileItem = (FileItem) iter.next(); if (fileItem.isFormField()) { name = fileItem.getFieldName(); value = fileItem.getString(HTTPConstants.CHARACTER_ENCODING); if (name.equals("classid")) { classId = value; } if (name.equals("txtNote")) { comments = value; } } else { try { fileName = fileItem.getName(); file = new File(fileName); fileName = file.getName(); ext = fileName.substring(fileName.lastIndexOf(".") + 1).toUpperCase(); file = new File(tempFilePath + "." + ext); fileItem.write(file); } catch (Exception ex) { session.setAttribute("UPLOAD_ERROR", ex.getLocalizedMessage()); return null; } } } //if if (file.length() <= 0) { //code for checking minimum size of file session.setAttribute("UPLOAD_ERROR", "Zero length document"); return null; } documentClass = DocumentClassDAO.getInstance().readDocumentClassById(Integer.parseInt(classId)); if (documentClass == null) { session.setAttribute("UPLOAD_ERROR", "Invalid document class"); return null; } AccessControlManager aclManager = new AccessControlManager(); ACL acl = aclManager.getACL(documentClass, loggedInUser); if (!acl.canCreate()) { session.setAttribute("UPLOAD_ERROR", "Access Denied"); return null; } long usedStorage = DocumentDAO.getInstance().documentSize(); long availableStorage = ServerConstants.MAX_STORAGE - usedStorage; if (file.length() > availableStorage) { session.setAttribute("UPLOAD_PERCENT_COMPLETE", new Long(0)); session.setAttribute("UPLOAD_ERROR", "Document upload failed. Storage limit exceeded."); return null; } String indexValue = ""; String indexName = ""; session.setAttribute("UPLOAD_PERCENT_COMPLETE", new Long(50)); for (IndexDefinition indexDefinition : documentClass.getIndexDefinitions()) { indexName = indexDefinition.getIndexColumnName(); Iterator iter1 = listItems.iterator(); while (iter1.hasNext()) { FileItem item1 = (FileItem) iter1.next(); if (item1.isFormField()) { name = item1.getFieldName(); value = item1.getString(HTTPConstants.CHARACTER_ENCODING); if (name.equals(indexName)) { indexValue = value; String errorMessage = ""; if (indexValue != null) { if (indexDefinition.isMandatory()) { if (indexValue.trim().length() <= 0) { errorMessage = "Invalid input for " + indexDefinition.getIndexDisplayName(); session.setAttribute("UPLOAD_ERROR", errorMessage); return null; } } 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(); session.setAttribute("UPLOAD_ERROR", errorMessage); return null; } } } 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(); session.setAttribute("UPLOAD_ERROR", errorMessage); return null; } } } if (indexValue.trim().length() > indexDefinition.getIndexMaxLength()) { //code for checking index field length errorMessage = "Document index size exceeded for " + "Index Name : " + indexDefinition.getIndexDisplayName() + " [ " + "Index Length : " + indexDefinition.getIndexMaxLength() + " , " + "Actual Length : " + indexValue.length() + " ]"; session.setAttribute("UPLOAD_ERROR", errorMessage); return null; } } indexRecord.put(indexName, indexValue); } } } //while iter } //while indexCfgList session.setAttribute("UPLOAD_PERCENT_COMPLETE", new Long(70)); DocumentRevision documentRevision = new DocumentRevision(); documentRevision.setClassId(documentClass.getClassId()); documentRevision.setDocumentId(0); documentRevision.setRevisionId("1.0"); documentRevision.setDocumentFile(file); documentRevision.setUserName(loggedInUser.getUserName()); documentRevision.setIndexRecord(indexRecord); documentRevision.setComments(comments); DocumentManager documentManager = new DocumentManager(); documentManager.storeDocument(documentRevision, documentClass); //Log the entry to audit logs AuditLogManager.log(new AuditLogRecord(documentRevision.getDocumentId(), AuditLogRecord.OBJECT_DOCUMENT, AuditLogRecord.ACTION_CREATED, userName, request.getRemoteAddr(), AuditLogRecord.LEVEL_INFO, "", "Document created")); session.setAttribute("UPLOAD_PERCENT_COMPLETE", new Long(100)); } catch (Exception e) { e.printStackTrace(System.out); } return null; } else { try { ArrayList<DocumentClass> availableDocumentClasses = DocumentClassDAO.getInstance() .readDocumentClasses(" ACTIVE = 'Y'"); ArrayList<DocumentClass> documentClasses = new ArrayList<DocumentClass>(); AccessControlManager aclManager = new AccessControlManager(); for (DocumentClass documentClass : availableDocumentClasses) { ACL acl = aclManager.getACL(documentClass, loggedInUser); if (acl.canCreate()) { documentClasses.add(documentClass); } } int documentClassId = 0; try { documentClassId = Integer.parseInt(classId); } catch (Exception ex) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid input"); return (new NewDocumentView(request, response)); } if (documentClassId > 0) { DocumentClass selectedDocumentClass = DocumentClassDAO.getInstance() .readDocumentClassById(documentClassId); request.setAttribute("DOCUMENTCLASS", selectedDocumentClass); } request.setAttribute("CLASSID", documentClassId); request.setAttribute("CLASSLIST", documentClasses); } catch (Exception ex) { ex.printStackTrace(); } } return (new NewDocumentView(request, response)); }