List of usage examples for org.apache.commons.fileupload.disk DiskFileItemFactory setRepository
public void setRepository(File repository)
From source file:com.mx.nibble.middleware.web.util.FileUpload.java
public void performTask(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) { /**// w ww . j a v a 2 s.c o m * This pages gives a sample of java upload management. It needs the commons FileUpload library, which can be found on apache.org. * * Note: * - putting error=true as a parameter on the URL will generate an error. Allows test of upload error management in the applet. * * * * * * */ logger.debug(" Directory to store all the uploaded files"); String ourTempDirectory = "/opt/erp/import/obras/"; try { out = response.getWriter(); } catch (Exception e) { e.printStackTrace(); } byte[] cr = { 13 }; byte[] lf = { 10 }; String CR = new String(cr); String LF = new String(lf); String CRLF = CR + LF; out.println("Before a LF=chr(10)" + LF + "Before a CR=chr(13)" + CR + "Before a CRLF" + CRLF); logger.debug("Initialization for chunk management."); boolean bLastChunk = false; int numChunk = 0; logger.debug( "CAN BE OVERRIDEN BY THE postURL PARAMETER: if error=true is passed as a parameter on the URL"); boolean generateError = false; boolean generateWarning = false; boolean sendRequest = false; response.setContentType("text/plain"); java.util.Enumeration<String> headers = request.getHeaderNames(); out.println("[parseRequest.jsp] ------------------------------ "); out.println("[parseRequest.jsp] Headers of the received request:"); logger.debug("[parseRequest.jsp] Headers of the received request:"); while (headers.hasMoreElements()) { String header = headers.nextElement(); out.println("[parseRequest.jsp] " + header + ": " + request.getHeader(header)); logger.debug("[parseRequest.jsp] " + header + ": " + request.getHeader(header)); } out.println("[parseRequest.jsp] ------------------------------ "); try { logger.debug(" Get URL Parameters."); Enumeration paraNames = request.getParameterNames(); out.println("[parseRequest.jsp] ------------------------------ "); out.println("[parseRequest.jsp] Parameters: "); logger.debug("[parseRequest.jsp] Parameters: "); String pname; String pvalue; while (paraNames.hasMoreElements()) { pname = (String) paraNames.nextElement(); pvalue = request.getParameter(pname); out.println("[parseRequest.jsp] " + pname + " = " + pvalue); logger.debug("[parseRequest.jsp] " + pname + " = " + pvalue); if (pname.equals("jufinal")) { bLastChunk = pvalue.equals("1"); } else if (pname.equals("jupart")) { numChunk = Integer.parseInt(pvalue); } if (pname.equals("error") && pvalue.equals("true")) { generateError = true; logger.debug( "For debug convenience, putting error=true as a URL parameter, will generate an error in this response."); } if (pname.equals("warning") && pvalue.equals("true")) { generateWarning = true; logger.debug( "For debug convenience, putting warning=true as a URL parameter, will generate a warning in this response."); } if (pname.equals("sendRequest") && pvalue.equals("true")) { sendRequest = true; logger.debug( "For debug convenience, putting readRequest=true as a URL parameter, will send back the request content into the response of this page."); } } out.println("[parseRequest.jsp] ------------------------------ "); int ourMaxMemorySize = 10000000; int ourMaxRequestSize = 2000000000; /////////////////////////////////////////////////////////////////////////////////////////////////////// //The code below is directly taken from the jakarta fileupload common classes //All informations, and download, available here : http://jakarta.apache.org/commons/fileupload/ /////////////////////////////////////////////////////////////////////////////////////////////////////// logger.debug(" Create a factory for disk-based file items"); DiskFileItemFactory factory = new DiskFileItemFactory(); logger.debug(" Set factory constraints"); factory.setSizeThreshold(ourMaxMemorySize); logger.debug("ourTempDirectory" + ourTempDirectory); factory.setRepository(new File(ourTempDirectory)); logger.debug(" Create a new file upload handler"); ServletFileUpload upload = new ServletFileUpload(factory); logger.debug(" Set overall request size constraint"); upload.setSizeMax(ourMaxRequestSize); logger.debug(" Parse the request"); if (sendRequest) { logger.debug("For debug only. Should be removed for production systems. "); out.println( "[parseRequest.jsp] ==========================================================================="); out.println("[parseRequest.jsp] Sending the received request content: "); logger.debug("[parseRequest.jsp] Sending the received request content: "); InputStream is = request.getInputStream(); int c; while ((c = is.read()) >= 0) { out.write(c); } logger.debug("while"); is.close(); out.println( "[parseRequest.jsp] ==========================================================================="); } else if (!request.getContentType().startsWith("multipart/form-data")) { out.println("[parseRequest.jsp] No parsing of uploaded file: content type is " + request.getContentType()); } else { List /* FileItem */ items = upload.parseRequest(request); logger.debug(" Process the uploaded items" + items.size()); Iterator iter = items.iterator(); FileItem fileItem; File fout; out.println("[parseRequest.jsp] Let's read the sent data (" + items.size() + " items)"); while (iter.hasNext()) { fileItem = (FileItem) iter.next(); if (fileItem.isFormField()) { out.println("[parseRequest.jsp] (form field) " + fileItem.getFieldName() + " = " + fileItem.getString()); logger.debug( "If we receive the md5sum parameter, we've read finished to read the current file. It's not"); logger.debug( "a very good (end of file) signal. Will be better in the future ... probably !"); logger.debug("Let's put a separator, to make output easier to read."); if (fileItem.getFieldName().equals("md5sum[]")) { out.println("[parseRequest.jsp] ------------------------------ "); } } else { logger.debug("Ok, we've got a file. Let's process it."); logger.debug("Again, for all informations of what is exactly a FileItem, please"); logger.debug("have a look to http://jakarta.apache.org/commons/fileupload/"); out.println("[parseRequest.jsp] FieldName: " + fileItem.getFieldName()); out.println("[parseRequest.jsp] File Name: " + fileItem.getName()); out.println("[parseRequest.jsp] ContentType: " + fileItem.getContentType()); out.println("[parseRequest.jsp] Size (Bytes): " + fileItem.getSize()); logger.debug( "If we are in chunk mode, we add .partN at the end of the file, where N is the chunk number."); String uploadedFilename = fileItem.getName() + (numChunk > 0 ? ".part" + numChunk : ""); fout = new File(ourTempDirectory + (new File(uploadedFilename)).getName()); out.println("[parseRequest.jsp] File Out: " + fout.toString()); logger.debug(" write the file"); fileItem.write(fout); // logger.debug("Chunk management: if it was the last chunk, let's recover the complete file"); logger.debug("by concatenating all chunk parts."); logger.debug(""); if (bLastChunk) { out.println("[parseRequest.jsp] Last chunk received: let's rebuild the complete file (" + fileItem.getName() + ")"); logger.debug("First: construct the final filename."); FileInputStream fis; FileOutputStream fos = new FileOutputStream(ourTempDirectory + fileItem.getName()); int nbBytes; byte[] byteBuff = new byte[1024]; String filename; for (int i = 1; i <= numChunk; i += 1) { filename = fileItem.getName() + ".part" + i; out.println("[parseRequest.jsp] " + " Concatenating " + filename); fis = new FileInputStream(ourTempDirectory + filename); while ((nbBytes = fis.read(byteBuff)) >= 0) { //out.println("[parseRequest.jsp] " + " Nb bytes read: " + nbBytes); fos.write(byteBuff, 0, nbBytes); } fis.close(); } fos.close(); } logger.debug(" End of chunk management"); // fileItem.delete(); } } logger.debug("while"); } if (generateWarning) { out.println("WARNING: just a warning message.\\nOn two lines!"); } out.println("[parseRequest.jsp] " + "Let's write a status, to finish the server response :"); logger.debug("Let's wait a little, to simulate the server time to manage the file."); Thread.sleep(500); logger.debug("Do you want to test a successful upload, or the way the applet reacts to an error ?"); if (generateError) { out.println( "ERROR: this is a test error (forced in /wwwroot/pages/parseRequest.jsp).\\nHere is a second line!"); } else { out.println("SUCCESS"); logger.debug(""); } out.println("[parseRequest.jsp] " + "End of server treatment "); } catch (Exception e) { out.println(""); out.println("ERROR: Exception e = " + e.toString()); out.println(""); } }
From source file:CourseFileManagementSystem.Upload.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); out.write("<html><head></head><body>"); // Check that we have a file upload request if (!ServletFileUpload.isMultipartContent(request)) { // if not, we stop here PrintWriter writer = response.getWriter(); writer.println("Error: Form must has enctype=multipart/form-data."); writer.flush();/*from w ww . j av a2 s . c om*/ return; } // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Sets the size threshold beyond which files are written directly to // disk. factory.setSizeThreshold(MAX_MEMORY_SIZE); // Sets the directory used to temporarily store files that are larger // than the configured size threshold. We use temporary directory for // java factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); // constructs the folder where uploaded file will be stored String temp_folder = " "; try { String dataFolder = getServletContext().getRealPath("") + File.separator + DATA_DIRECTORY; temp_folder = dataFolder; File uploadD = new File(dataFolder); if (!uploadD.exists()) { uploadD.mkdir(); } ResultList rs5 = DB.query( "SELECT * FROM course AS c, section AS s, year_semester AS ys, upload_checklist AS uc WHERE s.courseCode = c.courseCode " + "AND s.semesterID = ys.semesterID AND s.courseID = c.courseID AND s.sectionID=" + sectionID); rs5.next(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Sets maximum size of upload file upload.setFileSizeMax(MAX_FILE_SIZE); // Set overall request size constraint upload.setSizeMax(MAX_REQUEST_SIZE); // creates the directory if it does not exist String path1 = getServletContext().getContextPath() + "/" + DATA_DIRECTORY + "/"; String temp_semester = rs5.getString("year") + "-" + rs5.getString("semester"); String real_path = temp_folder + File.separator + temp_semester; File semester = new File(real_path); if (!semester.exists()) { semester.mkdir(); } path1 += temp_semester + "/"; real_path += File.separator; String temp_course = rs5.getString("courseCode") + rs5.getString("courseID") + "-" + rs5.getString("courseName"); String real_path1 = real_path + temp_course; File course = new File(real_path1); if (!course.exists()) { course.mkdir(); } path1 += temp_course + "/"; real_path1 += File.separator; String temp_section = "section-" + rs5.getString("sectionNo"); String real_path2 = real_path1 + temp_section; File section = new File(real_path2); if (!section.exists()) { section.mkdir(); } path1 += temp_section + "/"; real_path2 += File.separator; String sectionPath = path1; // Parse the request List<FileItem> items = upload.parseRequest(request); if (items != null && items.size() > 0) { // iterates over form's fields for (FileItem item : items) { // processes only fields that are not form fields if (!item.isFormField() && !item.getName().equals("")) { String DBPath = ""; System.out.println(item.getName() + " file is for " + item.getFieldName()); Scanner field_name = new Scanner(item.getFieldName()).useDelimiter("[^0-9]+"); int id = field_name.nextInt(); fileName = new File(item.getName()).getName(); ResultList rs = DB.query("SELECT * FROM upload_checklist WHERE checklistID =" + id); rs.next(); String temp_file = rs.getString("label"); String real_path3 = real_path2 + temp_file; File file_type = new File(real_path3); if (!file_type.exists()) file_type.mkdir(); DBPath = sectionPath + "/" + temp_file + "/"; String context_path = DBPath; real_path3 += File.separator; String filePath = real_path3 + fileName; DBPath += fileName; String temp_DBPath = DBPath; int count = 0; File f = new File(filePath); String temp_fileName = f.getName(); String fileNameWithOutExt = FilenameUtils.removeExtension(temp_fileName); String extension = FilenameUtils.getExtension(filePath); String newFullPath = filePath; String tempFileName = " "; while (f.exists()) { ++count; tempFileName = fileNameWithOutExt + "_(" + count + ")."; newFullPath = real_path3 + tempFileName + extension; temp_DBPath = context_path + tempFileName + extension; f = new File(newFullPath); } filePath = newFullPath; System.out.println("New path: " + filePath); DBPath = temp_DBPath; String changeFilePath = filePath.replace('/', '\\'); String changeFilePath1 = changeFilePath.replace("Course_File_Management_System\\", ""); File uploadedFile = new File(changeFilePath1); System.out.println("Change filepath = " + changeFilePath1); System.out.println("DBPath = " + DBPath); // saves the file to upload directory item.write(uploadedFile); String query = "INSERT INTO files (fileDirectory) values('" + DBPath + "')"; DB.update(query); ResultList rs3 = DB.query("SELECT label FROM upload_checklist WHERE id=" + id); while (rs3.next()) { String label = rs3.getString("label"); out.write("<a href=\"Upload?fileName=" + changeFilePath1 + "\">Download " + label + "</a>"); out.write("<br><br>"); } ResultList rs4 = DB.query("SELECT * FROM files ORDER BY fileID DESC LIMIT 1"); rs4.next(); String query2 = "INSERT INTO lecturer_upload (fileID, sectionID, checklistID) values(" + rs4.getString("fileID") + ", " + sectionID + ", " + id + ")"; DB.update(query2); } } } } catch (FileUploadException ex) { throw new ServletException(ex); } catch (Exception ex) { throw new ServletException(ex); } response.sendRedirect(request.getHeader("Referer")); }
From source file:de.ingrid.portal.portlets.ContactPortlet.java
public void processAction(ActionRequest request, ActionResponse actionResponse) throws PortletException, IOException { List<FileItem> items = null; File uploadFile = null;/* w w w. j a va2 s.c om*/ boolean uploadEnable = PortalConfig.getInstance().getBoolean(PortalConfig.PORTAL_CONTACT_UPLOAD_ENABLE, Boolean.FALSE); int uploadSize = PortalConfig.getInstance().getInt(PortalConfig.PORTAL_CONTACT_UPLOAD_SIZE, 10); RequestContext requestContext = (RequestContext) request.getAttribute(RequestContext.REQUEST_PORTALENV); HttpServletRequest servletRequest = requestContext.getRequest(); if (ServletFileUpload.isMultipartContent(servletRequest)) { DiskFileItemFactory factory = new DiskFileItemFactory(); // Set factory constraints factory.setSizeThreshold(uploadSize * 1000 * 1000); File file = new File("."); factory.setRepository(file); ServletFileUpload.isMultipartContent(servletRequest); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(uploadSize * 1000 * 1000); // Parse the request try { items = upload.parseRequest(servletRequest); } catch (FileUploadException e) { // TODO Auto-generated catch block } } if (items != null) { // check form input if (request.getParameter(PARAMV_ACTION_DB_DO_REFRESH) != null) { ContactForm cf = (ContactForm) Utils.getActionForm(request, ContactForm.SESSION_KEY, ContactForm.class); cf.populate(items); String urlViewParam = "?" + Utils.toURLParam(Settings.PARAM_ACTION, Settings.MSGV_TRUE); actionResponse.sendRedirect(actionResponse.encodeURL(Settings.PAGE_CONTACT + urlViewParam)); return; } else { Boolean isResponseCorrect = false; ContactForm cf = (ContactForm) Utils.getActionForm(request, ContactForm.SESSION_KEY, ContactForm.class); cf.populate(items); if (!cf.validate()) { // add URL parameter indicating that portlet action was called // before render request String urlViewParam = "?" + Utils.toURLParam(Settings.PARAM_ACTION, Settings.MSGV_TRUE); actionResponse.sendRedirect(actionResponse.encodeURL(Settings.PAGE_CONTACT + urlViewParam)); return; } //remenber that we need an id to validate! String sessionId = request.getPortletSession().getId(); //retrieve the response boolean enableCaptcha = PortalConfig.getInstance().getBoolean("portal.contact.enable.captcha", Boolean.TRUE); if (enableCaptcha) { String response = request.getParameter("jcaptcha"); for (FileItem item : items) { if (item.getFieldName() != null) { if (item.getFieldName().equals("jcaptcha")) { response = item.getString(); break; } } } // Call the Service method try { isResponseCorrect = CaptchaServiceSingleton.getInstance().validateResponseForID(sessionId, response); } catch (CaptchaServiceException e) { //should not happen, may be thrown if the id is not valid } } if (isResponseCorrect || !enableCaptcha) { try { IngridResourceBundle messages = new IngridResourceBundle( getPortletConfig().getResourceBundle(request.getLocale()), request.getLocale()); HashMap mailData = new HashMap(); mailData.put("user.name.given", cf.getInput(ContactForm.FIELD_FIRSTNAME)); mailData.put("user.name.family", cf.getInput(ContactForm.FIELD_LASTNAME)); mailData.put("user.employer", cf.getInput(ContactForm.FIELD_COMPANY)); mailData.put("user.business-info.telecom.telephone", cf.getInput(ContactForm.FIELD_PHONE)); mailData.put("user.business-info.online.email", cf.getInput(ContactForm.FIELD_EMAIL)); mailData.put("user.area.of.profession", messages.getString("contact.report.email.area.of.profession." + cf.getInput(ContactForm.FIELD_ACTIVITY))); mailData.put("user.interest.in.enviroment.info", messages.getString("contact.report.email.interest.in.enviroment.info." + cf.getInput(ContactForm.FIELD_INTEREST))); if (cf.hasInput(ContactForm.FIELD_NEWSLETTER)) { Session session = HibernateUtil.currentSession(); Transaction tx = null; try { mailData.put("user.subscribed.to.newsletter", "yes"); // check for email address in newsletter list tx = session.beginTransaction(); List newsletterDataList = session.createCriteria(IngridNewsletterData.class) .add(Restrictions.eq("emailAddress", cf.getInput(ContactForm.FIELD_EMAIL))) .list(); tx.commit(); // register for newsletter if not already registered if (newsletterDataList.isEmpty()) { IngridNewsletterData data = new IngridNewsletterData(); data.setFirstName(cf.getInput(ContactForm.FIELD_FIRSTNAME)); data.setLastName(cf.getInput(ContactForm.FIELD_LASTNAME)); data.setEmailAddress(cf.getInput(ContactForm.FIELD_EMAIL)); data.setDateCreated(new Date()); tx = session.beginTransaction(); session.save(data); tx.commit(); } } catch (Throwable t) { if (tx != null) { tx.rollback(); } throw new PortletException(t.getMessage()); } finally { HibernateUtil.closeSession(); } } else { mailData.put("user.subscribed.to.newsletter", "no"); } mailData.put("message.body", cf.getInput(ContactForm.FIELD_MESSAGE)); Locale locale = request.getLocale(); String language = locale.getLanguage(); String localizedTemplatePath = EMAIL_TEMPLATE; int period = localizedTemplatePath.lastIndexOf("."); if (period > 0) { String fixedTempl = localizedTemplatePath.substring(0, period) + "_" + language + "." + localizedTemplatePath.substring(period + 1); if (new File(getPortletContext().getRealPath(fixedTempl)).exists()) { localizedTemplatePath = fixedTempl; } } String emailSubject = messages.getString("contact.report.email.subject"); if (PortalConfig.getInstance().getBoolean("email.contact.subject.add.topic", Boolean.FALSE)) { if (cf.getInput(ContactForm.FIELD_ACTIVITY) != null && !cf.getInput(ContactForm.FIELD_ACTIVITY).equals("none")) { emailSubject = emailSubject + " - " + messages.getString("contact.report.email.area.of.profession." + cf.getInput(ContactForm.FIELD_ACTIVITY)); } } String from = cf.getInput(ContactForm.FIELD_EMAIL); String to = PortalConfig.getInstance().getString(PortalConfig.EMAIL_CONTACT_FORM_RECEIVER, "foo@bar.com"); String text = Utils.mergeTemplate(getPortletConfig(), mailData, "map", localizedTemplatePath); if (uploadEnable) { if (uploadEnable) { for (FileItem item : items) { if (item.getFieldName() != null) { if (item.getFieldName().equals("upload")) { uploadFile = new File(sessionId + "_" + item.getName()); // read this file into InputStream InputStream inputStream = item.getInputStream(); // write the inputStream to a FileOutputStream OutputStream out = new FileOutputStream(uploadFile); int read = 0; byte[] bytes = new byte[1024]; while ((read = inputStream.read(bytes)) != -1) { out.write(bytes, 0, read); } inputStream.close(); out.flush(); out.close(); break; } } } } Utils.sendEmail(from, emailSubject, new String[] { to }, text, null, uploadFile); } else { Utils.sendEmail(from, emailSubject, new String[] { to }, text, null); } } catch (Throwable t) { cf.setError("", "Error sending mail from contact form."); log.error("Error sending mail from contact form.", t); } // temporarily show same page with content String urlViewParam = "?" + Utils.toURLParam(Settings.PARAM_ACTION, PARAMV_ACTION_SUCCESS); actionResponse.sendRedirect(actionResponse.encodeURL(Settings.PAGE_CONTACT + urlViewParam)); } else { cf.setErrorCaptcha(); String urlViewParam = "?" + Utils.toURLParam(Settings.PARAM_ACTION, Settings.MSGV_TRUE); actionResponse.sendRedirect(actionResponse.encodeURL(Settings.PAGE_CONTACT + urlViewParam)); return; } } } else { ContactForm cf = (ContactForm) Utils.getActionForm(request, ContactForm.SESSION_KEY, ContactForm.class); cf.setErrorUpload(); String urlViewParam = "?" + Utils.toURLParam(Settings.PARAM_ACTION, Settings.MSGV_TRUE); actionResponse.sendRedirect(actionResponse.encodeURL(Settings.PAGE_CONTACT + urlViewParam)); return; } }
From source file:com.liferay.faces.bridge.context.map.internal.MultiPartFormDataProcessorImpl.java
@Override public Map<String, List<UploadedFile>> process(ClientDataRequest clientDataRequest, PortletConfig portletConfig, FacesRequestParameterMap facesRequestParameterMap) { Map<String, List<UploadedFile>> uploadedFileMap = null; PortletSession portletSession = clientDataRequest.getPortletSession(); String uploadedFilesDir = PortletConfigParam.UploadedFilesDir.getStringValue(portletConfig); // Using the portlet sessionId, determine a unique folder path and create the path if it does not exist. String sessionId = portletSession.getId(); // FACES-1452: Non-alpha-numeric characters must be removed order to ensure that the folder will be // created properly. sessionId = sessionId.replaceAll("[^A-Za-z0-9]", StringPool.BLANK); File uploadedFilesPath = new File(uploadedFilesDir, sessionId); if (!uploadedFilesPath.exists()) { uploadedFilesPath.mkdirs();/*from w w w .j a v a2s .c om*/ } // Initialize commons-fileupload with the file upload path. DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setRepository(uploadedFilesPath); // Initialize commons-fileupload so that uploaded temporary files are not automatically deleted. diskFileItemFactory.setFileCleaningTracker(null); // Initialize the commons-fileupload size threshold to zero, so that all files will be dumped to disk // instead of staying in memory. diskFileItemFactory.setSizeThreshold(0); // Determine the max file upload size threshold (in bytes). long uploadedFileMaxSize = PortletConfigParam.UploadedFileMaxSize.getLongValue(portletConfig); // Parse the request parameters and save all uploaded files in a map. PortletFileUpload portletFileUpload = new PortletFileUpload(diskFileItemFactory); portletFileUpload.setFileSizeMax(uploadedFileMaxSize); uploadedFileMap = new HashMap<String, List<UploadedFile>>(); // FACES-271: Include name+value pairs found in the ActionRequest. Set<Map.Entry<String, String[]>> actionRequestParameterSet = clientDataRequest.getParameterMap().entrySet(); for (Map.Entry<String, String[]> mapEntry : actionRequestParameterSet) { String parameterName = mapEntry.getKey(); String[] parameterValues = mapEntry.getValue(); if (parameterValues.length > 0) { for (String parameterValue : parameterValues) { facesRequestParameterMap.addValue(parameterName, parameterValue); } } } UploadedFileFactory uploadedFileFactory = (UploadedFileFactory) BridgeFactoryFinder .getFactory(UploadedFileFactory.class); // Begin parsing the request for file parts: try { FileItemIterator fileItemIterator = null; if (clientDataRequest instanceof ResourceRequest) { ResourceRequest resourceRequest = (ResourceRequest) clientDataRequest; fileItemIterator = portletFileUpload.getItemIterator(new ActionRequestAdapter(resourceRequest)); } else { ActionRequest actionRequest = (ActionRequest) clientDataRequest; fileItemIterator = portletFileUpload.getItemIterator(actionRequest); } if (fileItemIterator != null) { int totalFiles = 0; String namespace = facesRequestParameterMap.getNamespace(); // For each field found in the request: while (fileItemIterator.hasNext()) { try { totalFiles++; // Get the stream of field data from the request. FileItemStream fieldStream = (FileItemStream) fileItemIterator.next(); // Get field name from the field stream. String fieldName = fieldStream.getFieldName(); // Get the content-type, and file-name from the field stream. String contentType = fieldStream.getContentType(); boolean formField = fieldStream.isFormField(); String fileName = null; try { fileName = fieldStream.getName(); } catch (InvalidFileNameException e) { fileName = e.getName(); } // Copy the stream of file data to a temporary file. NOTE: This is necessary even if the // current field is a simple form-field because the call below to diskFileItem.getString() // will fail otherwise. DiskFileItem diskFileItem = (DiskFileItem) diskFileItemFactory.createItem(fieldName, contentType, formField, fileName); Streams.copy(fieldStream.openStream(), diskFileItem.getOutputStream(), true); // If the current field is a simple form-field, then save the form field value in the map. if (diskFileItem.isFormField()) { String characterEncoding = clientDataRequest.getCharacterEncoding(); String requestParameterValue = null; if (characterEncoding == null) { requestParameterValue = diskFileItem.getString(); } else { requestParameterValue = diskFileItem.getString(characterEncoding); } facesRequestParameterMap.addValue(fieldName, requestParameterValue); } else { File tempFile = diskFileItem.getStoreLocation(); // If the copy was successful, then if (tempFile.exists()) { // Copy the commons-fileupload temporary file to a file in the same temporary // location, but with the filename provided by the user in the upload. This has two // benefits: 1) The temporary file will have a nice meaningful name. 2) By copying // the file, the developer can have access to a semi-permanent file, because the // commmons-fileupload DiskFileItem.finalize() method automatically deletes the // temporary one. String tempFileName = tempFile.getName(); String tempFileAbsolutePath = tempFile.getAbsolutePath(); String copiedFileName = stripIllegalCharacters(fileName); String copiedFileAbsolutePath = tempFileAbsolutePath.replace(tempFileName, copiedFileName); File copiedFile = new File(copiedFileAbsolutePath); FileUtils.copyFile(tempFile, copiedFile); // If present, build up a map of headers. Map<String, List<String>> headersMap = new HashMap<String, List<String>>(); FileItemHeaders fileItemHeaders = fieldStream.getHeaders(); if (fileItemHeaders != null) { Iterator<String> headerNameItr = fileItemHeaders.getHeaderNames(); if (headerNameItr != null) { while (headerNameItr.hasNext()) { String headerName = headerNameItr.next(); Iterator<String> headerValuesItr = fileItemHeaders .getHeaders(headerName); List<String> headerValues = new ArrayList<String>(); if (headerValuesItr != null) { while (headerValuesItr.hasNext()) { String headerValue = headerValuesItr.next(); headerValues.add(headerValue); } } headersMap.put(headerName, headerValues); } } } // Put a valid UploadedFile instance into the map that contains all of the // uploaded file's attributes, along with a successful status. Map<String, Object> attributeMap = new HashMap<String, Object>(); String id = Long.toString(((long) hashCode()) + System.currentTimeMillis()); String message = null; UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile( copiedFileAbsolutePath, attributeMap, diskFileItem.getCharSet(), diskFileItem.getContentType(), headersMap, id, message, fileName, diskFileItem.getSize(), UploadedFile.Status.FILE_SAVED); facesRequestParameterMap.addValue(fieldName, copiedFileAbsolutePath); addUploadedFile(uploadedFileMap, fieldName, uploadedFile); logger.debug("Received uploaded file fieldName=[{0}] fileName=[{1}]", fieldName, fileName); } else { if ((fileName != null) && (fileName.trim().length() > 0)) { Exception e = new IOException("Failed to copy the stream of uploaded file=[" + fileName + "] to a temporary file (possibly a zero-length uploaded file)"); UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e); addUploadedFile(uploadedFileMap, fieldName, uploadedFile); } } } } catch (Exception e) { logger.error(e); UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e); String fieldName = Integer.toString(totalFiles); addUploadedFile(uploadedFileMap, fieldName, uploadedFile); } } } } // If there was an error in parsing the request for file parts, then put a bogus UploadedFile instance in // the map so that the developer can have some idea that something went wrong. catch (Exception e) { logger.error(e); UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e); addUploadedFile(uploadedFileMap, "unknown", uploadedFile); } return uploadedFileMap; }
From source file:com.example.web.Update_profile.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ String fileName = ""; int f = 0; String user = null;//www .j a v a 2 s. c o m Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals("user")) { user = cookie.getValue(); } } } String email = request.getParameter("email"); String First_name = request.getParameter("First_name"); String Last_name = request.getParameter("Last_name"); String Phone_number_1 = request.getParameter("Phone_number_1"); String Address = request.getParameter("Address"); String message = ""; int valid = 1; String query; ResultSet rs; Connection conn; String url = "jdbc:mysql://localhost:3306/"; String dbName = "tworld"; String driver = "com.mysql.jdbc.Driver"; isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. //factory.setRepository(new File("/var/lib/tomcat7/webapps/www_term_project/temp/")); factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); try { // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); fileName = fi.getName(); String contentType = fi.getContentType(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); String[] spliting = fileName.split("\\."); // Write the file System.out.println(sizeInBytes + " " + maxFileSize); System.out.println(spliting[spliting.length - 1]); if (!fileName.equals("")) { if ((sizeInBytes < maxFileSize) && (spliting[spliting.length - 1].equals("jpg") || spliting[spliting.length - 1].equals("png") || spliting[spliting.length - 1].equals("jpeg"))) { if (fileName.lastIndexOf("\\") >= 0) { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\"))); } else { file = new File( filePath + fileName.substring(fileName.lastIndexOf("\\") + 1)); } fi.write(file); System.out.println("Uploaded Filename: " + fileName + "<br>"); } else { valid = 0; message = "not a valid image"; } } } BufferedReader br = null; StringBuilder sb = new StringBuilder(); String line; try { br = new BufferedReader(new InputStreamReader(fi.getInputStream())); while ((line = br.readLine()) != null) { sb.append(line); } } catch (IOException e) { } finally { if (br != null) { try { br.close(); } catch (IOException e) { } } } if (f == 0) { email = sb.toString(); } else if (f == 1) { First_name = sb.toString(); } else if (f == 2) { Last_name = sb.toString(); } else if (f == 3) { Phone_number_1 = sb.toString(); } else if (f == 4) { Address = sb.toString(); } f++; } } catch (Exception ex) { System.out.println("hi"); System.out.println(ex); } } try { Class.forName(driver).newInstance(); conn = DriverManager.getConnection(url + dbName, "admin", "admin"); if (!email.equals("")) { PreparedStatement pst = (PreparedStatement) conn .prepareStatement("update `tworld`.`users` set `email`=? where `Username`=?"); pst.setString(1, email); pst.setString(2, user); pst.executeUpdate(); pst.close(); } if (!First_name.equals("")) { PreparedStatement pst = (PreparedStatement) conn .prepareStatement("update `tworld`.`users` set `First_name`=? where `Username`=?"); pst.setString(1, First_name); pst.setString(2, user); pst.executeUpdate(); pst.close(); } if (!Last_name.equals("")) { PreparedStatement pst = (PreparedStatement) conn .prepareStatement("update `tworld`.`users` set `Last_name`=? where `Username`=?"); pst.setString(1, Last_name); pst.setString(2, user); pst.executeUpdate(); pst.close(); } if (!Phone_number_1.equals("")) { PreparedStatement pst = (PreparedStatement) conn .prepareStatement("update `tworld`.`users` set `Phone_number_1`=? where `Username`=?"); pst.setString(1, Phone_number_1); pst.setString(2, user); pst.executeUpdate(); pst.close(); } if (!Address.equals("")) { PreparedStatement pst = (PreparedStatement) conn .prepareStatement("update `tworld`.`users` set `Address`=? where `Username`=?"); pst.setString(1, Address); pst.setString(2, user); pst.executeUpdate(); pst.close(); } if (!fileName.equals("")) { PreparedStatement pst = (PreparedStatement) conn .prepareStatement("update `tworld`.`users` set `Fototitle`=? where `Username`=?"); pst.setString(1, fileName); pst.setString(2, user); pst.executeUpdate(); pst.close(); } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException ex) { System.out.println("hi mom"); } request.setAttribute("s_page", "4"); request.getRequestDispatcher("/index.jsp").forward(request, response); } }
From source file:com.mx.nibble.middleware.web.util.FileParse.java
public String execute(ActionInvocation invocation) throws Exception { Iterator iterator = parameters.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry mapEntry = (Map.Entry) iterator.next(); System.out.println("The key is: " + mapEntry.getKey() + ",value is :" + mapEntry.getValue()); }//from ww w . jav a 2s. c o m ActionContext ac = invocation.getInvocationContext(); HttpServletRequest request = (HttpServletRequest) ac.get(ServletActionContext.HTTP_REQUEST); HttpServletResponse response = (HttpServletResponse) ac.get(ServletActionContext.HTTP_RESPONSE); /** * This pages gives a sample of java upload management. It needs the commons FileUpload library, which can be found on apache.org. * * Note: * - putting error=true as a parameter on the URL will generate an error. Allows test of upload error management in the applet. * * * * * * */ // Directory to store all the uploaded files String ourTempDirectory = "/opt/erp/import/obras/"; byte[] cr = { 13 }; byte[] lf = { 10 }; String CR = new String(cr); String LF = new String(lf); String CRLF = CR + LF; System.out.println("Before a LF=chr(10)" + LF + "Before a CR=chr(13)" + CR + "Before a CRLF" + CRLF); //Initialization for chunk management. boolean bLastChunk = false; int numChunk = 0; //CAN BE OVERRIDEN BY THE postURL PARAMETER: if error=true is passed as a parameter on the URL boolean generateError = false; boolean generateWarning = false; boolean sendRequest = false; response.setContentType("text/plain"); java.util.Enumeration<String> headers = request.getHeaderNames(); System.out.println("[parseRequest.jsp] ------------------------------ "); System.out.println("[parseRequest.jsp] Headers of the received request:"); while (headers.hasMoreElements()) { String header = headers.nextElement(); System.out.println("[parseRequest.jsp] " + header + ": " + request.getHeader(header)); } System.out.println("[parseRequest.jsp] ------------------------------ "); try { // Get URL Parameters. Enumeration paraNames = request.getParameterNames(); System.out.println("[parseRequest.jsp] ------------------------------ "); System.out.println("[parseRequest.jsp] Parameters: "); String pname; String pvalue; while (paraNames.hasMoreElements()) { pname = (String) paraNames.nextElement(); pvalue = request.getParameter(pname); System.out.println("[parseRequest.jsp] " + pname + " = " + pvalue); if (pname.equals("jufinal")) { bLastChunk = pvalue.equals("1"); } else if (pname.equals("jupart")) { numChunk = Integer.parseInt(pvalue); } //For debug convenience, putting error=true as a URL parameter, will generate an error //in this response. if (pname.equals("error") && pvalue.equals("true")) { generateError = true; } //For debug convenience, putting warning=true as a URL parameter, will generate a warning //in this response. if (pname.equals("warning") && pvalue.equals("true")) { generateWarning = true; } //For debug convenience, putting readRequest=true as a URL parameter, will send back the request content //into the response of this page. if (pname.equals("sendRequest") && pvalue.equals("true")) { sendRequest = true; } } System.out.println("[parseRequest.jsp] ------------------------------ "); int ourMaxMemorySize = 10000000; int ourMaxRequestSize = 2000000000; /////////////////////////////////////////////////////////////////////////////////////////////////////// //The code below is directly taken from the jakarta fileupload common classes //All informations, and download, available here : http://jakarta.apache.org/commons/fileupload/ /////////////////////////////////////////////////////////////////////////////////////////////////////// // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Set factory constraints factory.setSizeThreshold(ourMaxMemorySize); factory.setRepository(new File(ourTempDirectory)); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(ourMaxRequestSize); // Parse the request if (sendRequest) { //For debug only. Should be removed for production systems. System.out.println( "[parseRequest.jsp] ==========================================================================="); System.out.println("[parseRequest.jsp] Sending the received request content: "); InputStream is = request.getInputStream(); int c; while ((c = is.read()) >= 0) { out.write(c); } //while is.close(); System.out.println( "[parseRequest.jsp] ==========================================================================="); } else if (!request.getContentType().startsWith("multipart/form-data")) { System.out.println("[parseRequest.jsp] No parsing of uploaded file: content type is " + request.getContentType()); } else { List /* FileItem */ items = upload.parseRequest(request); // Process the uploaded items Iterator iter = items.iterator(); FileItem fileItem; File fout; System.out.println("[parseRequest.jsp] Let's read the sent data (" + items.size() + " items)"); while (iter.hasNext()) { fileItem = (FileItem) iter.next(); if (fileItem.isFormField()) { System.out.println("[parseRequest.jsp] (form field) " + fileItem.getFieldName() + " = " + fileItem.getString()); //If we receive the md5sum parameter, we've read finished to read the current file. It's not //a very good (end of file) signal. Will be better in the future ... probably ! //Let's put a separator, to make output easier to read. if (fileItem.getFieldName().equals("md5sum[]")) { System.out.println("[parseRequest.jsp] ------------------------------ "); } } else { //Ok, we've got a file. Let's process it. //Again, for all informations of what is exactly a FileItem, please //have a look to http://jakarta.apache.org/commons/fileupload/ // System.out.println("[parseRequest.jsp] FieldName: " + fileItem.getFieldName()); System.out.println("[parseRequest.jsp] File Name: " + fileItem.getName()); System.out.println("[parseRequest.jsp] ContentType: " + fileItem.getContentType()); System.out.println("[parseRequest.jsp] Size (Bytes): " + fileItem.getSize()); //If we are in chunk mode, we add ".partN" at the end of the file, where N is the chunk number. String uploadedFilename = fileItem.getName() + (numChunk > 0 ? ".part" + numChunk : ""); fout = new File(ourTempDirectory + (new File(uploadedFilename)).getName()); System.out.println("[parseRequest.jsp] File Out: " + fout.toString()); // write the file fileItem.write(fout); ////////////////////////////////////////////////////////////////////////////////////// //Chunk management: if it was the last chunk, let's recover the complete file //by concatenating all chunk parts. // if (bLastChunk) { System.out.println( "[parseRequest.jsp] Last chunk received: let's rebuild the complete file (" + fileItem.getName() + ")"); //First: construct the final filename. FileInputStream fis; FileOutputStream fos = new FileOutputStream(ourTempDirectory + fileItem.getName()); int nbBytes; byte[] byteBuff = new byte[1024]; String filename; for (int i = 1; i <= numChunk; i += 1) { filename = fileItem.getName() + ".part" + i; System.out.println("[parseRequest.jsp] " + " Concatenating " + filename); fis = new FileInputStream(ourTempDirectory + filename); while ((nbBytes = fis.read(byteBuff)) >= 0) { //System.out.println("[parseRequest.jsp] " + " Nb bytes read: " + nbBytes); fos.write(byteBuff, 0, nbBytes); } fis.close(); } fos.close(); } // End of chunk management ////////////////////////////////////////////////////////////////////////////////////// fileItem.delete(); } } //while } if (generateWarning) { System.out.println("WARNING: just a warning message.\\nOn two lines!"); } System.out.println("[parseRequest.jsp] " + "Let's write a status, to finish the server response :"); //Let's wait a little, to simulate the server time to manage the file. Thread.sleep(500); //Do you want to test a successful upload, or the way the applet reacts to an error ? if (generateError) { System.out.println( "ERROR: this is a test error (forced in /wwwroot/pages/parseRequest.jsp).\\nHere is a second line!"); } else { System.out.println("SUCCESS"); PrintWriter out = ServletActionContext.getResponse().getWriter(); out.write("SUCCESS"); //System.out.println(" <span class=\"cpg_user_message\">Il y eu une erreur lors de l'excution de la requte</span>"); } System.out.println("[parseRequest.jsp] " + "End of server treatment "); } catch (Exception e) { System.out.println(""); System.out.println("ERROR: Exception e = " + e.toString()); System.out.println(""); } return SUCCESS; }
From source file:com.liferay.faces.bridge.context.map.MultiPartFormDataProcessorImpl.java
@Override public Map<String, Collection<UploadedFile>> process(ClientDataRequest clientDataRequest, PortletConfig portletConfig, FacesRequestParameterMap facesRequestParameterMap) { Map<String, Collection<UploadedFile>> uploadedFileMap = null; PortletSession portletSession = clientDataRequest.getPortletSession(); String uploadedFilesDir = PortletConfigParam.UploadedFilesDir.getStringValue(portletConfig); // Using the portlet sessionId, determine a unique folder path and create the path if it does not exist. String sessionId = portletSession.getId(); // FACES-1452: Non-alpha-numeric characters must be removed order to ensure that the folder will be // created properly. sessionId = sessionId.replaceAll("[^A-Za-z0-9]", StringPool.BLANK); File uploadedFilesPath = new File(uploadedFilesDir, sessionId); if (!uploadedFilesPath.exists()) { uploadedFilesPath.mkdirs();/*from w w w . ja v a 2 s. c o m*/ } // Initialize commons-fileupload with the file upload path. DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setRepository(uploadedFilesPath); // Initialize commons-fileupload so that uploaded temporary files are not automatically deleted. diskFileItemFactory.setFileCleaningTracker(null); // Initialize the commons-fileupload size threshold to zero, so that all files will be dumped to disk // instead of staying in memory. diskFileItemFactory.setSizeThreshold(0); // Determine the max file upload size threshold (in bytes). int uploadedFileMaxSize = PortletConfigParam.UploadedFileMaxSize.getIntegerValue(portletConfig); // Parse the request parameters and save all uploaded files in a map. PortletFileUpload portletFileUpload = new PortletFileUpload(diskFileItemFactory); portletFileUpload.setFileSizeMax(uploadedFileMaxSize); uploadedFileMap = new HashMap<String, Collection<UploadedFile>>(); // FACES-271: Include name+value pairs found in the ActionRequest. Set<Map.Entry<String, String[]>> actionRequestParameterSet = clientDataRequest.getParameterMap().entrySet(); for (Map.Entry<String, String[]> mapEntry : actionRequestParameterSet) { String parameterName = mapEntry.getKey(); String[] parameterValues = mapEntry.getValue(); if (parameterValues.length > 0) { for (String parameterValue : parameterValues) { facesRequestParameterMap.addValue(parameterName, parameterValue); } } } UploadedFileFactory uploadedFileFactory = (UploadedFileFactory) FactoryExtensionFinder .getFactory(UploadedFileFactory.class); // Begin parsing the request for file parts: try { FileItemIterator fileItemIterator = null; if (clientDataRequest instanceof ResourceRequest) { ResourceRequest resourceRequest = (ResourceRequest) clientDataRequest; fileItemIterator = portletFileUpload.getItemIterator(new ActionRequestAdapter(resourceRequest)); } else { ActionRequest actionRequest = (ActionRequest) clientDataRequest; fileItemIterator = portletFileUpload.getItemIterator(actionRequest); } boolean optimizeNamespace = PortletConfigParam.OptimizePortletNamespace.getBooleanValue(portletConfig); if (fileItemIterator != null) { int totalFiles = 0; String namespace = facesRequestParameterMap.getNamespace(); // For each field found in the request: while (fileItemIterator.hasNext()) { try { totalFiles++; // Get the stream of field data from the request. FileItemStream fieldStream = (FileItemStream) fileItemIterator.next(); // Get field name from the field stream. String fieldName = fieldStream.getFieldName(); // If namespace optimization is enabled and the namespace is present in the field name, // then remove the portlet namespace from the field name. if (optimizeNamespace) { int pos = fieldName.indexOf(namespace); if (pos >= 0) { fieldName = fieldName.substring(pos + namespace.length()); } } // Get the content-type, and file-name from the field stream. String contentType = fieldStream.getContentType(); boolean formField = fieldStream.isFormField(); String fileName = null; try { fileName = fieldStream.getName(); } catch (InvalidFileNameException e) { fileName = e.getName(); } // Copy the stream of file data to a temporary file. NOTE: This is necessary even if the // current field is a simple form-field because the call below to diskFileItem.getString() // will fail otherwise. DiskFileItem diskFileItem = (DiskFileItem) diskFileItemFactory.createItem(fieldName, contentType, formField, fileName); Streams.copy(fieldStream.openStream(), diskFileItem.getOutputStream(), true); // If the current field is a simple form-field, then save the form field value in the map. if (diskFileItem.isFormField()) { String characterEncoding = clientDataRequest.getCharacterEncoding(); String requestParameterValue = null; if (characterEncoding == null) { requestParameterValue = diskFileItem.getString(); } else { requestParameterValue = diskFileItem.getString(characterEncoding); } facesRequestParameterMap.addValue(fieldName, requestParameterValue); } else { File tempFile = diskFileItem.getStoreLocation(); // If the copy was successful, then if (tempFile.exists()) { // Copy the commons-fileupload temporary file to a file in the same temporary // location, but with the filename provided by the user in the upload. This has two // benefits: 1) The temporary file will have a nice meaningful name. 2) By copying // the file, the developer can have access to a semi-permanent file, because the // commmons-fileupload DiskFileItem.finalize() method automatically deletes the // temporary one. String tempFileName = tempFile.getName(); String tempFileAbsolutePath = tempFile.getAbsolutePath(); String copiedFileName = stripIllegalCharacters(fileName); String copiedFileAbsolutePath = tempFileAbsolutePath.replace(tempFileName, copiedFileName); File copiedFile = new File(copiedFileAbsolutePath); FileUtils.copyFile(tempFile, copiedFile); // If present, build up a map of headers. Map<String, List<String>> headersMap = new HashMap<String, List<String>>(); FileItemHeaders fileItemHeaders = fieldStream.getHeaders(); if (fileItemHeaders != null) { Iterator<String> headerNameItr = fileItemHeaders.getHeaderNames(); if (headerNameItr != null) { while (headerNameItr.hasNext()) { String headerName = headerNameItr.next(); Iterator<String> headerValuesItr = fileItemHeaders .getHeaders(headerName); List<String> headerValues = new ArrayList<String>(); if (headerValuesItr != null) { while (headerValuesItr.hasNext()) { String headerValue = headerValuesItr.next(); headerValues.add(headerValue); } } headersMap.put(headerName, headerValues); } } } // Put a valid UploadedFile instance into the map that contains all of the // uploaded file's attributes, along with a successful status. Map<String, Object> attributeMap = new HashMap<String, Object>(); String id = Long.toString(((long) hashCode()) + System.currentTimeMillis()); String message = null; UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile( copiedFileAbsolutePath, attributeMap, diskFileItem.getCharSet(), diskFileItem.getContentType(), headersMap, id, message, fileName, diskFileItem.getSize(), UploadedFile.Status.FILE_SAVED); facesRequestParameterMap.addValue(fieldName, copiedFileAbsolutePath); addUploadedFile(uploadedFileMap, fieldName, uploadedFile); logger.debug("Received uploaded file fieldName=[{0}] fileName=[{1}]", fieldName, fileName); } else { if ((fileName != null) && (fileName.trim().length() > 0)) { Exception e = new IOException("Failed to copy the stream of uploaded file=[" + fileName + "] to a temporary file (possibly a zero-length uploaded file)"); UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e); addUploadedFile(uploadedFileMap, fieldName, uploadedFile); } } } } catch (Exception e) { logger.error(e); UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e); String fieldName = Integer.toString(totalFiles); addUploadedFile(uploadedFileMap, fieldName, uploadedFile); } } } } // If there was an error in parsing the request for file parts, then put a bogus UploadedFile instance in // the map so that the developer can have some idea that something went wrong. catch (Exception e) { logger.error(e); UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e); addUploadedFile(uploadedFileMap, "unknown", uploadedFile); } return uploadedFileMap; }
From source file:com.aspectran.web.activity.request.multipart.MultipartFormDataParser.java
/** * Parse the given servlet request, resolving its multipart elements. * * @param requestAdapter the request adapter * @throws MultipartRequestException if multipart resolution failed *///from www . j ava2 s . c om public void parse(RequestAdapter requestAdapter) { try { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(DEFAULT_SIZE_THRESHOLD); if (temporaryFilePath != null) { File repository = new File(temporaryFilePath); if (!repository.exists() && !repository.mkdirs()) { throw new IllegalArgumentException( "Given temporaryFilePath [" + temporaryFilePath + "] could not be created."); } factory.setRepository(repository); } ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(maxRequestSize); upload.setHeaderEncoding(requestAdapter.getCharacterEncoding()); Map<String, List<FileItem>> fileItemListMap; try { RequestContext requestContext = createRequestContext(requestAdapter.getAdaptee()); fileItemListMap = upload.parseParameterMap(requestContext); } catch (SizeLimitExceededException e) { log.warn("Max length exceeded. multipart.maxRequestSize: " + maxRequestSize); requestAdapter.setMaxLengthExceeded(true); return; } parseMultipart(fileItemListMap, requestAdapter); } catch (Exception e) { throw new MultipartRequestException("Could not parse multipart servlet request.", e); } }
From source file:it.geosolutions.servicebox.FileUploadCallback.java
/** * Handle a POST request//from w w w. j ava2s . c om * * @param request * @param response * * @return CallbackResult * * @throws IOException */ @SuppressWarnings("unchecked") public ServiceBoxActionParameters onPost(HttpServletRequest request, HttpServletResponse response, ServiceBoxActionParameters callbackResult) throws IOException { // Get items if already initialized List<FileItem> items = null; if (callbackResult == null) { callbackResult = new ServiceBoxActionParameters(); } else { items = callbackResult.getItems(); } String temp = callbackConfiguration.getTempFolder(); int buffSize = callbackConfiguration.getBuffSize(); int itemSize = 0; long maxSize = 0; String itemName = null; boolean fileTypeMatch = true; File tempDir = new File(temp); try { if (items == null && ServletFileUpload.isMultipartContent(request) && tempDir != null && tempDir.exists()) { // items are not initialized. Read it from the request DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); /* * Set the size threshold, above which content will be stored on * disk. */ fileItemFactory.setSizeThreshold(buffSize); // 1 MB /* * Set the temporary directory to store the uploaded files of * size above threshold. */ fileItemFactory.setRepository(tempDir); ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); /* * Parse the request */ items = uploadHandler.parseRequest(request); } // Read items if (items != null) { itemSize = items.size(); callbackResult.setItems(items); if (itemSize <= this.callbackConfiguration.getMaxItems()) { // only if item size not exceeded max for (FileItem item : items) { itemName = item.getName(); if (item.getSize() > maxSize) { maxSize = item.getSize(); if (maxSize > this.callbackConfiguration.getMaxSize()) { // max size exceeded break; } else if (this.callbackConfiguration.getFileTypePatterns() != null) { fileTypeMatch = false; int index = 0; while (!fileTypeMatch && index < this.callbackConfiguration.getFileTypePatterns().size()) { Pattern pattern = this.callbackConfiguration.getFileTypePatterns().get(index++); fileTypeMatch = pattern.matcher(itemName).matches(); } if (!fileTypeMatch) { break; } } } } } } else { itemSize = 1; maxSize = request.getContentLength(); // TODO: Handle file type } } catch (Exception ex) { if (LOGGER.isLoggable(Level.SEVERE)) LOGGER.log(Level.SEVERE, "Error encountered while parsing the request"); response.setContentType("text/html"); JSONObject jsonObj = new JSONObject(); jsonObj.put("success", false); jsonObj.put("errorMessage", ex.getLocalizedMessage()); Utilities.writeResponse(response, jsonObj.toString(), LOGGER); } // prepare and send error if exists boolean error = false; int errorCode = -1; String message = null; Map<String, Object> errorDetails = null; if (itemSize > this.callbackConfiguration.getMaxItems()) { errorDetails = new HashMap<String, Object>(); error = true; errorDetails.put("expected", this.callbackConfiguration.getMaxItems()); errorDetails.put("found", itemSize); errorCode = Utilities.JSON_MODEL.KNOWN_ERRORS.MAX_ITEMS.ordinal(); message = "Max items size exceeded (expected: '" + this.callbackConfiguration.getMaxItems() + "', found: '" + itemSize + "')."; } else if (maxSize > this.callbackConfiguration.getMaxSize()) { errorDetails = new HashMap<String, Object>(); error = true; errorDetails.put("expected", this.callbackConfiguration.getMaxSize()); errorDetails.put("found", maxSize); errorDetails.put("item", itemName); errorCode = Utilities.JSON_MODEL.KNOWN_ERRORS.MAX_ITEM_SIZE.ordinal(); message = "Max item size exceeded (expected: '" + this.callbackConfiguration.getMaxSize() + "', found: '" + maxSize + "' on item '" + itemName + "')."; } else if (fileTypeMatch == false) { errorDetails = new HashMap<String, Object>(); error = true; String expected = this.callbackConfiguration.getFileTypes(); errorDetails.put("expected", expected); errorDetails.put("found", itemName); errorDetails.put("item", itemName); errorCode = Utilities.JSON_MODEL.KNOWN_ERRORS.ITEM_TYPE.ordinal(); message = "File type not maches with known file types: (expected: '" + expected + "', item '" + itemName + "')."; } if (error) { callbackResult.setSuccess(false); Utilities.writeError(response, errorCode, errorDetails, message, LOGGER); } else { callbackResult.setSuccess(true); } return callbackResult; }
From source file:com.aspectran.web.support.multipart.commons.CommonsMultipartFormDataParser.java
@Override public void parse(RequestAdapter requestAdapter) { try {//from w ww. j a v a 2s .c o m DiskFileItemFactory factory = new DiskFileItemFactory(); if (maxInMemorySize > -1) { factory.setSizeThreshold(maxInMemorySize); } if (tempDirectoryPath != null) { File repository = new File(tempDirectoryPath); if (!repository.exists() && !repository.mkdirs()) { throw new IllegalArgumentException( "Given tempDirectoryPath [" + tempDirectoryPath + "] could not be created"); } factory.setRepository(repository); } FileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding(requestAdapter.getEncoding()); if (maxRequestSize > -1L) { upload.setSizeMax(maxRequestSize); } if (maxFileSize > -1L) { upload.setFileSizeMax(maxFileSize); } Map<String, List<FileItem>> fileItemListMap; try { RequestContext requestContext = createRequestContext(requestAdapter.getAdaptee()); fileItemListMap = upload.parseParameterMap(requestContext); } catch (FileUploadBase.SizeLimitExceededException e) { log.warn("Maximum request length exceeded; multipart.maxRequestSize: " + maxRequestSize); requestAdapter.setMaxLengthExceeded(true); return; } catch (FileUploadBase.FileSizeLimitExceededException e) { log.warn("Maximum file length exceeded; multipart.maxFileSize: " + maxFileSize); requestAdapter.setMaxLengthExceeded(true); return; } parseMultipartParameters(fileItemListMap, requestAdapter); } catch (Exception e) { throw new MultipartRequestParseException("Could not parse multipart servlet request", e); } }