List of usage examples for org.apache.commons.fileupload.disk DiskFileItemFactory DEFAULT_SIZE_THRESHOLD
int DEFAULT_SIZE_THRESHOLD
To view the source code for org.apache.commons.fileupload.disk DiskFileItemFactory DEFAULT_SIZE_THRESHOLD.
Click Source Link
From source file:hu.sztaki.lpds.storage.service.carmen.server.upload.ProgressMonitorFileItemFactory.java
/** * * @see DiskFileItemFactory#createItem(java.lang.String, java.lang.String, boolean, java.lang.String) */// w w w . j a v a 2 s .c om @Override public FileItem createItem(String fieldName, String contentType, boolean isFormField, String fileName) { SessionUpdatingProgressObserver observer = null; // This must be a file upload. if (isFormField == false) { observer = new SessionUpdatingProgressObserver(requestRef, fieldName, fileName); } ProgressMonitorFileItem item = new ProgressMonitorFileItem(fieldName, contentType, isFormField, fileName, DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD, temporaryDirectory, observer, requestLength); return item; }
From source file:gr.forth.ics.isl.x3mlEditor.upload.MultipartUploadParser.java
private DiskFileItemFactory setupFileItemFactory(File repository, ServletContext context) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD); factory.setRepository(repository);//from w w w .j av a 2s . c om FileCleaningTracker pTracker = FileCleanerCleanup.getFileCleaningTracker(context); factory.setFileCleaningTracker(pTracker); return factory; }
From source file:isl.FIMS.servlet.imports.ImportVocabulary.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.initVars(request); String username = getUsername(request); Config conf = new Config("AdminVoc"); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); StringBuilder xml = new StringBuilder( this.xmlStart(this.topmenu, username, this.pageTitle, this.lang, "", request)); String file = request.getParameter("file"); if (ServletFileUpload.isMultipartContent(request)) { // configures some settings String filePath = this.export_import_Folder; java.util.Date date = new java.util.Date(); Timestamp t = new Timestamp(date.getTime()); String currentDir = filePath + t.toString().replaceAll(":", ""); File saveDir = new File(currentDir); if (!saveDir.exists()) { saveDir.mkdir();/*from www.j a va2 s. c om*/ } DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD); factory.setRepository(saveDir); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(REQUEST_SIZE); // constructs the directory path to store upload file String uploadPath = currentDir; try { // parses the request's content to extract file data List formItems = upload.parseRequest(request); Iterator iter = formItems.iterator(); // iterates over form's fields File storeFile = null; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); // processes only fields that are not form fields if (!item.isFormField()) { String fileName = new File(item.getName()).getName(); filePath = uploadPath + File.separator + fileName; storeFile = new File(filePath); // saves the file on disk item.write(storeFile); } } ArrayList<String> content = Utils.readFile(storeFile); DMSConfig vocConf = new DMSConfig(this.DBURI, this.systemDbCollection + "Vocabulary/", this.DBuser, this.DBpassword); Vocabulary voc = new Vocabulary(file, this.lang, vocConf); String[] terms = voc.termValues(); for (int i = 0; i < content.size(); i++) { String addTerm = content.get(i); if (!Arrays.asList(terms).contains(addTerm)) { voc.addTerm(addTerm); } } Utils.deleteDir(currentDir); response.sendRedirect("AdminVoc?action=list&file=" + file + "&menuId=AdminVoc"); } catch (Exception ex) { } } xml.append("<FileName>").append(file).append("</FileName>\n"); xml.append("<EntityType>").append("AdminVoc").append("</EntityType>\n"); xml.append(this.xmlEnd()); String xsl = conf.IMPORT_Vocabulary; try { XMLTransform xmlTrans = new XMLTransform(xml.toString()); xmlTrans.transform(out, xsl); } catch (DMSException e) { e.printStackTrace(); } out.close(); }
From source file:edu.cornell.mannlib.vitro.webapp.filestorage.uploadrequest.MultipartHttpServletRequest.java
/** * Create an upload handler that will throw an exception if the file is too * large.//from www.ja v a2 s . c o m */ private ServletFileUpload createUploadHandler(int maxFileSize, File tempDir) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD); factory.setRepository(tempDir); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(maxFileSize); return upload; }
From source file:com.bbc.remarc.ws.UploadServiceImpl.java
/** * Helper method to create a DiskFileItemFactory, which includes a cleaning tracker to remove old tmp files * @param context Servlet Context/*from w ww .j av a2 s . c o m*/ * @param repository Temp Directory * @return created DiskFileItemFactory */ private DiskFileItemFactory newDiskFileItemFactory(ServletContext context, File repository) { FileCleaningTracker fileCleaningTracker = FileCleanerCleanup.getFileCleaningTracker(context); DiskFileItemFactory factory = new DiskFileItemFactory(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD, repository); factory.setFileCleaningTracker(fileCleaningTracker); return factory; }
From source file:edu.cornell.mannlib.vitro.webapp.controller.MultipartRequestWrapper.java
/** * Create an upload handler that will throw an exception if the file is too * large.//from w w w . j ava2 s . c om */ private static ServletFileUpload createUploadHandler(HttpServletRequest req, long maxFileSize) { File tempDir = figureTemporaryDirectory(req); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD); factory.setRepository(tempDir); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(maxFileSize); return upload; }
From source file:isl.FIMS.servlet.imports.ImportXML.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.initVars(request); String username = getUsername(request); Config conf = new Config("EisagwghXML_RDF"); String xsl = ApplicationConfig.SYSTEM_ROOT + "formating/xsl/import/ImportXML.xsl"; String displayMsg = ""; response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); StringBuilder xml = new StringBuilder( this.xmlStart(this.topmenu, username, this.pageTitle, this.lang, "", request)); // ArrayList<String> notValidMXL = new ArrayList<String>(); HashMap<String, ArrayList> notValidMXL = new <String, ArrayList>HashMap(); if (!ServletFileUpload.isMultipartContent(request)) { displayMsg = "form"; } else {/* ww w . j av a 2 s .c om*/ // configures some settings String filePath = this.export_import_Folder; java.util.Date date = new java.util.Date(); Timestamp t = new Timestamp(date.getTime()); String currentDir = filePath + t.toString().replaceAll(":", ""); File saveDir = new File(currentDir); if (!saveDir.exists()) { saveDir.mkdir(); } DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD); factory.setRepository(saveDir); ArrayList<String> savedIDs = new ArrayList<String>(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(REQUEST_SIZE); // constructs the directory path to store upload file String uploadPath = currentDir; int xmlCount = 0; String[] id = null; try { // parses the request's content to extract file data List formItems = upload.parseRequest(request); Iterator iter = formItems.iterator(); // iterates over form's fields File storeFile = null; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); // processes only fields that are not form fields if (!item.isFormField()) { String fileName = new File(item.getName()).getName(); filePath = uploadPath + File.separator + fileName; storeFile = new File(filePath); item.write(storeFile); Utils.unzip(fileName, uploadPath); File dir = new File(uploadPath); String[] extensions = new String[] { "xml", "x3ml" }; List<File> files = (List<File>) FileUtils.listFiles(dir, extensions, true); xmlCount = files.size(); for (File file : files) { // saves the file on disk Document doc = ParseXMLFile.parseFile(file.getPath()); String xmlContent = doc.getDocumentElement().getTextContent(); String uri_name = ""; try { uri_name = DMSTag.valueOf("uri_name", "target", type, this.conf)[0]; } catch (DMSException ex) { ex.printStackTrace(); } String uriValue = this.URI_Reference_Path + uri_name + "/"; boolean insertEntity = false; if (xmlContent.contains(uriValue) || file.getName().contains(type)) { insertEntity = true; } Element root = doc.getDocumentElement(); Node admin = Utils.removeNode(root, "admin", true); // File rename = new File(uploadPath + File.separator + id[0] + ".xml"); // boolean isRename = storeFile.renameTo(rename); // ParseXMLFile.saveXMLDocument(rename.getPath(), doc); String schemaFilename = ""; schemaFilename = type; SchemaFile sch = new SchemaFile(schemaFolder + schemaFilename + ".xsd"); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(writer)); String xmlString = writer.getBuffer().toString().replaceAll("\r", ""); //without admin boolean isValid = sch.validate(xmlString); if ((!isValid && insertEntity)) { notValidMXL.put(file.getName(), null); } else if (insertEntity) { id = initInsertFile(type, false); doc = createAdminPart(id[0], type, doc, username); writer = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(writer)); xmlString = writer.getBuffer().toString().replaceAll("\r", ""); DBCollection col = new DBCollection(this.DBURI, id[1], this.DBuser, this.DBpassword); DBFile dbF = col.createFile(id[0] + ".xml", "XMLDBFile"); dbF.setXMLAsString(xmlString); dbF.store(); ArrayList<String> externalFiles = new <String>ArrayList(); ArrayList<String> externalDBFiles = new <String>ArrayList(); String q = "//*["; for (String attrSet : this.uploadAttributes) { String[] temp = attrSet.split("#"); String func = temp[0]; String attr = temp[1]; if (func.contains("text")) { q += "@" + attr + "]/text()"; } else { q = "data(//*[@" + attr + "]/@" + attr + ")"; } String[] res = dbF.queryString(q); for (String extFile : res) { externalFiles.add(extFile + "#" + attr); } } q = "//"; if (!dbSchemaPath[0].equals("")) { for (String attrSet : this.dbSchemaPath) { String[] temp = attrSet.split("#"); String func = temp[0]; String path = temp[1]; if (func.contains("text")) { q += path + "//text()"; } else { q = "data(//" + path + ")"; } String[] res = dbF.queryString(q); for (String extFile : res) { externalDBFiles.add(extFile); } } } ArrayList<String> missingExternalFiles = new <String>ArrayList(); for (String extFile : externalFiles) { extFile = extFile.substring(0, extFile.lastIndexOf("#")); List<File> f = (List<File>) FileUtils.listFiles(dir, FileFilterUtils.nameFileFilter(extFile), TrueFileFilter.INSTANCE); if (f.size() == 0) { missingExternalFiles.add(extFile); } } if (missingExternalFiles.size() > 0) { notValidMXL.put(file.getName(), missingExternalFiles); } XMLEntity xmlNew = new XMLEntity(this.DBURI, this.systemDbCollection + type, this.DBuser, this.DBpassword, type, id[0]); ArrayList<String> worngFiles = Utils.checkReference(xmlNew, this.DBURI, id[0], type, this.DBuser, this.DBpassword); if (worngFiles.size() > 0) { //dbF.remove(); notValidMXL.put(file.getName(), worngFiles); } //remove duplicates from externalFiles if any HashSet hs = new HashSet(); hs.addAll(missingExternalFiles); missingExternalFiles.clear(); missingExternalFiles.addAll(hs); if (missingExternalFiles.isEmpty() && worngFiles.isEmpty()) { for (String extFile : externalFiles) { String attr = extFile.substring(extFile.lastIndexOf("#") + 1, extFile.length()); extFile = extFile.substring(0, extFile.lastIndexOf("#")); List<File> f = (List<File>) FileUtils.listFiles(dir, FileFilterUtils.nameFileFilter(extFile), TrueFileFilter.INSTANCE); File uploadFile = f.iterator().next(); String content = FileUtils.readFileToString(uploadFile); DBFile uploadsDBFile = new DBFile(this.DBURI, this.adminDbCollection, "Uploads.xml", this.DBuser, this.DBpassword); String mime = Utils.findMime(uploadsDBFile, uploadFile.getName(), attr); String uniqueName = Utils.createUniqueFilename(uploadFile.getName()); File uploadFileUnique = new File(uploadFile.getPath().substring(0, uploadFile.getPath().lastIndexOf(File.separator)) + File.separator + uniqueName); uploadFile.renameTo(uploadFileUnique); xmlString = xmlString.replaceAll(uploadFile.getName(), uniqueName); String upload_path = this.systemUploads + type; File upload_dir = null; ; if (mime.equals("Photos")) { upload_path += File.separator + mime + File.separator + "original" + File.separator; upload_dir = new File(upload_path + uniqueName); FileUtils.copyFile(uploadFileUnique, upload_dir); Utils.resizeImage(uniqueName, upload_path, upload_path.replaceAll("original", "thumbs"), thumbSize); Utils.resizeImage(uniqueName, upload_path, upload_path.replaceAll("original", "normal"), normalSize); xmlString = xmlString.replace("</versions>", "</versions>" + "\n" + "<type>Photos</type>"); } else { upload_path += File.separator + mime + File.separator; upload_dir = new File(upload_path + uniqueName); FileUtils.copyFile(uploadFileUnique, upload_dir); } if (!dbSchemaFolder.equals("")) { if (externalDBFiles.contains(extFile)) { try { DBCollection colSchema = new DBCollection(this.DBURI, dbSchemaFolder, this.DBuser, this.DBpassword); DBFile dbFSchema = colSchema.createFile(uniqueName, "XMLDBFile"); dbFSchema.setXMLAsString(content); dbFSchema.store(); } catch (Exception e) { } } } uploadFileUnique.renameTo(uploadFile); } dbF.setXMLAsString(xmlString); dbF.store(); Utils.updateReferences(xmlNew, this.DBURI, id[0].split(type)[1], type, this.DBpassword, this.DBuser); Utils.updateVocabularies(xmlNew, this.DBURI, id[0].split(type)[1], type, this.DBpassword, this.DBuser, lang); savedIDs.add(id[0]); } else { dbF.remove(); } } } } } Document doc = ParseXMLFile.parseFile(ApplicationConfig.SYSTEM_ROOT + "formating/multi_lang.xml"); Element root = doc.getDocumentElement(); Element contextTag = (Element) root.getElementsByTagName("context").item(0); String uri_name = ""; try { uri_name = DMSTag.valueOf("uri_name", "target", type, this.conf)[0]; } catch (DMSException ex) { } if (notValidMXL.size() == 0) { xsl = conf.DISPLAY_XSL; displayMsg = Messages.ACTION_SUCCESS; displayMsg += Messages.NL + Messages.NL + Messages.URI_ID; String uriValue = ""; xml.append("<Display>").append(displayMsg).append("</Display>\n"); xml.append("<backPages>").append('2').append("</backPages>\n"); for (String saveId : savedIDs) { uriValue = this.URI_Reference_Path + uri_name + "/" + saveId + Messages.NL; xml.append("<codeValue>").append(uriValue).append("</codeValue>\n"); } } else if (notValidMXL.size() >= 1) { xsl = ApplicationConfig.SYSTEM_ROOT + "formating/xsl/import/ImportXML.xsl"; Iterator it = notValidMXL.keySet().iterator(); while (it.hasNext()) { String key = (String) it.next(); ArrayList<String> value = notValidMXL.get(key); if (value != null) { displayMsg += "<line>"; Element select = (Element) contextTag.getElementsByTagName("missingReferences").item(0); displayMsg += select.getElementsByTagName(lang).item(0).getTextContent(); displayMsg = displayMsg.replace("?", key); for (String mis_res : value) { displayMsg += mis_res + ","; } displayMsg = displayMsg.substring(0, displayMsg.length() - 1); displayMsg += "."; displayMsg += "</line>"; } else { displayMsg += "<line>"; Element select = (Element) contextTag.getElementsByTagName("NOT_VALID_XML").item(0); displayMsg += select.getElementsByTagName(lang).item(0).getTextContent(); displayMsg = displayMsg.replace(";", key); displayMsg += "</line>"; } displayMsg += "<line>"; displayMsg += "</line>"; } if (notValidMXL.size() < xmlCount) { displayMsg += "<line>"; Element select = (Element) contextTag.getElementsByTagName("rest_valid").item(0); displayMsg += select.getElementsByTagName(lang).item(0).getTextContent(); displayMsg += "</line>"; for (String saveId : savedIDs) { displayMsg += "<line>"; String uriValue = this.URI_Reference_Path + uri_name + "/" + saveId; select = (Element) contextTag.getElementsByTagName("URI_ID").item(0); displayMsg += select.getElementsByTagName(lang).item(0).getTextContent() + ": " + uriValue; displayMsg += "</line>"; } } } Utils.deleteDir(currentDir); } catch (Exception ex) { ex.printStackTrace(); displayMsg += Messages.NOT_VALID_IMPORT; } } xml.append("<Display>").append(displayMsg).append("</Display>\n"); xml.append("<EntityType>").append(type).append("</EntityType>\n"); xml.append(this.xmlEnd()); try { XMLTransform xmlTrans = new XMLTransform(xml.toString()); xmlTrans.transform(out, xsl); } catch (DMSException e) { e.printStackTrace(); } out.close(); }
From source file:lucee.runtime.type.scope.FormImpl.java
private void initializeMultiPart(PageContext pc, boolean scriptProteced) { // get temp directory Resource tempDir = ((ConfigImpl) pc.getConfig()).getTempDirectory(); Resource tempFile;//from w w w . j a v a 2 s . c o m // Create a new file upload handler final String encoding = getEncoding(); FileItemFactory factory = tempDir instanceof File ? new DiskFileItemFactory(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD, (File) tempDir) : new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding(encoding); //ServletRequestContext c = new ServletRequestContext(pc.getHttpServletRequest()); HttpServletRequest req = pc.getHttpServletRequest(); ServletRequestContext context = new ServletRequestContext(req) { public String getCharacterEncoding() { return encoding; } }; // Parse the request try { FileItemIterator iter = upload.getItemIterator(context); //byte[] value; InputStream is; ArrayList<URLItem> list = new ArrayList<URLItem>(); while (iter.hasNext()) { FileItemStream item = iter.next(); is = IOUtil.toBufferedInputStream(item.openStream()); if (item.getContentType() == null || StringUtil.isEmpty(item.getName())) { list.add(new URLItem(item.getFieldName(), new String(IOUtil.toBytes(is), encoding), false)); } else { tempFile = tempDir.getRealResource(getFileName()); fileItems.put(item.getFieldName().toLowerCase(), new Item(tempFile, item.getContentType(), item.getName(), item.getFieldName())); String value = tempFile.toString(); IOUtil.copy(is, tempFile, true); list.add(new URLItem(item.getFieldName(), value, false)); } } raw = list.toArray(new URLItem[list.size()]); fillDecoded(raw, encoding, scriptProteced, pc.getApplicationContext().getSameFieldAsArray(SCOPE_FORM)); } catch (Exception e) { //throw new PageRuntimeException(Caster.toPageException(e)); fillDecodedEL(new URLItem[0], encoding, scriptProteced, pc.getApplicationContext().getSameFieldAsArray(SCOPE_FORM)); initException = e; } }
From source file:dk.dma.msinm.common.repo.RepositoryService.java
/** * Creates a new DiskFileItemFactory. See: * http://commons.apache.org/proper/commons-fileupload/using.html * @return the new DiskFileItemFactory//from w ww .java 2 s. co m */ public static DiskFileItemFactory newDiskFileItemFactory(ServletContext servletContext) { FileCleaningTracker fileCleaningTracker = FileCleanerCleanup.getFileCleaningTracker(servletContext); DiskFileItemFactory factory = new DiskFileItemFactory(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD, null); factory.setFileCleaningTracker(fileCleaningTracker); return factory; }
From source file:com.krawler.spring.crm.emailMarketing.crmEmailMarketingController.java
public ModelAndView saveEmailTemplateFiles(HttpServletRequest request, HttpServletResponse response) throws ServletException { JSONObject result = new JSONObject(); DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setName("JE_Tx"); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_UNCOMMITTED); TransactionStatus status = txnManager.getTransaction(def); try {//w w w .java2s. c om result.put("success", false); int file_type = 1; String fType = request.getParameter("type"); if (fType != null && fType.compareTo("img") == 0) { file_type = 0; } String companyid = sessionHandlerImpl.getCompanyid(request); String filename = ""; ServletFileUpload fu = new ServletFileUpload( new DiskFileItemFactory(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD, new File("/tmp"))); if (fu.isMultipartContent(request)) { List<FileItem> fileItems = fu.parseRequest(request); for (FileItem field : fileItems) { if (!field.isFormField()) { String fname = new String(field.getName().getBytes(), "UTF8"); String file_id = java.util.UUID.randomUUID().toString(); String file_extn = fname.substring(fname.lastIndexOf(".")); filename = file_id.concat(file_extn); boolean isUploaded = false; fname = fname.substring(fname.lastIndexOf("\\") + 1); if (field.getSize() != 0) { String basePath = StorageHandler.GetDocStorePath() + companyid + "/" + fType; File destDir = new File(basePath); if (!destDir.exists()) { destDir.mkdirs(); } File uploadFile = new File(basePath + "/" + filename); field.write(uploadFile); isUploaded = true; String id = request.getParameter("fileid"); if (StringUtil.isNullOrEmpty(id)) { id = file_id; } crmEmailMarketingDAOObj.saveEmailTemplateFile(id, fname, file_extn, new Date(), file_type, sessionHandlerImplObj.getUserid()); } } } } txnManager.commit(status); result.put("success", true); } catch (ServiceException e) { logger.warn(e.getMessage(), e); txnManager.rollback(status); try { result.put("msg", e.getMessage()); } catch (Exception je) { } } catch (UnsupportedEncodingException ex) { logger.warn(ex.getMessage(), ex); txnManager.rollback(status); try { result.put("msg", ex.getMessage()); } catch (Exception je) { } } catch (Exception e) { logger.warn(e.getMessage(), e); txnManager.rollback(status); try { result.put("msg", e.getMessage()); } catch (Exception je) { } } return new ModelAndView("jsonView", "model", result.toString()); }