List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload parseRequest
public List parseRequest(HttpServletRequest request) throws FileUploadException
From source file:com.sapuraglobal.hrms.servlet.UploadEmp.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// www . j ava 2 s . co 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 { 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); } }
From source file:com.github.davidcarboni.encryptedfileupload.SizesTest.java
/** Checks, whether limiting the file size works. *//*from w ww.ja v a 2 s .c o m*/ @Test public void testFileSizeLimit() throws IOException, FileUploadException { final String request = "-----1234\r\n" + "Content-Disposition: form-data; name=\"file\"; filename=\"foo.tab\"\r\n" + "Content-Type: text/whatever\r\n" + "\r\n" + "This is the content of the file\n" + "\r\n" + "-----1234--\r\n"; ServletFileUpload upload = new ServletFileUpload(new EncryptedFileItemFactory()); upload.setFileSizeMax(-1); HttpServletRequest req = new MockHttpServletRequest(request.getBytes("US-ASCII"), CONTENT_TYPE); List<FileItem> fileItems = upload.parseRequest(req); assertEquals(1, fileItems.size()); FileItem item = fileItems.get(0); assertEquals("This is the content of the file\n", new String(item.get())); upload = new ServletFileUpload(new EncryptedFileItemFactory()); upload.setFileSizeMax(40); req = new MockHttpServletRequest(request.getBytes("US-ASCII"), CONTENT_TYPE); fileItems = upload.parseRequest(req); assertEquals(1, fileItems.size()); item = fileItems.get(0); assertEquals("This is the content of the file\n", new String(item.get())); upload = new ServletFileUpload(new EncryptedFileItemFactory()); upload.setFileSizeMax(30); req = new MockHttpServletRequest(request.getBytes("US-ASCII"), CONTENT_TYPE); try { upload.parseRequest(req); fail("Expected exception."); } catch (FileUploadBase.FileSizeLimitExceededException e) { assertEquals(30, e.getPermittedSize()); } }
From source file:guru.bubl.service.resources.vertex.VertexImageResource.java
@POST @Consumes(MediaType.MULTIPART_FORM_DATA) @GraphTransactional/*from ww w .j a v a 2s . co m*/ @Produces(MediaType.APPLICATION_JSON) @Path("/") public Response add(@Context HttpServletRequest request) { Set<Image> uploadedImages = new HashSet<>(); if (ServletFileUpload.isMultipartContent(request)) { final FileItemFactory factory = new DiskFileItemFactory(); final ServletFileUpload fileUpload = new ServletFileUpload(factory); try { /* * parseRequest returns a list of FileItem * but in old (pre-java5) style */ final List items = fileUpload.parseRequest(request); if (items != null) { final Iterator iter = items.iterator(); while (iter.hasNext()) { final FileItem item = (FileItem) iter.next(); String imageId = UUID.randomUUID().toString(); final File savedFile = new File(IMAGES_FOLDER_PATH + File.separator + imageId); System.out.println("Saving the file: " + savedFile.getName()); item.write(savedFile); saveBigImage(savedFile); String imageBaseUrl = request.getRequestURI() + "/" + imageId + "/"; String base64ForSmallImage = Base64.encodeBase64String(resizedSmallImage(savedFile)); uploadedImages.add(Image.withBase64ForSmallAndUriForBigger(base64ForSmallImage, URI.create(imageBaseUrl + "big"))); } } vertex.addImages(uploadedImages); return Response.ok().entity(ImageJson.toJsonArray(uploadedImages)).build(); } catch (Exception exception) { exception.printStackTrace(); throw new WebApplicationException(Response.Status.BAD_REQUEST); } } throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR); }
From source file:com.nemesis.admin.UploadServlet.java
/** * @param request/* w w w . j a v a2s .c o m*/ * @param response * @throws javax.servlet.ServletException * @throws java.io.IOException * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) * */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (!ServletFileUpload.isMultipartContent(request)) { throw new IllegalArgumentException( "Request is not multipart, please 'multipart/form-data' enctype for your form."); } ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory()); PrintWriter writer = response.getWriter(); response.setContentType("application/json"); JsonArray json = new JsonArray(); try { List<FileItem> items = uploadHandler.parseRequest(request); for (FileItem item : items) { if (!item.isFormField()) { final String savedFile = UUID.randomUUID().toString() + "." + getSuffix(item.getName()); File file = new File(request.getServletContext().getRealPath("/") + "uploads/", savedFile); item.write(file); JsonObject jsono = new JsonObject(); jsono.addProperty("name", savedFile); jsono.addProperty("path", file.getAbsolutePath()); jsono.addProperty("size", item.getSize()); json.add(jsono); System.out.println(json.toString()); } } } catch (FileUploadException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } finally { writer.write(json.toString()); writer.close(); } }
From source file:com.weaforce.system.component.fckeditor.connector.ConnectorServlet.java
/** * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br /> * // w w w. j a va 2 s.c o m * The servlet accepts commands sent in the following format:<br /> * <code>connector?Command=<FileUpload>&Type=<ResourceType>&CurrentFolder=<FolderPath></code> * with the file in the <code>POST</code> body.<br /> * <br> * It stores an uploaded file (renames a file if another exists with the * same name) and then returns the JavaScript callback. */ @SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.debug("Entering Connector#doPost"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); String commandStr = request.getParameter("Command"); // "FileUpload" String typeStr = request.getParameter("Type"); // Image String currentFolderStr = request.getParameter("CurrentFolder"); // "/" imageSubPath = request.getParameter("subpath"); logger.info("Parameter Command in doPost: {}", commandStr); logger.info("Parameter Type in doPost: {}", typeStr); logger.info("Parameter CurrentFolder in doPost: {}", currentFolderStr); UploadResponse ur; // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr' // are empty if (StringUtil.isEmpty(commandStr) && StringUtil.isEmpty(currentFolderStr)) { commandStr = "QuickUpload"; currentFolderStr = "/"; } if (!RequestCycleHandler.isEnabledForFileUpload(request)) ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null, Messages.NOT_AUTHORIZED_FOR_UPLOAD); else if (!CommandHandler.isValidForPost(commandStr)) ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND); else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr)) ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE); else if (!FileUtils.isValidPath(currentFolderStr)) ur = UploadResponse.UR_INVALID_CURRENT_FOLDER; else { ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr); //String userLogin = Security.getCurrentUserName().toLowerCase(); // typePath=\\data\\file in the weaforce.properties String typePath = UtilsFile.constructServerSidePath(request, resourceType); typePath = typePath + "/" + imageSubPath + "/" + DateUtil.getCurrentYearObliqueMonthStr(); System.out.println("typePath: " + typePath); logger.info("doPost: typePath value is: {}", typePath); String typeDirPath = typePath; FileUtils.checkAndCreateDir(typeDirPath); File typeDir = new File(typeDirPath); File currentDir = new File(typeDir, currentFolderStr); if (!currentDir.exists()) ur = UploadResponse.UR_INVALID_CURRENT_FOLDER; else { String newFilename = null; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> items = upload.parseRequest(request); // We upload only one file at the same time FileItem uplFile = items.get(0); String rawName = UtilsFile.sanitizeFileName(uplFile.getName()); String filename = FilenameUtils.getName(rawName); // String baseName = // FilenameUtils.removeExtension(filename); String extension = FilenameUtils.getExtension(filename); if (!ExtensionsHandler.isAllowed(resourceType, extension)) ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); else { filename = getFilename(typeDirPath, System.currentTimeMillis(), extension); File pathToSave = new File(currentDir, filename); // String responseUrl = UtilsResponse // .constructResponseUrl(request, resourceType, // currentFolderStr, true, // ConnectorHandler.isFullUrl()); String responseUrl = UtilsResponse.constructResponseUrl(resourceType, imageSubPath, currentFolderStr); if (StringUtil.isEmpty(newFilename)) { responseUrl = responseUrl + DateUtil.getCurrentYearObliqueMonthStr() + "/"; ur = new UploadResponse(UploadResponse.SC_OK, responseUrl.concat(filename)); } else ur = new UploadResponse(UploadResponse.SC_RENAMED, responseUrl.concat(newFilename), newFilename); // secure image check if (resourceType.equals(ResourceTypeHandler.IMAGE) && ConnectorHandler.isSecureImageUploads()) { if (FileUtils.isImage(uplFile.getInputStream())) uplFile.write(pathToSave); else { uplFile.delete(); ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); } } else uplFile.write(pathToSave); } } catch (Exception e) { ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR); } // System.out.println("newFilename2: " + newFilename); } } out.print(ur); out.flush(); out.close(); logger.debug("Exiting Connector#doPost"); }
From source file:com.intranet.intr.contabilidad.SupControllerGastos.java
@RequestMapping(value = "addGastoRF.htm", method = RequestMethod.POST) public String addGastoRF_post(@ModelAttribute("ga") gastosR ga, BindingResult result, HttpServletRequest request) {//from w ww . j a va2 s.c om String mensaje = ""; String ruta = "redirect:Gastos.htm"; gastosR gr = new gastosR(); //MultipartFile multipart = c.getArchivo(); System.out.println("olaEnviarMAILS"); String ubicacionArchivo = "C:\\glassfish-4.1.1-web\\glassfish4\\glassfish\\domains\\domain1\\applications\\Intranet\\resources\\fotosfacturas"; //File file=new File(ubicacionArchivo,multipart.getOriginalFilename()); //String ubicacionArchivo="C:\\"; DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1024); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> partes = upload.parseRequest(request); for (FileItem item : partes) { if (idPC != 0) { gr.setIdgasto(idPC); if (gastosRService.existe(item.getName()) == false) { System.out.println("NOMBRE FOTO: " + item.getName()); File file = new File(ubicacionArchivo, item.getName()); item.write(file); gr.setNombreimg(item.getName()); gastosRService.insertar(gr); } } else ruta = "redirect:Gastos.htm"; } System.out.println("Archi subido correctamente"); } catch (Exception ex) { System.out.println("Error al subir archivo" + ex.getMessage()); } return ruta; }
From source file:com.intranet.intr.contabilidad.SupControllerGastos.java
@RequestMapping(value = "updateGastoRF.htm", method = RequestMethod.POST) public String EupdateGastoRF_post(@ModelAttribute("ga") gastosR ga, BindingResult result, HttpServletRequest request) {//from ww w.j a v a 2 s . c o m String mensaje = ""; String ruta = "redirect:Gastos.htm"; //MultipartFile multipart = c.getArchivo(); System.out.println("olaEnviarMAILS"); String ubicacionArchivo = "C:\\glassfish-4.1.1-web\\glassfish4\\glassfish\\domains\\domain1\\applications\\Intranet\\resources\\fotosfacturas"; //File file=new File(ubicacionArchivo,multipart.getOriginalFilename()); //String ubicacionArchivo="C:\\"; DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1024); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> partes = upload.parseRequest(request); for (FileItem item : partes) { if (gr.getIdgasto() != 0) { if (gastosRService.existe(item.getName()) == false) { System.out.println("updateeeNOMBRE FOTO: " + item.getName()); File file = new File(ubicacionArchivo, item.getName()); item.write(file); gr.setNombreimg(item.getName()); gastosRService.updateGasto(gr); } } else ruta = "redirect:Gastos.htm"; } System.out.println("Archi subido correctamente"); } catch (Exception ex) { System.out.println("Error al subir archivo" + ex.getMessage()); } return ruta; }
From source file:com.estampate.corteI.servlet.guardarEstampa.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request//from www .j av a 2 s . co 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 rutaImg = "NN"; /* SUBIR LA IMAGEN AL SERVIDOR */ dirUploadFiles = getServletContext().getRealPath(getServletContext().getInitParameter("dirUploadFiles")); if (ServletFileUpload.isMultipartContent(request)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(new Long(getServletContext().getInitParameter("maxFileSize")).longValue()); List listUploadFiles = null; FileItem item = null; try { listUploadFiles = upload.parseRequest(request); Iterator it = listUploadFiles.iterator(); while (it.hasNext()) { item = (FileItem) it.next(); if (!item.isFormField()) { if (item.getSize() > 0) { String nombre = item.getName(); String extension = nombre.substring(nombre.lastIndexOf(".")); File archivo = new File(dirUploadFiles, nombre); item.write(archivo); if (archivo.exists()) { subioImagen = true; rutaImg = "estampas/" + nombre; // response.sendRedirect("uploadsave.jsp"); } else { subioImagen = false; } } } else { campos.add(item.getString()); } } } catch (FileUploadException e) { subioImagen = false; } catch (Exception e) { subioImagen = false; } } /* FIN DE SUBIR IMAGEN */ String nombreImg = campos.get(1); EstampaCamiseta estampa = new EstampaCamiseta(); //estampa.setIdEstampaCamiseta(null); //TRAIGO EL ARTISTA PARA GUARDARLO EN LA ESTAMPA datosGeneralesDAO artista = new datosGeneralesDAO(); Artista artEstampa = artista.getArtista(Integer.parseInt(campos.get(0))); estampa.setArtista(artEstampa); //TRAIGO EL ARTISTA PARA GUARDARLO EN LA ESTAMPA datosGeneralesDAO rating = new datosGeneralesDAO(); RatingEstampa ratingEstampa = rating.getRating(1); estampa.setRatingEstampa(ratingEstampa); //TRAIGO EL TAMAO QUE ELIGIERON DE LA ESTAMPA datosGeneralesDAO tamano = new datosGeneralesDAO(); TamanoEstampa tamEstampa = tamano.getTamano(Integer.parseInt(campos.get(4))); estampa.setTamanoEstampa(tamEstampa); //TRAIGO EL TEMA QUE ELIGIERON DE LA ESTAMPA datosGeneralesDAO tema = new datosGeneralesDAO(); TemaEstampa temaEstampa = tema.getTema(Integer.parseInt(campos.get(2))); estampa.setTemaEstampa(temaEstampa); //ASIGNO EL NOMBRE DE LA ESTAMPA estampa.setDescripcion(nombreImg); //ASIGNO LA RUTA DE LA IMAGEN QUE CREO estampa.setImagenes(rutaImg); //ASIGNO LA UBICACION DE LA IMAGEN EN LA CAMISA estampa.setUbicacion(campos.get(5)); //ASIGNO EL PRECIO DE LA IMAGEN QUE CREO estampa.setPrecio(campos.get(3)); //ASIGNO EL ID DEL LUGAR estampa.setIdLugarEstampa(Integer.parseInt(campos.get(5))); guardarRegistroDAO guardarEstampa = new guardarRegistroDAO(); guardarEstampa.guardaEstampa(estampa); processRequest(request, response); }
From source file:com.patrolpro.servlet.UploadJasperReportServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w . ja va 2s .co 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 { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); String companyId = request.getParameter("companyId"); FileItem fileData = null; Integer mobileFormId = null; List<FileItem> fields = upload.parseRequest(request); for (int f = 0; f < fields.size(); f++) { if (fields.get(f).getFieldName().equals("file_data")) { fileData = fields.get(f); } else if (fields.get(f).getFieldName().equals("mobileFormId")) { mobileFormId = Integer.parseInt(fields.get(f).getString()); } } if (fileData == null || !fileData.getName().endsWith(".jrxml")) { out.write("{\"error\": \"Invalid file type! Please select a jrxml (Jasper Report) file!\"}"); out.flush(); } else { InputStream iStream = fileData.getInputStream(); MobileFormService mobileService = new MobileFormService(companyId); ByteArrayOutputStream bOutput = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int bufCount = 0; while ((bufCount = iStream.read(buffer)) > -1) { bOutput.write(buffer, 0, bufCount); } bOutput.flush(); byte[] rawData = bOutput.toByteArray(); JasperReport jasperReport = JasperCompileManager.compileReport(new ByteArrayInputStream(rawData)); JRParameter[] params = jasperReport.getParameters(); HashMap<String, Class> reportParams = new HashMap<String, Class>(); for (int p = 0; p < params.length; p++) { JRParameter param = params[p]; int searchPos = -1; for (int a = 0; a < MobileForms.getReservedIdentifiers().length; a++) { if (MobileForms.getReservedIdentifiers()[a].equals(param.getName())) { searchPos = a; } } if (!param.isSystemDefined() && searchPos < 0 && !param.getName().startsWith("nfc_l_") && !param.getName().endsWith("_loc")) { reportParams.put(param.getName(), param.getValueClass()); } } ByteArrayOutputStream oStream = new ByteArrayOutputStream(); JasperCompileManager.writeReportToXmlStream(jasperReport, oStream); //JasperCompileManager.compileReportToStream(new ByteArrayInputStream(rawData), oStream); MobileForms selectedForm = mobileService.getForm(mobileFormId); selectedForm.setReportData(oStream.toByteArray()); mobileService.saveForm(selectedForm); Iterator<String> keyIterator = reportParams.keySet().iterator(); ArrayList<MobileFormData> currData = mobileService.getFormData(selectedForm.getMobileFormsId()); int numberInserted = 1; while (keyIterator.hasNext()) { String key = keyIterator.next(); boolean hasData = false; for (int d = 0; d < currData.size(); d++) { if (currData.get(d).getDataLabel().equals(key) && currData.get(d).getActive()) { hasData = true; } } if (!hasData) { MobileFormData formData = new MobileFormData(); formData.setActive(true); formData.setMobileFormsId(selectedForm.getMobileFormsId()); formData.setDataLabel(key); if (reportParams.get(key) == Date.class) { formData.setDateType(5); } else if (reportParams.get(key) == InputStream.class) { formData.setDateType(8); } else if (reportParams.get(key) == Boolean.class) { formData.setDateType(3); } else { formData.setDateType(1); } formData.setOrdering(currData.size() + numberInserted); mobileService.saveFormData(formData); numberInserted++; } } out.write("{}"); out.flush(); } } catch (JRException jr) { out.write("{\"error\": \"" + jr.getMessage().replaceAll("\n", "").replaceAll(":", "").replaceAll("\t", "") + "\"}"); out.flush(); } catch (Exception e) { out.write("{\"error\": \"Exception uploading report, " + e + "\"}"); out.flush(); } finally { out.close(); } }
From source file:graphvis.webui.servlets.UploadServlet.java
/** * This method receives POST from the index.jsp page and uploads file, * converts into the correct format then places in the HDFS. */// w ww . j a va2 s .c o m protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { response.setStatus(403); return; } File tempDirFileObject = new File(Configuration.tempDirectory); // Create/remove temp folder if (tempDirFileObject.exists()) { FileUtils.deleteDirectory(tempDirFileObject); } // (Re-)create temp directory tempDirFileObject.mkdir(); FileUtils.copyFile( new File(getServletContext() .getRealPath("giraph-1.1.0-SNAPSHOT-for-hadoop-2.2.0-jar-with-dependencies.jar")), new File(Configuration.tempDirectory + "/giraph-1.1.0-SNAPSHOT-for-hadoop-2.2.0-jar-with-dependencies.jar")); FileUtils.copyFile(new File(getServletContext().getRealPath("dist-graphvis.jar")), new File(Configuration.tempDirectory + "/dist-graphvis.jar")); // 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(Configuration.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"))); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(Configuration.MAX_REQUEST_SIZE); String fileName = ""; try { // Parse the request List<?> items = upload.parseRequest(request); Iterator<?> iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { fileName = new File(item.getName()).getName(); String filePath = Configuration.tempDirectory + File.separator + fileName; File uploadedFile = new File(filePath); System.out.println(filePath); // saves the file to upload directory try { item.write(uploadedFile); } catch (Exception ex) { throw new ServletException(ex); } } } String fullFilePath = Configuration.tempDirectory + File.separator + fileName; String extension = FilenameUtils.getExtension(fullFilePath); // Load Files intoHDFS // (This is where we do the parsing.) loadIntoHDFS(fullFilePath, extension); getServletContext().setAttribute("fileName", new File(fullFilePath).getName()); getServletContext().setAttribute("fileExtension", extension); // Displays fileUploaded.jsp page after upload finished getServletContext().getRequestDispatcher("/fileUploaded.jsp").forward(request, response); } catch (FileUploadException ex) { throw new ServletException(ex); } }