List of usage examples for org.apache.commons.fileupload.disk DiskFileItemFactory setSizeThreshold
public void setSizeThreshold(int sizeThreshold)
From source file:org.karsha.controler.UploadDocumentServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { SecurityManager sm = System.getSecurityManager(); HttpSession session = request.getSession(); String userPath = request.getServletPath(); String url = ""; List items = null;/*from w w w .ja v a 2 s .com*/ if (userPath.equals("/uploaddocuments")) { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(5000000); // FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { // items = upload. items = upload.parseRequest(request); } catch (Exception ex) { Logger.getLogger(UploadDocumentServlet.class.getName()).log(Level.SEVERE, null, ex); } HashMap requestParameters = new HashMap(); try { Iterator iterator = items.iterator(); while (iterator.hasNext()) { FileItem item = (FileItem) iterator.next(); if (item.isFormField()) { requestParameters.put(item.getFieldName(), item.getString()); } else { PDFBookmark pdfBookmark = new PDFBookmark(); byte[] fileContent = item.get(); LinkedHashMap<String, String> docSectionMap = pdfBookmark .splitPDFByBookmarks(fileContent); if (!docSectionMap.isEmpty()) { Document newDocument = new Document(); newDocument.setDocumentName(requestParameters.get("docName").toString()); newDocument.setUserId(Integer.parseInt(session.getAttribute("userId").toString())); String a = requestParameters.get("collection_type_new").toString(); newDocument.setCollectionId(Integer.parseInt(a)); // newDocument.setDocumentContent(fileContent); request.setAttribute("requestParameters", requestParameters); if (DocumentDB.isFileNameDuplicate(newDocument.getDocumentName())) { url = "/WEB-INF/view/uploaddoc.jsp?error=File name already exists, please enter another file name"; } else { //DocumentDB.insert(newDocument); DocumentDB.insertDocMetaData(newDocument); int docId = DocumentDB .getDocumentDataByDocName(requestParameters.get("docName").toString()) .getDocId(); DocSection docSection = new DocSection(); for (Map.Entry entry : docSectionMap.entrySet()) { docSection.setParentDocId(docId); docSection.setSectionName((String) entry.getKey()); byte[] byte1 = ((String) entry.getValue()).getBytes(); docSection.setSectionContent(byte1); docSection.setUserId( Integer.parseInt(session.getAttribute("userId").toString())); //To-Do set this correctly //docSection.setSectionCatog(Integer.parseInt(session.getAttribute("sectioncat").toString())); docSection.setSectionCatog(4); DocSectionDB.insert(docSection); } url = "/WEB-INF/view/uploaddoc.jsp?succuss=File Uploaded Successfully"; } } /* * check wheter text can be extracted */ /* * if(DocumentValidator.isDocValidated(fileContent)){ * * * Document newDocument = new Document(); * newDocument.setDocumentName(requestParameters.get("docName").toString()); * newDocument.setUserId(Integer.parseInt(session.getAttribute("userId").toString())); * String a = * requestParameters.get("collection_type_new").toString(); * newDocument.setCollectionId(Integer.parseInt(a)); * newDocument.setDocumentContent(fileContent); * * request.setAttribute("requestParameters", * requestParameters); * * if * (DocumentDB.isFileNameDuplicate(newDocument.getDocumentName())) * { url = "/WEB-INF/view/uploaddoc.jsp?error=File * name already exists, please enter another file * name"; } else { //DocumentDB.insert(newDocument); * DocumentDB.insertDocMetaData(newDocument); url = * "/WEB-INF/view/uploaddoc.jsp?succuss=File * Uploaded Successfully"; } * * * } * */ else { url = "/WEB-INF/view/uploaddoc.jsp?error=Text can't be extracted from file, Please try onother"; } } } } // catch (FileUploadException e) { // e.printStackTrace(); // // // } // catch (Exception e) { e.printStackTrace(); } } request.getRequestDispatcher(url).forward(request, response); } }
From source file:org.kuali.ole.web.DocumentServlet.java
private ArrayList<File> extractBagFilesFromRequest(HttpServletRequest req, HttpServletResponse res) throws Exception { File targetDir = null;/*w w w . j a v a 2 s . co m*/ try { File file = null; DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); fileItemFactory.setSizeThreshold(1 * 1024 * 1024); // 1 MB Iterator items = new ServletFileUpload(fileItemFactory).parseRequest(req).iterator(); while (items.hasNext()) { FileItem item = (FileItem) items.next(); file = new File(FileUtils.getTempDirectory(), item.getName()); item.write(file); } targetDir = compressUtils.extractZippedBagFile(file.getAbsolutePath(), null); LOG.info("extractedBagFileLocation " + targetDir); } catch (IOException e) { LOG.error("IOException", e); sendResponseBag(res, e.getMessage(), "failure"); } catch (FormatHelper.UnknownFormatException unknownFormatException) { LOG.error("unknownFormatException", unknownFormatException); sendResponseBag(res, unknownFormatException.getMessage(), "failure"); } return compressUtils.getAllFilesList(targetDir); }
From source file:org.kuali.ole.web.LicenseRestServlet.java
private ArrayList<File> extractBagFilesFromRequest(HttpServletRequest req, HttpServletResponse res) throws Exception { File targetDir = null;/*from ww w . j a v a 2 s. co m*/ try { File file = null; DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); fileItemFactory.setSizeThreshold(1 * 1024 * 1024); // 1 MB Iterator items = new ServletFileUpload(fileItemFactory).parseRequest(req).iterator(); while (items.hasNext()) { FileItem item = (FileItem) items.next(); file = new File(FileUtils.getTempDirectory(), item.getName()); item.write(file); } targetDir = compressUtils.extractZippedBagFile(file.getAbsolutePath(), extractFilePath); LOG.info("extractedBagFileLocation " + targetDir); } catch (IOException e) { LOG.error("IOException", e); // sendResponseBag(res, e.getMessage(), "failure"); } catch (FormatHelper.UnknownFormatException unknownFormatException) { LOG.error("unknownFormatException", unknownFormatException); // sendResponseBag(res, unknownFormatException.getMessage(), "failure"); } return compressUtils.getAllFilesList(targetDir); }
From source file:org.kuali.rice.edl.impl.RequestParser.java
private static void parseRequest(HttpServletRequest request) { if (request.getAttribute(PARSED_MULTI_REQUEST_KEY) != null) { return;//from w w w . j a va2s.c om } Map requestParams = new HashMap(); request.setAttribute(PARSED_MULTI_REQUEST_KEY, requestParams); DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setSizeThreshold(100); ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory); List items = null; try { items = upload.parseRequest(request); } catch (FileUploadException fue) { throw new WorkflowRuntimeException(fue); } Iterator iter = items.iterator(); while (iter.hasNext()) { try { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { String fieldName = item.getFieldName(); String fieldValue = item.getString("utf-8"); String[] paramVals = null; if (requestParams.containsKey(fieldName)) { paramVals = (String[]) requestParams.get(fieldName); paramVals = (String[]) ArrayUtils.add(paramVals, fieldValue); } else { paramVals = new String[1]; paramVals[0] = fieldValue; } requestParams.put(fieldName, paramVals); } else { List uploadedFiles = (List) request.getAttribute(UPLOADED_FILES_KEY); if (uploadedFiles == null) { uploadedFiles = new ArrayList(); request.setAttribute(UPLOADED_FILES_KEY, uploadedFiles); } uploadedFiles.add(item); } } catch (UnsupportedEncodingException e) { throw new WorkflowRuntimeException(e); } } }
From source file:org.ldp4j.apps.ldp4ro.servlets.FileUploaderServlet.java
private ServletFileUpload getFileItemFactory() { Config config = ConfigManager.getAppConfig(); // configures upload settings DiskFileItemFactory factory = new DiskFileItemFactory(); // sets memory threshold - beyond which files are stored in disk factory.setSizeThreshold(config.getInt(MEMORY_THRESHOULD)); // sets temporary location to store files File tempUploadDir = new File(System.getProperty("java.io.tmpdir")); if (!tempUploadDir.exists()) { tempUploadDir.mkdir();/* ww w .ja v a 2 s .com*/ } factory.setRepository(tempUploadDir); ServletFileUpload upload = new ServletFileUpload(factory); // sets maximum size of upload file upload.setFileSizeMax(config.getLong(MAX_FILE_SIZE)); // sets maximum size of request (include file + form data) upload.setSizeMax(config.getLong(MAX_REQUEST_SIZE)); return upload; }
From source file:org.locationtech.geogig.rest.repository.UploadCommandResource.java
/** * Consumes the data sent from the client and stores it into a temporary file to be processed. * This method is just looking through the request entity for form data named * {@value #UPLOAD_FILE_KEY}. If present, we will consume the data stream from the request and * store it in a temporary file.//from w w w .j a v a 2 s .co m * * @param entity POSTed entity containing binary data to be processed. * * @return local File representation of the data streamed form the client. */ private File consumeFileUpload(Representation entity) { File uploadedFile = null; // get a File item factory final DiskFileItemFactory factory = new DiskFileItemFactory(); // set the threshold factory.setSizeThreshold(UPLOAD_THRESHOLD); // build a Restlet file upload with the factory final RestletFileUpload fileUploadUtil = new RestletFileUpload(factory); // try to extract the uploaded file entity try { // build a RepresentaionContext of the request entity final RepresentationContext context = new RepresentationContext(entity); // get an iterator to loop through the entity for the upload data final FileItemIterator iterator = fileUploadUtil.getItemIterator(context); // look for the the "fileUpload" form data while (iterator.hasNext()) { final FileItemStream fis = iterator.next(); // see if this is the data we are looking for if (UPLOAD_FILE_KEY.equals(fis.getFieldName())) { // if we've already ingested a fileUpload, then the request had more than one. Preconditions.checkState(uploadedFile == null, FILE_UPLOAD_ERROR_TMPL, UPLOAD_FILE_KEY); // found it, create a temp file uploadedFile = File.createTempFile("geogig-" + UPLOAD_FILE_KEY + "-", ".tmp"); uploadedFile.deleteOnExit(); // consume the streamed contetn into the temp file try (FileOutputStream fos = new FileOutputStream(uploadedFile)) { ByteUtils.write(fis.openStream(), fos); // flush the output stream fos.flush(); } } } // if we don't have an uploaded file, we can't continue Preconditions.checkNotNull(uploadedFile, FILE_UPLOAD_ERROR_TMPL, UPLOAD_FILE_KEY); } catch (Exception ex) { // delete the temp file if it exists if (uploadedFile != null) { uploadedFile.delete(); } // null out the file uploadedFile = null; } // return the uploaded entity data as a file return uploadedFile; }
From source file:org.martin.cloudWebClient.servlets.UploadFileServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from ww w .j av a2 s. c om * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); if (session.getAttribute("cliPackage") == null || session.getAttribute("connector") == null) { response.sendRedirect("index.jsp"); return; } ClientPackage cp = (ClientPackage) session.getAttribute("cliPackage"); Connector con = (Connector) session.getAttribute("connector"); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1024); factory.setRepository(new File(SysInfo.TEMP_FOLDER_NAME)); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> partes = upload.parseRequest(request); Archive toUpload; Command cmdUpload; File file; for (FileItem item : partes) { if (!item.isFormField()) { file = new File(SysInfo.TEMP_FOLDER_NAME, item.getName()); item.write(file); toUpload = new Archive(cp.getCurrentDir(), item.getName()); toUpload.writeBytesFrom(file); cmdUpload = new Command(Command.uplF.getOrder(), file.getCanonicalPath(), cp.getCurrentDirPath()); con.sendTransferPackage(new TransferPackage(cmdUpload, toUpload)); file.delete(); } } con.sendUpdateRequest(cp.getCurrentDirPath(), cp.getUserNick()); cp.update(con.getUpdatesReceived()); session.setAttribute("cliPackage", cp); response.sendRedirect("management.jsp"); } catch (FileUploadException ex) { JOptionPane.showMessageDialog(null, "FileUploadException"); Logger.getLogger(UploadFileServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { JOptionPane.showMessageDialog(null, "Exception"); Logger.getLogger(UploadFileServlet.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:org.megatome.frame2.front.FileUploadSupport.java
@SuppressWarnings("unchecked") public static Map<String, Object> processMultipartRequest(final HttpServletRequest request) throws Frame2Exception { Map<String, Object> parameters = new HashMap<String, Object>(); // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Set factory constraints factory.setSizeThreshold(FileUploadConfig.getBufferSize()); factory.setRepository(new File(FileUploadConfig.getFileTempDir())); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(FileUploadConfig.getMaxFileSize()); List<FileItem> fileItems = null; try {// www.j av a 2s .c o m fileItems = upload.parseRequest(request); } catch (FileUploadException fue) { LOGGER.severe("File Upload Error", fue); //$NON-NLS-1$ throw new Frame2Exception("File Upload Exception", fue); //$NON-NLS-1$ } for (FileItem fi : fileItems) { String fieldName = fi.getFieldName(); if (fi.isFormField()) { if (parameters.containsKey(fieldName)) { List<Object> tmpArray = new ArrayList<Object>(); if (parameters.get(fieldName) instanceof String[]) { String[] origValues = (String[]) parameters.get(fieldName); for (int idx = 0; idx < origValues.length; idx++) { tmpArray.add(origValues[idx]); } tmpArray.add(fi.getString()); } else { tmpArray.add(parameters.get(fieldName)); tmpArray.add(fi.getString()); } String[] newValues = new String[tmpArray.size()]; newValues = tmpArray.toArray(newValues); parameters.put(fieldName, newValues); } else { parameters.put(fieldName, fi.getString()); } } else { if (parameters.containsKey(fieldName)) { List<Object> tmpArray = new ArrayList<Object>(); if (parameters.get(fieldName) instanceof FileItem[]) { FileItem[] origValues = (FileItem[]) parameters.get(fieldName); for (int idx = 0; idx < origValues.length; idx++) { tmpArray.add(origValues[idx]); } tmpArray.add(fi); } else { tmpArray.add(parameters.get(fieldName)); tmpArray.add(fi); } FileItem[] newValues = new FileItem[tmpArray.size()]; newValues = tmpArray.toArray(newValues); parameters.put(fieldName, newValues); } else { parameters.put(fieldName, fi); } } } return parameters; }
From source file:org.metaeffekt.dcc.agent.AgentRouteBuilder.java
public AgentRouteBuilder(AgentScriptExecutor scriptExecutor) { final DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(MAX_FILE_SIZE); factory.setFileCleaningTracker(new FileCleaningTracker()); restletFileUpload = new RestletFileUpload(factory); this.remoteScriptExecutor = scriptExecutor; }
From source file:org.mifos.dmt.ui.DMTExcelUpload.java
@SuppressWarnings("rawtypes") protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { DMTLock migrationLock = DMTLock.getInstance(); if (!migrationLock.isLocked()) { migrationLock.getLock();// ww w . j a v a2 s .c o m clearLogs(); response.setContentType("text/plain"); DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); fileItemFactory.setSizeThreshold(5 * 1024 * 1024); fileItemFactory.setRepository(tmpDir); ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); try { List items = uploadHandler.parseRequest(request); Iterator itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); File file = new File(destinationDir, "MigrationTemplate.xlsx"); /*System.out.println("i got here " + destinationDir.toString());*/ Workbook workbook = WorkbookFactory.create(item.getInputStream()); SheetStructure sheetStructure = new SheetStructure(workbook); if (!sheetStructure.processWorkbook()) { logger.error( "Excel upload failed!!Please check if necessary sheets are present in the excel"); throw new DMTException( "Excel upload failed!!Please check if necessary sheets are present in the excel"); } String baseTemplate = DMTConfig.DMT_CONFIG_DIR + "\\DMTMigrationTemplateBase.xlsx"; ColumnStructure columnstructure = new ColumnStructure(workbook, baseTemplate); workbook = columnstructure.processSheetStructure(); PurgeEmptyRows excessrows = new PurgeEmptyRows(workbook); workbook = excessrows.processEmptyRows(); FileOutputStream fileoutputstream = new FileOutputStream(file); workbook.write(fileoutputstream); logger.info("Uploading of Excel has been successful!!"); migrationLock.releaseLock(); } } catch (FileUploadException ex) { logger.error("Error encountered while parsing the request", ex); logger.error("Uploading of Excel has not been successful!!"); migrationLock.releaseLock(); ex.printStackTrace(); } catch (Exception ex) { logger.error("Error encountered while uploading file", ex); logger.error("Uploading of Excel has not been successful!!"); migrationLock.releaseLock(); ex.printStackTrace(); } } else { request.setAttribute("action", "info"); RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("/x"); requestDispatcher.forward(request, response); } }