List of usage examples for org.apache.commons.fileupload.disk DiskFileItemFactory DiskFileItemFactory
public DiskFileItemFactory()
From source file:com.mx.nibble.middleware.web.util.FileUploadOLD.java
public String execute() throws Exception { //ActionContext ac = invocation.getInvocationContext(); HttpServletResponse response = ServletActionContext.getResponse(); // MultiPartRequestWrapper multipartRequest = ((MultiPartRequestWrapper)ServletActionContext.getRequest()); HttpServletRequest multipartRequest = ServletActionContext.getRequest(); List<FileItem> items2 = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(multipartRequest); System.out.println("TAMAO ITEMS " + items2.size()); System.out.println("Check that we have a file upload request"); boolean isMultipart = ServletFileUpload.isMultipartContent(multipartRequest); System.out.println("isMultipart: " + isMultipart); 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;//www.j ava 2 s.c o m 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 = multipartRequest.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 + ": " + multipartRequest.getHeader(header)); } System.out.println("[parseRequest.jsp] ------------------------------ "); try { System.out.println(" Get URL Parameters."); Enumeration paraNames = multipartRequest.getParameterNames(); System.out.println("[parseRequest.jsp] ------------------------------ "); System.out.println("[parseRequest.jsp] Parameters: "); String pname; String pvalue; while (paraNames.hasMoreElements()) { pname = (String) paraNames.nextElement(); pvalue = multipartRequest.getParameter(pname); System.out.println("[parseRequest.jsp] " + pname + " = " + pvalue); if (pname.equals("jufinal")) { System.out.println("pname.equals(\"jufinal\")"); bLastChunk = pvalue.equals("1"); } else if (pname.equals("jupart")) { System.out.println("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 = multipartRequest.getInputStream(); int c; while ((c = is.read()) >= 0) { System.out.write(c); } //while is.close(); System.out.println( "[parseRequest.jsp] ==========================================================================="); } else if (!multipartRequest.getContentType().startsWith("multipart/form-data")) { System.out.println("[parseRequest.jsp] No parsing of uploaded file: content type is " + multipartRequest.getContentType()); } else { List /* FileItem */ items = upload.parseRequest(multipartRequest); // 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()); System.out.println(" write the file"); fileItem.write(fout); ////////////////////////////////////////////////////////////////////////////////////// System.out.println( " Chunk management: if it was the last chunk, let's recover the complete file"); System.out.println(" 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) { //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"); //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:gsn.http.FieldUpload.java
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String msg;// w w w . j a v a 2 s. c o m Integer code; PrintWriter out = res.getWriter(); ArrayList<String> paramNames = new ArrayList<String>(); ArrayList<String> paramValues = new ArrayList<String>(); //Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(req); if (!isMultipart) { out.write("not multipart!"); code = 666; msg = "Error post data is not multipart!"; logger.error(msg); } else { // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(5 * 1024 * 1024); List items; try { // Parse the request items = upload.parseRequest(req); //building xml data out of the input String cmd = ""; String vsname = ""; Base64 b64 = new Base64(); StringBuilder sb = new StringBuilder("<input>\n"); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.getFieldName().equals("vsname")) { //define which cmd block is sent sb.append("<vsname>" + item.getString() + "</vsname>\n"); vsname = item.getString(); } else if (item.getFieldName().equals("cmd")) { //define which cmd block is sent cmd = item.getString(); sb.append("<command>" + item.getString() + "</command>\n"); sb.append("<fields>\n"); } else if (item.getFieldName().split(";")[0].equals(cmd)) { //only for the defined cmd sb.append("<field>\n"); sb.append("<name>" + item.getFieldName().split(";")[1] + "</name>\n"); paramNames.add(item.getFieldName().split(";")[1]); if (item.isFormField()) { sb.append("<value>" + item.getString() + "</value>\n"); paramValues.add(item.getString()); } else { sb.append("<value>" + new String(b64.encode(item.get())) + "</value>\n"); paramValues.add(new String(b64.encode(item.get()))); } sb.append("</field>\n"); } } sb.append("</fields>\n"); sb.append("</input>\n"); //do something with xml aka statement.toString() AbstractVirtualSensor vs = null; try { vs = Mappings.getVSensorInstanceByVSName(vsname).borrowVS(); vs.dataFromWeb(cmd, paramNames.toArray(new String[] {}), paramValues.toArray(new Serializable[] {})); } catch (VirtualSensorInitializationFailedException e) { logger.warn("Sending data back to the source virtual sensor failed !: " + e.getMessage(), e); } finally { Mappings.getVSensorInstanceByVSName(vsname).returnVS(vs); } code = 200; msg = "The upload to the virtual sensor went successfully! (" + vsname + ")"; } catch (ServletFileUpload.SizeLimitExceededException e) { code = 600; msg = "Upload size exceeds maximum limit!"; logger.error(msg, e); } catch (Exception e) { code = 500; msg = "Internal Error: " + e; logger.error(msg, e); } } //callback to the javascript out.write("<script>window.parent.GSN.msgcallback('" + msg + "'," + code + ");</script>"); }
From source file:com.sr.controller.MahasiswaController.java
@RequestMapping(value = "/isibiodata", method = { RequestMethod.GET, RequestMethod.POST }) public String isi(HttpServletRequest request) { DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload sfu = new ServletFileUpload(factory); try {/*from ww w .j a va 2 s.c o m*/ List<FileItem> items = sfu.parseRequest(request); FileItem foto = items.get(0); FileItem nama_lengkap = items.get(1); FileItem tempat_lahir = items.get(2); FileItem tanggal_lahir = items.get(3); FileItem agama = items.get(4); FileItem kelamin = items.get(5); FileItem alamat_asal = items.get(6); FileItem kabupaten = items.get(7); FileItem provinsi = items.get(8); FileItem no_telp = items.get(9); FileItem nama_ayah = items.get(10); FileItem nama_ibu = items.get(11); FileItem pend_ayah = items.get(12); FileItem pend_ibu = items.get(13); FileItem pekerjaan_ayah = items.get(14); FileItem pekerjaan_ibu = items.get(15); FileItem pendapatan_ortu = items.get(16); FileItem no_telp_rumah = items.get(17); FileItem no_telp_hp = items.get(18); FileItem alamat_keluarga_terdekat = items.get(19); FileItem no_telp_rumah_terdekat = items.get(20); FileItem no_telp_hp_terdekat = items.get(21); FileItem nim = items.get(22); FileItem prodi = items.get(23); FileItem jurusan = items.get(24); FileItem fakultas = items.get(25); FileItem semester = items.get(26); FileItem ipk_sr = items.get(27); FileItem rapor_smu = items.get(28); for (FileItem item : items) { if (item.isFormField()) { System.out.println("FieldName: " + item.getFieldName() + " value: " + item.getString()); } } List<Prestasi> prestasi = new ArrayList(); for (int i = 29; i < items.size() - 1; i += 2) { FileItem n = items.get(i); FileItem k = items.get(i + 1); Prestasi pres = new Prestasi(); pres.setNim(nim.getString()); pres.setNo_sertifikat(n.getString()); pres.setNama_prestasi(k.getString()); if (k.get() != null) { if (n.getFieldName().equals("sertifikatkegiatan")) { pres.setJenis_prestasi("Kampus"); prestasi.add(pres); } else { pres.setJenis_prestasi("Luar Kampus"); prestasi.add(pres); } } } Mahasiswa maha = new Mahasiswa(); maha.setNama_mhs(nama_lengkap.getString()); maha.setTempat_lahir(tempat_lahir.getString()); maha.setTanggal_lahir(tanggal_lahir.getString()); maha.setAgama(agama.getString()); maha.setKelamin(kelamin.getString()); maha.setAlamat_asal(alamat_asal.getString()); maha.setKab_kota_asal(kabupaten.getString()); maha.setProv_asal(provinsi.getString()); maha.setNo_hp_mhs(no_telp.getString()); maha.setNama_ayah(nama_ayah.getString()); maha.setNama_ibu(nama_ibu.getString()); maha.setPendidikan_ayah(pend_ayah.getString()); maha.setPendidikan_ibu(pend_ibu.getString()); maha.setPekerjaan_ayah(pekerjaan_ayah.getString()); maha.setPekerjaan_ibu(pekerjaan_ibu.getString()); maha.setPendapatan_ortu(pendapatan_ortu.getString()); maha.setNo_tel_ortu(no_telp_rumah.getString()); maha.setNo_hp_ortu(no_telp_hp.getString()); maha.setAlamat_keluarga(alamat_keluarga_terdekat.getString()); maha.setNo_tel_keluarga(no_telp_rumah_terdekat.getString()); maha.setNo_hp_keluarga(no_telp_hp_terdekat.getString()); maha.setNim(nim.getString()); AkademikSR asr = new AkademikSR(); asr.setProdi(prodi.getString()); asr.setIpk_masuk(ipk_sr.getString()); asr.setSemester(semester.getString()); asr.setJurusan(jurusan.getString()); asr.setFakultas(fakultas.getString()); asr.setRapor_smu(rapor_smu.getString()); asr.setNim(nim.getString()); mhs.insertBiodata(maha, asr, foto, prestasi); } catch (FileUploadException ex) { System.out.println(ex.getMessage()); } return "redirect:/mahasiswa/daftar"; }
From source file:com.martin.zkedit.controller.Import.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.debug("Importing Action!"); try {/*from www . j a v a 2 s . co m*/ Properties globalProps = (Properties) this.getServletContext().getAttribute("globalProps"); Dao dao = new Dao(globalProps); String zkServer = globalProps.getProperty("zkServer"); String[] zkServerLst = zkServer.split(","); StringBuilder sbFile = new StringBuilder(); String scmOverwrite = "false"; String scmServer = ""; String scmFilePath = ""; String scmFileRevision = ""; String uploadFileName = ""; DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1034); ServletFileUpload upload = new ServletFileUpload(factory); List items = upload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { if (item.getFieldName().equals("scmOverwrite")) { scmOverwrite = item.getString(); } if (item.getFieldName().equals("scmServer")) { scmServer = item.getString(); } if (item.getFieldName().equals("scmFilePath")) { scmFilePath = item.getString(); } if (item.getFieldName().equals("scmFileRevision")) { scmFileRevision = item.getString(); } } else { uploadFileName = item.getName(); sbFile.append(item.getString()); } } InputStream inpStream; if (sbFile.toString().length() == 0) { uploadFileName = scmServer + scmFileRevision + "@" + scmFilePath; logger.debug("P4 file Processing " + uploadFileName); dao.insertHistory((String) request.getSession().getAttribute("authName"), request.getRemoteAddr(), "Importing P4 File: " + uploadFileName + "<br/>" + "Overwrite: " + scmOverwrite); URL url = new URL(uploadFileName); URLConnection conn = url.openConnection(); inpStream = conn.getInputStream(); } else { logger.debug("Upload file Processing " + uploadFileName); dao.insertHistory((String) request.getSession().getAttribute("authName"), request.getRemoteAddr(), "Uploading File: " + uploadFileName + "<br/>" + "Overwrite: " + scmOverwrite); inpStream = new ByteArrayInputStream(sbFile.toString().getBytes()); } // open the stream and put it into BufferedReader BufferedReader br = new BufferedReader(new InputStreamReader(inpStream)); String inputLine; List<String> importFile = new ArrayList<>(); Integer lineCnt = 0; while ((inputLine = br.readLine()) != null) { lineCnt++; // Empty or comment? if (inputLine.trim().equals("") || inputLine.trim().startsWith("#")) { continue; } if (inputLine.startsWith("-")) { //DO nothing. } else if (!inputLine.matches("/.+=.+=.*")) { throw new IOException("Invalid format at line " + lineCnt + ": " + inputLine); } importFile.add(inputLine); } br.close(); ZooKeeperUtil.INSTANCE.importData(importFile, Boolean.valueOf(scmOverwrite), ServletUtil.INSTANCE.getZookeeper(request, response, zkServerLst[0])); for (String line : importFile) { if (line.startsWith("-")) { dao.insertHistory((String) request.getSession().getAttribute("authName"), request.getRemoteAddr(), "File: " + uploadFileName + ", Deleting Entry: " + line); } else { dao.insertHistory((String) request.getSession().getAttribute("authName"), request.getRemoteAddr(), "File: " + uploadFileName + ", Adding Entry: " + line); } } request.getSession().setAttribute("flashMsg", "Import Completed!"); response.sendRedirect("/home"); } catch (FileUploadException | IOException | InterruptedException | KeeperException ex) { ServletUtil.INSTANCE.renderError(request, response, ex.getMessage()); } }
From source file:check_reg_bidder.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try {//from w ww . j a v a2 s . co m HttpSession sess = request.getSession(true); String f = (String) sess.getAttribute("fn"); String l = (String) sess.getAttribute("ln"); String mail = (String) sess.getAttribute("em"); String un = (String) sess.getAttribute("usr"); String pwd = (String) sess.getAttribute("pass"); String add = (String) sess.getAttribute("add"); String phn = (String) sess.getAttribute("no"); String cit = (String) sess.getAttribute("city"); String ut = (String) sess.getAttribute("type"); String des = (String) sess.getAttribute("des"); String dept = (String) sess.getAttribute("depa"); // out.println(dept); Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/project?zeroDateTimeBehavior=convertToNull", "root", "root"); Statement st = con.createStatement(); boolean isMultipart = ServletFileUpload.isMultipartContent(request);//retrive req.. data & extract below //out.println(isMultipart); if (isMultipart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items = upload.parseRequest(request); String paraname[] = new String[15]; int i = 0; Iterator iterator = items.iterator(); while (iterator.hasNext()) { org.apache.commons.fileupload.FileItem item = (org.apache.commons.fileupload.FileItem) iterator .next(); paraname[i] = item.getString();// one by one tag's values to arrat //out.println(i+"----"+paraname[i]); //out.println("<br>"); i++; if (!item.isFormField())// if type=file { String fileName = item.getName();// uploadiing file out.println(fileName); String root = "D:\\rushiraj\\Main Project\\web";//currnet path File path = new File(root + "/cmpfile");// path plus testimage directory if (!path.exists()) { boolean status = path.mkdirs(); //if dir! not exists than createe once } File uploadedFile = new File(path + "/" + fileName); /// upload file/image at path item.write(uploadedFile);//phiscaly write- String q1 = "insert into company_details (name,pan_no,it_cer,est_date,lic_val,reg_no,address,city,state,class) values('" + paraname[0] + "','" + paraname[1] + "','" + fileName + "','" + paraname[2] + "','" + paraname[3] + "','" + paraname[4] + "','" + paraname[5] + paraname[6] + paraname[7] + "','" + paraname[8] + "','" + paraname[9] + "','" + paraname[10] + "')"; String query = "insert into register (first_name,last_name,mail,username,password,phone,address,city,type,designation,department) values('" + f + "','" + l + "','" + mail + "','" + un + "','" + pwd + "','" + phn + "','" + add + "','" + cit + "','" + ut + "','" + des + "','" + dept + "');"; out.println(q1); out.println(query); int r = st.executeUpdate(q1);//insert remaing data into table..... int p = st.executeUpdate(query); if (r > 0) { response.sendRedirect("login.jsp"); } } } } } catch (Exception ex) { out.println(ex); } }
From source file:com.mycompany.mytubeaws.UploadServlet.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*from www . j a va2s . c o m*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String result = ""; String fileName = null; boolean uploaded = false; // configures upload settings DiskFileItemFactory factory = new DiskFileItemFactory(); // sets memory threshold - beyond which files are stored in disk factory.setSizeThreshold(1024 * 1024 * 3); // 3mb factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); // sets temporary location to store files ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(1024 * 1024 * 40); // sets maximum size of upload file upload.setSizeMax(1024 * 1024 * 50); // sets maximum size of request (include file + form data) try { List<FileItem> formItems = upload.parseRequest(request); // parses the request's content to extract file data if (formItems != null && formItems.size() > 0) // iterates over form's fields { for (FileItem item : formItems) // processes only fields that are not form fields { if (!item.isFormField()) { fileName = item.getName(); UUID id = UUID.randomUUID(); fileName = FilenameUtils.getBaseName(fileName) + "_ID-" + id.toString() + "." + FilenameUtils.getExtension(fileName); File file = File.createTempFile("aws-java-sdk-upload", ""); item.write(file); // write form item to file (?) if (file.length() == 0) throw new RuntimeException("No file selected or empty file uploaded."); try { s3.putObject(new PutObjectRequest(bucketName, fileName, file)); result += "File uploaded successfully; "; uploaded = true; } catch (AmazonServiceException ase) { System.out.println("Caught an AmazonServiceException, which means your request made it " + "to Amazon S3, but was rejected with an error response for some reason."); System.out.println("Error Message: " + ase.getMessage()); System.out.println("HTTP Status Code: " + ase.getStatusCode()); System.out.println("AWS Error Code: " + ase.getErrorCode()); System.out.println("Error Type: " + ase.getErrorType()); System.out.println("Request ID: " + ase.getRequestId()); result += "AmazonServiceException thrown; "; } catch (AmazonClientException ace) { System.out .println("Caught an AmazonClientException, which means the client encountered " + "a serious internal problem while trying to communicate with S3, " + "such as not being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); result += "AmazonClientException thrown; "; } file.delete(); } } } } catch (Exception ex) { result += "Generic exception: '" + ex.getMessage() + "'; "; ex.printStackTrace(); } if (fileName != null && uploaded) result += "Generated file ID: " + fileName; System.out.println(result); request.setAttribute("resultText", result); request.getRequestDispatcher("/UploadResult.jsp").forward(request, response); }
From source file:Controlador.Contr_Evento.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w .ja v a2 s . c o m * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /*Se detalla el contenido que tendra el servlet*/ response.setContentType("text/html;charset=UTF-8"); request.setCharacterEncoding("UTF-8"); /*Se crea una variable para la sesion*/ HttpSession session = request.getSession(true); boolean b; try { /*Se declaran las variables necesarias*/ Cls_Evento eve = new Cls_Evento(); Cls_Mensajeria sms = new Cls_Mensajeria(); String Codigo = "", Mensaje = "", Nombre = "", Tipo = "", Imagen = "", url, Peti; String urlsalidaimg; urlsalidaimg = "/media/santiago/Santiago/IMGTE/"; //urlsalidaimg = "I:\\IMGTE\\"; String urlimgservidor = this.getServletContext().getRealPath("/Libs/Customs/images/Evento"); /*FileItemFactory es una interfaz para crear FileItem*/ FileItemFactory file_factory = new DiskFileItemFactory(); /*ServletFileUpload esta clase convierte los input file a FileItem*/ ServletFileUpload servlet_up = new ServletFileUpload(file_factory); /*sacando los FileItem del ServletFileUpload en una lista */ List items = servlet_up.parseRequest(request); Iterator it = items.iterator(); /*Se evalua cada una de las posibles peticiones y los posibles campos que envien*/ while (it.hasNext()) { FileItem item = (FileItem) it.next(); if (item.isFormField()) { //Plain request parameters will come here. String name = item.getFieldName(); if (name.equals("Creador")) { /*Se guarda el campo en la clase*/ eve.setCreador(item.getString()); } else if (name.equals("Nombre")) { /*Se guarda el campo en la clase*/ eve.setNombre(item.getString()); } else if (name.equals("Codigo")) { /*Se guarda el campo en la clase*/ eve.setCodigo(item.getString()); } else if (name.equals("Rango")) { /*Se guarda el campo en la clase*/ eve.setRango(item.getString()); } else if (name.equals("Rangomaximo")) { /*Se guarda el campo en la clase*/ eve.setRangoMaximo(item.getString()); } else if (name.equals("Fecha")) { /*Se guarda el campo en la clase*/ eve.setFecha(item.getString()); } else if (name.equals("Descripcion")) { /*Se guarda el campo en la clase*/ eve.setDescipcion(item.getString()); } else if (name.equals("Ciudad")) { /*Se guarda el campo en la clase*/ eve.setCiudad(item.getString()); } else if (name.equals("Direccion")) { /*Se guarda el campo en la clase*/ eve.setDireccion(item.getString()); } else if (name.equals("Motivo")) { /*Se guarda el campo en la clase*/ eve.setMotivo(item.getString()); } else if (name.equals("Latitud")) { /*Se guarda el campo en la clase*/ eve.setLatitud(item.getString()); } else if (name.equals("Longitud")) { /*Se guarda el campo en la clase*/ eve.setLongitud(item.getString()); } else if (name.equals("RegistrarEvento")) { /*Se convierte la fecha a date*/ if (eve.ConvertirFecha(eve.getFecha())) { /*Se evalua si la fecha tiene dos dias mas a la fecha de hoy*/ if (eve.ValidarDosDiasFecha(eve.getFechaDate())) { /*Se evalua si se mando una iamgen*/ if (!eve.getImagen().equals("")) { /*Si se envia una imagen obtiene la imagen para eliminarla luego*/ File img = new File(eve.getImagen()); /*Se ejecuta el metodo de registrar evento, en la clase modelo con los datos que se encuentran en la clase*/ String rangoprecios = eve.getRango() + "-" + eve.getRangoMaximo(); b = eve.setRegistrarEvento(eve.getTypeimg(), eve.getNombre(), eve.getFechaDate(), eve.getDescipcion(), rangoprecios, eve.getCreador(), eve.getCiudad(), eve.getDireccion(), eve.getLatitud(), eve.getLongitud()); if (b) { File imagedb = new File( urlimgservidor + "/" + eve.getCodigo() + eve.getTypeimg()); img.renameTo(imagedb); /*Se guarda un mensaje mediante las sesiones y se redirecciona*/ session.setAttribute("Mensaje", "Se registro el evento satisfactoriamente."); session.setAttribute("TipoMensaje", "Dio"); response.sendRedirect( "View/RClasificacionEvento.jsp?CodigoEvento=" + eve.getCodigo()); } else { img.delete(); /*Se guarda un mensaje mediante las sesiones y se redirecciona*/ session.setAttribute("Mensaje", eve.getMensaje()); session.setAttribute("TipoMensaje", "NODio"); response.sendRedirect("View/RegistrarEvento.jsp"); } } else { /*Se guarda un mensaje mediante las sesiones y se redirecciona*/ session.setAttribute("Mensaje", "Seleccione una imagen para registrar el evento"); session.setAttribute("TipoMensaje", "NODio"); response.sendRedirect("View/RegistrarEvento.jsp"); } } else { /*Se guarda un mensaje mediante las sesiones y se redirecciona*/ session.setAttribute("Mensaje", "No se puede registrar un evento que inicie antes de dos das"); session.setAttribute("TipoMensaje", "NODio"); response.sendRedirect("View/RegistrarEvento.jsp"); } } else { /*Se guarda un mensaje mediante las sesiones y se redirecciona*/ session.setAttribute("Mensaje", "Ocurri un problema inesperado con la fecha del evento. Estamos trabajando para solucionar este problema."); session.setAttribute("TipoMensaje", "NODio"); response.sendRedirect("View/RegistrarEvento.jsp"); } } else if (name.equals("DesactivarEvento")) { if (eve.validar_Cancelar_Evento_Un_Dia(eve.getCodigo())) { /*Se ejecuta el metodo de desaprobar evento, en la clase modelo con los datos que se encuentran en la clase*/ if (eve.setDesaprobarEvento(eve.getCodigo(), eve.getMotivo())) { String[] Datos = eve.BuscarEventoParaMensaje(eve.getCodigo()); if (sms.EnviarMensajeCambioEstadoEvento(Datos, "Desaprobado", eve.getMotivo())) { /*Se guarda un mensaje mediante las sesiones y se redirecciona*/ session.setAttribute("Mensaje", "Se cancel el evento satisfactoriamente."); session.setAttribute("TipoMensaje", "Dio"); } else { /*Se guarda un mensaje mediante las sesiones y se redirecciona*/ session.setAttribute("Mensaje", "Se cancel el evento, pero no se logr enviar la notificacin al correo electrnico de la empresa."); session.setAttribute("TipoMensaje", "NODio"); } } else { /*Se guarda un mensaje mediante las sesiones y se redirecciona*/ session.setAttribute("Mensaje", "Ocurri un error al cancelar el evento. Estamos trabajando para solucionar este problema."); session.setAttribute("TipoMensaje", "NODio"); } } else { session.setAttribute("Mensaje", "No se puede cancelar un evento antes de un da de su inicio. Lo lamentamos."); session.setAttribute("TipoMensaje", "NODio"); } response.sendRedirect("View/CEventoPendiente.jsp"); } else if (name.equals("DesactivarEventoAdmin")) { if (eve.validar_Cancelar_Evento_Un_Dia(eve.getCodigo())) { /*Se ejecuta el metodo de desaprobar evento, en la clase modelo con los datos que se encuentran en la clase(administradir)*/ if (eve.setDesaprobarEvento(eve.getCodigo(), eve.getMotivo())) { String[] Datos = eve.BuscarEventoParaMensaje(eve.getCodigo()); if (sms.EnviarMensajeCambioEstadoEvento(Datos, "Desaprobado", eve.getMotivo())) { /*Se guarda un mensaje mediante las sesiones y se redirecciona*/ session.setAttribute("Mensaje", "Se desaprob el evento satisfactoriamente."); session.setAttribute("TipoMensaje", "Dio"); } else { /*Se guarda un mensaje mediante las sesiones y se redirecciona*/ session.setAttribute("Mensaje", "Se desaprob el evento, pero no se logr enviar la notificacin al correo electrnico de la empresa."); session.setAttribute("TipoMensaje", "NODio"); } } else { /*Se guarda un mensaje mediante las sesiones y se redirecciona*/ session.setAttribute("Mensaje", "Ocurri un error al desaprobar el evento. Estamos trabajando para solucionar este problema."); session.setAttribute("TipoMensaje", "NODio"); } } else { session.setAttribute("Mensaje", "No se puede cancelar un evento antes de un da de su inicio. Lo lamentamos."); session.setAttribute("TipoMensaje", "NODio"); } response.sendRedirect("View/ConsultaTodosEventos.jsp"); } else if (name.equals("DesactivarEventoEmpresa")) { if (eve.validar_Cancelar_Evento_Un_Dia(eve.getCodigo())) { /*Se ejecuta el metodo de desaprobar evento, en la clase modelo con los datos que se encuentran en la clase(Empresa)*/ if (eve.setCancelarEvento(eve.getCodigo(), eve.getMotivo())) { session.setAttribute("Mensaje", "Se cancel el evento satisfactoriamente."); session.setAttribute("TipoMensaje", "Dio"); } else { session.setAttribute("Mensaje", "Ocurri un error al cancelar el evento. Estamos trabajando para solucionar este problema."); session.setAttribute("TipoMensaje", "NODio"); } } else { session.setAttribute("Mensaje", "No se puede cancelar un evento antes de un da de su inicio. Lo lamentamos."); session.setAttribute("TipoMensaje", "NODio"); } response.sendRedirect("View/MisEventos.jsp"); } } else { if (!item.getName().equals("")) { //uploaded files will come here. FileItem file = item; String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); if (sizeInBytes > 1000000) { /*Se muestra un mensaje en caso de pesar mas de 3 MB*/ session.setAttribute("Mensaje", "El tamao lmite de la imagen es: 1 MB"); session.setAttribute("TipoMensaje", "NODio"); /*Se redirecciona*/ response.sendRedirect("View/ConsultaSeleccion.jsp"); } else { if (contentType.indexOf("jpeg") > 0 || contentType.indexOf("png") > 0) { if (contentType.indexOf("jpeg") > 0) { contentType = ".jpg"; } else { contentType = ".png"; } /*Se crea la imagne*/ File archivo_server = new File(urlimgservidor + "/" + item.getName()); /*Se guardael url de la imagen en la clase*/ eve.setImagen(urlimgservidor + "/" + item.getName()); eve.setTypeimg(contentType); /*Se guarda la imagen*/ item.write(archivo_server); } else { session.setAttribute("Mensaje", "Solo se pueden registrar imagenes JPG o PNG"); session.setAttribute("TipoMensaje", "NODio"); } } } else { /** * Se guardael url de la imagen en la clase */ eve.setImagen(""); } } } response.sendRedirect("View/index.jsp"); } catch (FileUploadException ex) { System.out.print(ex.getMessage().toString()); } catch (Exception ex) { Logger.getLogger(Contr_Seleccion.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.deem.zkui.controller.Import.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.debug("Importing Action!"); try {//from www .j a va2 s . co m Properties globalProps = (Properties) this.getServletContext().getAttribute("globalProps"); Dao dao = new Dao(globalProps); String zkServer = globalProps.getProperty("zkServer"); String[] zkServerLst = zkServer.split(","); StringBuilder sbFile = new StringBuilder(); String scmOverwrite = "false"; String scmServer = ""; String scmFilePath = ""; String scmFileRevision = ""; String uploadFileName = ""; DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1034); ServletFileUpload upload = new ServletFileUpload(factory); List items = upload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { if (item.getFieldName().equals("scmOverwrite")) { scmOverwrite = item.getString(); } if (item.getFieldName().equals("scmServer")) { scmServer = item.getString(); } if (item.getFieldName().equals("scmFilePath")) { scmFilePath = item.getString(); } if (item.getFieldName().equals("scmFileRevision")) { scmFileRevision = item.getString(); } } else { uploadFileName = item.getName(); sbFile.append(item.getString()); } } InputStream inpStream; if (sbFile.toString().length() == 0) { uploadFileName = scmServer + scmFileRevision + "@" + scmFilePath; logger.debug("P4 file Processing " + uploadFileName); dao.insertHistory((String) request.getSession().getAttribute("authName"), request.getRemoteAddr(), "Importing P4 File: " + uploadFileName + "<br/>" + "Overwrite: " + scmOverwrite); URL url = new URL(uploadFileName); URLConnection conn = url.openConnection(); inpStream = conn.getInputStream(); } else { logger.debug("Upload file Processing " + uploadFileName); dao.insertHistory((String) request.getSession().getAttribute("authName"), request.getRemoteAddr(), "Uploading File: " + uploadFileName + "<br/>" + "Overwrite: " + scmOverwrite); inpStream = new ByteArrayInputStream(sbFile.toString().getBytes()); } // open the stream and put it into BufferedReader BufferedReader br = new BufferedReader(new InputStreamReader(inpStream)); String inputLine; List<String> importFile = new ArrayList<>(); Integer lineCnt = 0; while ((inputLine = br.readLine()) != null) { lineCnt++; // Empty or comment? if (inputLine.trim().equals("") || inputLine.trim().startsWith("#")) { continue; } if (inputLine.startsWith("-")) { //DO nothing. } else if (!inputLine.matches("/.+=.+=.*")) { throw new IOException("Invalid format at line " + lineCnt + ": " + inputLine); } importFile.add(inputLine); } br.close(); ZooKeeperUtil.INSTANCE.importData(importFile, Boolean.valueOf(scmOverwrite), ServletUtil.INSTANCE.getZookeeper(request, response, zkServerLst[0], globalProps)); for (String line : importFile) { if (line.startsWith("-")) { dao.insertHistory((String) request.getSession().getAttribute("authName"), request.getRemoteAddr(), "File: " + uploadFileName + ", Deleting Entry: " + line); } else { dao.insertHistory((String) request.getSession().getAttribute("authName"), request.getRemoteAddr(), "File: " + uploadFileName + ", Adding Entry: " + line); } } request.getSession().setAttribute("flashMsg", "Import Completed!"); response.sendRedirect("/home"); } catch (FileUploadException | IOException | InterruptedException | KeeperException ex) { logger.error(Arrays.toString(ex.getStackTrace())); ServletUtil.INSTANCE.renderError(request, response, ex.getMessage()); } }
From source file:eu.impact_project.iif.t2.client.Helper.java
/** * Extracts all the form input values from a request object. Taverna * workflows are read as strings. Other files are converted to Base64 * strings./*from ww w . j a v a2 s .c om*/ * * @param request * The request object that will be analyzed * @return Map containing all form values and files as strings. The name of * the form is used as the index */ public static Map<String, String> parseRequest(HttpServletRequest request) { // stores all the strings and encoded files from the html form Map<String, String> htmlFormItems = new HashMap<String, String>(); try { // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List items; items = upload.parseRequest(request); // Process the uploaded items Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); // a normal string field if (item.isFormField()) { // put the string items into the map htmlFormItems.put(item.getFieldName(), item.getString()); // uploaded workflow file } else if (item.getFieldName().startsWith("file_workflow")) { htmlFormItems.put(item.getFieldName(), new String(item.get())); // uploaded file } else { // encode the uploaded file to base64 String currentAttachment = new String(Base64.encode(item.get())); // put the encoded attachment into the map htmlFormItems.put(item.getFieldName(), currentAttachment); } } } catch (FileUploadException e) { e.printStackTrace(); } return htmlFormItems; }
From source file:com.sapuraglobal.hrms.servlet.UploadEmp.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w . jav a 2 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 { response.setContentType("text/html;charset=UTF-8"); String action = request.getParameter("action"); System.out.println("action: " + action); if (action == null || action.isEmpty()) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); //PriceDAO priceDAO = new PriceDAO(); try { List<FileItem> fields = upload.parseRequest(request); //out.println("Number of fields: " + fields.size() + "<br/><br/>"); Iterator<FileItem> it = fields.iterator(); while (it.hasNext()) { FileItem fileItem = it.next(); //store in webserver. String fileName = fileItem.getName(); if (fileName != null) { File file = new File(fileName); fileItem.write(file); System.out.println("File successfully saved as " + file.getAbsolutePath()); //process file Reader in = new FileReader(file.getAbsolutePath()); Iterable<CSVRecord> records = CSVFormat.EXCEL.withHeader().parse(in); for (CSVRecord record : records) { String name = record.get("<name>"); String login = record.get("<login>"); String title = record.get("<title>"); String email = record.get("<email>"); String role = record.get("<role>"); String dept = record.get("<department>"); String joinDate = record.get("<joinDate>"); String probDate = record.get("<probDate>"); String annLeaveEnt = record.get("<leave_entitlement>"); String annBal = record.get("<leave_bal>"); String annMax = record.get("<leave_max>"); String annCF = record.get("<leave_cf>"); String med = record.get("<med_taken>"); String oil = record.get("<oil_taken>"); String unpaid = record.get("<unpaid_taken>"); String child = record.get("<child_bal>"); TitleDTO titleDto = titleBean.getTitleByName(title); RoleDTO roleDto = accessBean.getRole(role); DeptDTO deptDto = deptBean.getDepartment(dept); //create the user first UserDTO user = new UserDTO(); user.setName(name); user.setLogin(login); user.setTitle(titleDto); user.setEmail(email); user.setDateJoin(Utility.format(joinDate, "dd/MM/yyyy")); user.setProbationDue(Utility.format(probDate, "dd/MM/yyyy")); //store in user table. userBean.createUser(user); //assign role userBean.assignRole(user, roleDto); //assign dept deptBean.assignEmployee(user, deptDto); //leave ent LeaveTypeDTO lvtypeDTO = leaveBean.getLeaveType("Annual"); LeaveEntDTO annualentDTO = new LeaveEntDTO(); annualentDTO.setCurrent(Double.parseDouble(annLeaveEnt)); annualentDTO.setBalance(Double.parseDouble(annBal)); annualentDTO.setMax(Double.parseDouble(annMax)); annualentDTO.setCarriedOver(Double.parseDouble(annCF)); annualentDTO.setLeaveType(lvtypeDTO); //assign annual leave annualentDTO.setUser(user); leaveBean.addLeaveEnt(annualentDTO); //medical ent LeaveTypeDTO medTypeDTO = leaveBean.getLeaveType("Medical Leave"); LeaveEntDTO medentDTO = new LeaveEntDTO(); medentDTO.setBalance(medTypeDTO.getDays() - Double.parseDouble(med)); medentDTO.setCurrent(medTypeDTO.getDays()); medentDTO.setUser(user); medentDTO.setLeaveType(medTypeDTO); leaveBean.addLeaveEnt(medentDTO); //oil ent LeaveTypeDTO oilTypeDTO = leaveBean.getLeaveType("Off-in-Lieu"); LeaveEntDTO oilentDTO = new LeaveEntDTO(); oilentDTO.setBalance(oilTypeDTO.getDays() - Double.parseDouble(oil)); oilentDTO.setCurrent(0); oilentDTO.setUser(user); oilentDTO.setLeaveType(oilTypeDTO); leaveBean.addLeaveEnt(oilentDTO); //unpaid LeaveTypeDTO unpaidTypeDTO = leaveBean.getLeaveType("Unpaid"); LeaveEntDTO unpaidentDTO = new LeaveEntDTO(); unpaidentDTO.setBalance(unpaidTypeDTO.getDays() - Double.parseDouble(unpaid)); unpaidentDTO.setCurrent(0); unpaidentDTO.setUser(user); unpaidentDTO.setLeaveType(unpaidTypeDTO); leaveBean.addLeaveEnt(unpaidentDTO); //child LeaveTypeDTO childTypeDTO = leaveBean.getLeaveType("Child Care"); double cur = childTypeDTO.getDays(); LeaveEntDTO childentDTO = new LeaveEntDTO(); childentDTO.setBalance(cur - Double.parseDouble(child)); childentDTO.setCurrent(cur); childentDTO.setUser(user); childentDTO.setLeaveType(childTypeDTO); leaveBean.addLeaveEnt(childentDTO); } /* if (stockPrices.size() > 0) { priceDAO.OpenConnection(); priceDAO.updateStockPrice(stockPrices); } */ } } } catch (Exception e) { e.printStackTrace(); } finally { //priceDAO.CloseConnection(); RequestDispatcher dispatcher = request.getRequestDispatcher("/employee"); //request.setAttribute(Constants.TITLE, "Home"); dispatcher.forward(request, response); } } else { RequestDispatcher dispatcher = request.getRequestDispatcher("/uploadEmp.jsp"); //request.setAttribute(Constants.TITLE, "Home"); dispatcher.forward(request, response); } }