List of usage examples for org.apache.commons.fileupload.disk DiskFileItemFactory DiskFileItemFactory
public DiskFileItemFactory()
From source file:com.cmart.PageControllers.SellItemImagesController.java
/** * This method checks the page for any input errors that may have come from Client generator error * These would need to be check in real life to stop users attempting to hack and mess with things * /*from ww w .j ava 2s .c om*/ * @param request * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com) */ public void checkInputs(HttpServletRequest request) { super.startTimer(); if (request != null) { // If there is a multiform there are probably pictures if (ServletFileUpload.isMultipartContent(request)) { // Get the parameters try { // Create the objects needed to read the parameters factory = new DiskFileItemFactory(); factory.setRepository(GV.LOCAL_TEMP_DIR); upload = new ServletFileUpload(factory); items = upload.parseRequest(request); Iterator<FileItem> iter = items.iterator(); TreeMap<String, String> params = new TreeMap<String, String>(); // Go through all the parameters and get the ones that are form fields while (iter.hasNext()) { FileItem item = iter.next(); // If the item is a parameter, read it if (item.isFormField()) { params.put(item.getFieldName(), item.getString()); } else { this.images.add(item); } } /* * Get the parameters */ // Get the userID if (params.containsKey("userID")) { try { this.userID = Long.parseLong(params.get("userID")); if (this.userID < 0) if (!errors.contains(GlobalErrors.userIDLessThanZero)) errors.add(GlobalErrors.userIDLessThanZero); } catch (NumberFormatException e) { if (!errors.contains(GlobalErrors.userIDNotAnInteger)) errors.add(GlobalErrors.userIDNotAnInteger); } } else { if (!errors.contains(GlobalErrors.userIDNotPresent)) errors.add(GlobalErrors.userIDNotPresent); } // We nned to get the html5 tag as the parent cannot do the normal parsing if (params.containsKey("useHTML5")) { try { int u5 = Integer.parseInt(params.get("useHTML5")); if (u5 == 1) this.useHTML5 = true; else this.useHTML5 = false; } catch (Exception e) { this.useHTML5 = false; } } // Get the authToken if (params.containsKey("authToken")) { this.authToken = params.get("authToken"); if (this.authToken.equals(EMPTY)) if (!errors.contains(GlobalErrors.authTokenEmpty)) errors.add(GlobalErrors.authTokenEmpty); } else { if (!errors.contains(GlobalErrors.authTokenNotPresent)) errors.add(GlobalErrors.authTokenNotPresent); } // Get the itemID if (params.containsKey("itemID")) { try { this.itemID = Long.parseLong(params.get("itemID")); if (this.itemID <= 0) if (!errors.contains(GlobalErrors.itemIDLessThanZero)) errors.add(GlobalErrors.itemIDLessThanZero); } catch (NumberFormatException e) { if (!errors.contains(GlobalErrors.itemIDNotAnInteger)) errors.add(GlobalErrors.itemIDNotAnInteger); } } else { if (!errors.contains(GlobalErrors.itemIDNotPresent)) errors.add(GlobalErrors.itemIDNotPresent); } } catch (FileUploadException e1) { // TODO Auto-generated catch block //System.out.println("SellItemImageController (checkInputs): There was an error in the multi-form"); e1.printStackTrace(); } } // Do normal request processing else { super.checkInputs(request); // Get the userID (if exists), we will pass it along to the next pages try { this.userID = CheckInputs.checkUserID(request); } catch (Error e) { // The user must be logged in to upload the images if (!errors.contains(e)) errors.add(e); } // Get the authToken (if exists), we will pass it along to the next pages try { this.authToken = CheckInputs.checkAuthToken(request); } catch (Error e) { if (!errors.contains(e)) errors.add(e); } // Get the itemID try { this.itemID = CheckInputs.checkItemID(request); if (this.itemID <= 0) if (!errors.contains(GlobalErrors.itemIDLessThanZero)) errors.add(GlobalErrors.itemIDLessThanZero); } catch (Error e) { if (!errors.contains(e)) errors.add(e); this.itemID = -1; } } } // Calculate how long that took super.stopTimerAddParam(); }
From source file:it.lufraproini.cms.servlet.Upload.java
private Map prendiInfo(HttpServletRequest request) throws FileUploadException { Map info = new HashMap(); Map files = new HashMap(); //riutilizzo codice prof. Della Penna per l'upload if (ServletFileUpload.isMultipartContent(request)) { // Funzioni delle librerie Apache per l'upload FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items; items = upload.parseRequest(request); ////from www . jav a 2 s . co m for (FileItem item : items) { String name = item.getFieldName(); //le form che prevedono l'upload di un file devono avere il campo del file chiamato in questo modo if (name.startsWith("file_to_upload")) { files.put(name, item); } else { info.put(name, item.getString()); } } info.put("files", files); return info; } return null; }
From source file:co.com.rempe.impresiones.negocio.servlets.SubirArchivosServlet.java
private Respuesta subirArchivo(HttpServletRequest request) throws FileUploadException, Exception { Respuesta respuesta = new Respuesta(); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); // req es la HttpServletRequest que recibimos del formulario. // Los items obtenidos sern cada uno de los campos del formulario, // tanto campos normales como ficheros subidos. // System.out.println("Items-------"); List items = upload.parseRequest(request); System.out.println(items);//from w w w. j a v a 2 s .co m // System.out.println("Request-----------------"); System.out.println(request); // Se recorren todos los items, que son de tipo FileItem for (Object item : items) { FileItem uploaded = (FileItem) item; // Hay que comprobar si es un campo de formulario. Si no lo es, se guarda el fichero // subido donde nos interese // System.out.println("Item---------------"); System.out.println(uploaded.isFormField()); if (!uploaded.isFormField()) { // No es campo de formulario, guardamos el fichero en algn sitio //El sisguiente bloque simplemente es para divorciar el nombre del archivo de las rutas //posibles que pueda traernos el getName() sobre el objeto de la clase FileItem, //pues he descuvierto que el explorer especificamente es el nico que enva //la ruta adjuntada al nombre, por lo cual es importante corregirlo. String nombreArchivo = uploaded.getName(); String cadena = nombreArchivo; System.out.println(cadena); while (cadena.contains("\\")) { cadena = cadena.replace("\\", "&"); } // System.out.println(cadena); String[] ruta = cadena.split("&"); for (int i = 0; i < ruta.length; i++) { String string = ruta[i]; System.out.println(string); } nombreArchivo = ruta[ruta.length - 1]; // System.out.println("Ruta archivo: " + nombreArchivo); //Fin correccin nombre. String nombreArchivoEscrito = System.currentTimeMillis() + "-" + nombreArchivo; String rutaEscritura = new File(request.getRealPath("archivos-subidos"), nombreArchivoEscrito) .toString(); File fichero = new File(rutaEscritura); ArchivosAdjuntos archivo = new ArchivosAdjuntos(); archivo.setNombreArchivo(nombreArchivo); archivo.setRutaArchivo(rutaEscritura); archivo.setTamanioArchivo(uploaded.getSize()); if (nombreArchivo.endsWith(".pdf") || nombreArchivo.endsWith(".png") || nombreArchivo.endsWith(".jpg") || nombreArchivo.endsWith(".bmp") || nombreArchivo.endsWith(".svg")) { // System.out.println("Archivo subido: " + uploaded.getName()); uploaded.write(fichero); respuesta.setCodigo(1); respuesta.setDatos(archivo); respuesta.setMensaje("Se ha subido exitosamente el archivo: " + uploaded.getName()); } else { respuesta.setCodigo(0); respuesta.setDatos(archivo); respuesta.setMensaje("El formato del archivo " + nombreArchivo + " es invalido!"); } } // else { // // es un campo de formulario, podemos obtener clave y valor // String key = uploaded.getFieldName(); // String valor = uploaded.getString(); // System.out.println("Archivo subido: " + key); // } } return respuesta; }
From source file:com.ccsna.safetynet.AdminNewsServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// w w w . j a va2s . 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"); try { PrintWriter out = response.getWriter(); String smallUrl = "", largeUrl = "", message = "", title = "", content = "", startDate = "", endDate = "", newsType = "", st = "", endTime = "", startTime = "", fileType = null; Date sDate = null, eDate = null; Time eTime = null, sTime = null; String fullPath = null; int action = 0, newsId = 0; boolean dataValid = true; News news = null; Member loggedInMember = UserAuthenticator.loggedInUser(request.getSession()); if (loggedInMember != null) { String home = ""; String alertPage = ""; if (loggedInMember.getRole().equals(Menu.MEMBER)) { home = "/pages/member.jsp"; alertPage = "/pages/memberAlert.jsp"; } else { home = "/pages/agencyAdmin.jsp"; alertPage = "/pages/editAlert.jsp"; } log.info("home page is : " + home); log.info("alert page is : " + alertPage); String createdBy = String.valueOf(loggedInMember.getMemberId()); boolean isMultipart = ServletFileUpload.isMultipartContent(request); log.info("isMultipart :" + isMultipart); if (isMultipart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); String appPath = request.getServletContext().getRealPath(""); //String glassfishInstanceRootPropertyName = "com.sun.aas.instanceRoot"; //String instanceRoot = System.getProperty(glassfishInstanceRootPropertyName) + "/applications/user-pix/"; try { List items = upload.parseRequest(request); Iterator iterator = items.iterator(); while (iterator.hasNext()) { FileItem item = (FileItem) iterator.next(); if (!item.isFormField()) { //log.info("item is form field"); String fileName = item.getName(); //log.info("the name of the item is :" + fileName); String contentType = item.getContentType(); //log.info("the content type is :" + contentType); if (item.getContentType().equalsIgnoreCase(JPEG) || item.getContentType().equalsIgnoreCase(JPG) || item.getContentType().equalsIgnoreCase(PDF)) { String root = appPath; log.info("pdf content recognised"); log.info("root path is :" + appPath); //String smallLoc = "/uploads/small"; String largeLoc = "/uploads/large"; log.info("largeLoc:" + largeLoc); //File pathSmall = new File(root + smallLoc); File pathLarge = new File(root + largeLoc); //log.info("small image path :" + pathSmall); log.info("large image path :" + pathLarge); if (!pathLarge.exists()) { // boolean status = pathSmall.mkdirs(); pathLarge.mkdirs(); } if (item.getContentType().equalsIgnoreCase(PDF)) { log.info("loading pdf file"); fileType = Menu.PDF; fileName = createdBy + "_" + System.currentTimeMillis() + "." + PDF_EXTENSION; //File uploadedFileSmall = new File(pathSmall + "/" + fileName); File uploadedFileLarge = new File(pathLarge + "/" + fileName); Menu.uploadPdfFile(item.getInputStream(), uploadedFileLarge); } else { fileType = Menu.IMAGE; fileName = createdBy + "_" + System.currentTimeMillis() + "." + JPEG_EXTENSION; log.info("filename is : " + fileName); // File uploadedFileSmall = new File(pathSmall + "/" + fileName); File uploadedFileLarge = new File(pathLarge + "/" + fileName); //Menu.resizeImage(item.getInputStream(), 160, uploadedFileSmall); Menu.resizeImage(item.getInputStream(), 160, uploadedFileLarge); } //smallUrl = smallLoc + "/" + fileName + ""; largeUrl = largeLoc + "/" + fileName + ""; log.info("largeUrl image url is :" + largeUrl); fullPath = request.getContextPath() + "/" + largeUrl; } } else { if (item.getFieldName().equalsIgnoreCase("newsTitle")) { title = item.getString(); log.info("title is :" + title); } if (item.getFieldName().equalsIgnoreCase("type")) { newsType = item.getString(); log.info("newsType is :" + newsType); } if (item.getFieldName().equalsIgnoreCase("content")) { content = item.getString(); log.info("content is :" + content); } if (item.getFieldName().equalsIgnoreCase("start_Date")) { startDate = item.getString(); if (startDate != null && !startDate.isEmpty()) { sDate = Menu .convertDateToSqlDate(Menu.stringToDate(startDate, "yyyy-MM-dd")); } log.info("startDate is :" + startDate); } if (item.getFieldName().equalsIgnoreCase("end_Date")) { endDate = item.getString(); if (endDate != null && !endDate.isEmpty()) { eDate = Menu.convertDateToSqlDate(Menu.stringToDate(endDate, "yyyy-MM-dd")); } log.info("endDate is :" + endDate); } if (item.getFieldName().equalsIgnoreCase("action")) { action = Integer.parseInt(item.getString()); log.info("the action is :" + action); } if (item.getFieldName().equalsIgnoreCase("newsId")) { newsId = Integer.parseInt(item.getString()); log.info("the newsid is :" + newsId); } if (item.getFieldName().equalsIgnoreCase("status")) { st = item.getString(); log.info("the status is :" + st); } if (item.getFieldName().equalsIgnoreCase("end_Time")) { endTime = item.getString(); if (endTime != null && !endTime.isEmpty()) { eTime = Menu.convertStringToSqlTime(endTime); } log.info("eTime is :" + eTime); } if (item.getFieldName().equalsIgnoreCase("start_Time")) { startTime = item.getString(); if (startTime != null && !startTime.isEmpty()) { sTime = Menu.convertStringToSqlTime(startTime); } log.info("sTime is :" + sTime); } } } } catch (FileUploadException e) { e.printStackTrace(); } } switch (Validation.Actions.values()[action]) { case CREATE: log.info("creating new serlvet ................"); news = new NewsModel().addNews(title, newsType, content, sDate, eDate, new Date(), createdBy, Menu.ACTIVE, largeUrl, fileType, fullPath); if (news != null) { log.info("news successfully created..."); message += "News item has been successfully added"; Validation.setAttributes(request, Validation.SUCCESS, message); response.sendRedirect(request.getContextPath() + home); } else { log.info("news creating failed..."); message += "Unable to add news item"; Validation.setAttributes(request, Validation.ERROR, message); response.sendRedirect(request.getContextPath() + home); } break; case UPDATE: log.info("updating news ..."); if (title != null && !title.isEmpty()) { news = new NewsModel().findByParameter("title", title); } if (news != null && (news.getNewsId() == newsId)) { log.info("news is :" + news.getNewsId()); dataValid = true; } else { dataValid = false; } if (news == null) { dataValid = true; } log.info("dataValid is :" + dataValid); if (dataValid) { boolean newsUpdated = new NewsModel().updateNews(newsId, title, newsType, content, sDate, eDate, createdBy, st, largeUrl, smallUrl, sTime, eTime); if (newsUpdated) { message += "News/Alert has been successfully updated"; Validation.setAttributes(request, Validation.SUCCESS, message); response.sendRedirect(request.getContextPath() + home); } else { message += "Unable to update news item"; Validation.setAttributes(request, Validation.ERROR, message); response.sendRedirect(request.getContextPath() + alertPage + "?id=" + newsId); } } else { message += "News with same title already exist, Enter a different title"; Validation.setAttributes(request, Validation.ERROR, message); response.sendRedirect(request.getContextPath() + alertPage + "?id=" + newsId); } break; } } else { message += "Session expired, Kindly login with username and password"; Validation.setAttributes(request, Validation.ERROR, message); response.sendRedirect(request.getContextPath() + "/index.jsp"); } } catch (Exception e) { } }
From source file:com.ikon.servlet.WorkflowRegisterServlet.java
@SuppressWarnings("unchecked") private String handleRequest(HttpServletRequest request) throws FileUploadException, IOException, Exception { log.debug("handleRequest({})", request); if (ServletFileUpload.isMultipartContent(request)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); if (items.isEmpty()) { String msg = "No process file in the request"; log.warn(msg);//from w ww . ja v a 2s .c om return msg; } else { FileItem fileItem = (FileItem) items.get(0); if (fileItem.getContentType().indexOf("application/x-zip-compressed") == -1) { String msg = "Not a process archive"; log.warn(msg); throw new Exception(msg); } else { log.info("Deploying process archive: {}", fileItem.getName()); JbpmContext jbpmContext = JBPMUtils.getConfig().createJbpmContext(); InputStream isForms = null; ZipInputStream zis = null; try { zis = new ZipInputStream(fileItem.getInputStream()); ProcessDefinition processDefinition = ProcessDefinition.parseParZipInputStream(zis); // Check XML form definition FileDefinition fileDef = processDefinition.getFileDefinition(); isForms = fileDef.getInputStream("forms.xml"); FormUtils.parseWorkflowForms(isForms); log.debug("Created a processdefinition: {}", processDefinition.getName()); jbpmContext.deployProcessDefinition(processDefinition); return "Process " + processDefinition.getName() + " deployed successfully"; } finally { IOUtils.closeQuietly(isForms); IOUtils.closeQuietly(zis); jbpmContext.close(); } } } } else { log.warn("Not a multipart request"); return "Not a multipart request"; } }
From source file:com.woonoz.proxy.servlet.HttpEntityEnclosingRequestHandler.java
private HttpEntity createMultipartEntity(HttpServletRequest request) throws FileUploadException, IOException { DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); MultipartEntity multipartEntity = new MultipartEntity(); FileItemIterator iterator = servletFileUpload.getItemIterator(request); while (iterator.hasNext()) { FileItemStream fileItem = iterator.next(); final String partName = fileItem.getFieldName(); if (fileItem.isFormField()) { multipartEntity.addPart(partName, buildStringBody(fileItem)); } else {//ww w. j a va 2 s . c o m multipartEntity.addPart(partName, buildContentBodyFromFileItem(fileItem)); } } return multipartEntity; }
From source file:com.mylop.servlet.ImageServlet.java
public void uploadImage(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("application/json"); boolean isMultipart = ServletFileUpload.isMultipartContent(request); HttpSession session = request.getSession(); String account = (String) session.getAttribute("userid"); if (isMultipart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try {/*from w w w.j a v a2 s.co m*/ List<FileItem> multiparts = upload.parseRequest(request); for (FileItem item : multiparts) { if (!item.isFormField()) { String contentType = item.getContentType(); String[] ext = contentType.split("/"); String fileName = UPLOAD_DIRECTORY + File.separator + account + "_Avatar"; File file = new File(fileName); item.write(file); String avatarUrl = "http://mylop.tk:8080/Avatar/" + account + "_Avatar"; ProfileModel pm = new ProfileModel(); Map<String, String> update = new HashMap<String, String>(); update.put("avatar", avatarUrl); pm.updateProfile(account, update); } } } catch (Exception e) { e.printStackTrace(); } } String json = "{\"message\": \"success\"}"; response.getWriter().write(json); }
From source file:com.rubinefocus.admin.servlet.UploadProductImage.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request//w w w .jav a 2 s.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 { File f = new File(this.getServletContext().getRealPath("admin/assets/images/products")); String savePath = f.getPath(); savePath = savePath.replace("%20", " "); savePath = savePath.replace("build", ""); String fileName = ""; boolean isMultipart = ServletFileUpload.isMultipartContent(request); // process only if its multipart content if (isMultipart) { // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); try { // Parse the request List<FileItem> multiparts = upload.parseRequest(request); for (FileItem item : multiparts) { if (!item.isFormField()) { fileName = new File(item.getName()).getName(); File file = new File(savePath + "/" + fileName); if (file.exists()) { String fileNameWithOutExt = FilenameUtils.removeExtension(fileName); String ext = FilenameUtils.getExtension(fileName); fileName = fileNameWithOutExt + new SimpleDateFormat("dd-MM-yyyy HH:mm:ss").format(new Date()) + "." + ext; fileName = fileName.replace(" ", ""); fileName = fileName.replace("-", ""); fileName = fileName.replace(":", ""); item.write(new File(savePath + File.separator + fileName)); } else { item.write(new File(savePath + File.separator + fileName)); } Gson gson = new Gson(); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(gson.toJson(fileName)); } } } catch (Exception e) { e.printStackTrace(); } } }
From source file:ai.h2o.servicebuilder.MakePythonWarServlet.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Long startTime = System.currentTimeMillis(); File tmpDir = null;/*from w ww .j a v a 2 s .co m*/ try { //create temp directory tmpDir = createTempDirectory("makeWar"); logger.debug("tmpDir " + tmpDir); // create output directories File webInfDir = new File(tmpDir.getPath(), "WEB-INF"); if (!webInfDir.mkdir()) throw new Exception("Can't create output directory (WEB-INF)"); File outDir = new File(webInfDir.getPath(), "classes"); if (!outDir.mkdir()) throw new Exception("Can't create output directory (WEB-INF/classes)"); File libDir = new File(webInfDir.getPath(), "lib"); if (!libDir.mkdir()) throw new Exception("Can't create output directory (WEB-INF/lib)"); // get input files List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); String pojofile = null; String jarfile = null; String mojofile = null; String pythonfile = null; String predictorClassName = null; String pythonenvfile = null; ArrayList<String> pojos = new ArrayList<String>(); ArrayList<String> rawfiles = new ArrayList<String>(); for (FileItem i : items) { String field = i.getFieldName(); String filename = i.getName(); if (filename != null && filename.length() > 0) { if (field.equals("pojo")) { // pojo file name, use this or a mojo file pojofile = filename; pojos.add(pojofile); predictorClassName = filename.replace(".java", ""); FileUtils.copyInputStreamToFile(i.getInputStream(), new File(tmpDir, filename)); logger.info("added pojo model {}", filename); } if (field.equals("jar")) { jarfile = "WEB-INF" + File.separator + "lib" + File.separator + filename; FileUtils.copyInputStreamToFile(i.getInputStream(), new File(libDir, filename)); } if (field.equals("python")) { pythonfile = "WEB-INF" + File.separator + "python.py"; FileUtils.copyInputStreamToFile(i.getInputStream(), new File(webInfDir, "python.py")); } if (field.equals("pythonextra")) { // optional extra files for python pythonfile = "WEB-INF" + File.separator + "lib" + File.separator + filename; FileUtils.copyInputStreamToFile(i.getInputStream(), new File(libDir, filename)); } if (field.equals("mojo")) { // a raw model zip file, a mojo file (optional) mojofile = filename; rawfiles.add(mojofile); predictorClassName = filename.replace(".zip", ""); FileUtils.copyInputStreamToFile(i.getInputStream(), new File(tmpDir, filename)); logger.info("added mojo model {}", filename); } if (field.equals("envfile")) { // optional conda environment file pythonenvfile = filename; FileUtils.copyInputStreamToFile(i.getInputStream(), new File(tmpDir, filename)); logger.debug("using conda environment file {}", pythonenvfile); } } } logger.debug("jar {} pojo {} mojo {} python {} envfile {}", jarfile, pojofile, mojofile, pythonfile, pythonenvfile); if ((pojofile == null || jarfile == null) && (mojofile == null || jarfile == null)) throw new Exception("need either pojo and genmodel jar, or raw file and genmodel jar "); if (pojofile != null) { // Compile the pojo runCmd(tmpDir, Arrays.asList("javac", "-target", JAVA_TARGET_VERSION, "-source", JAVA_TARGET_VERSION, "-J-Xmx" + MEMORY_FOR_JAVA_PROCESSES, "-cp", jarfile, "-d", outDir.getPath(), pojofile), "Compilation of pojo failed"); logger.info("compiled pojo {}", pojofile); } if (servletPath == null) throw new Exception("servletPath is null"); FileUtils.copyDirectoryToDirectory(new File(servletPath, "extra"), tmpDir); String extraPath = "extra" + File.separator; String webInfPath = extraPath + File.separator + "WEB-INF" + File.separator; String srcPath = extraPath + "src" + File.separator; copyExtraFile(servletPath, extraPath, tmpDir, "pyindex.html", "index.html"); copyExtraFile(servletPath, extraPath, tmpDir, "jquery.js", "jquery.js"); copyExtraFile(servletPath, extraPath, tmpDir, "predict.js", "predict.js"); copyExtraFile(servletPath, extraPath, tmpDir, "custom.css", "custom.css"); copyExtraFile(servletPath, webInfPath, webInfDir, "web-pythonpredict.xml", "web.xml"); FileUtils.copyDirectoryToDirectory(new File(servletPath, webInfPath + "lib"), webInfDir); FileUtils.copyDirectoryToDirectory(new File(servletPath, extraPath + "bootstrap"), tmpDir); FileUtils.copyDirectoryToDirectory(new File(servletPath, extraPath + "fonts"), tmpDir); // change the class name in the predictor template file to the predictor we have String modelCode = null; if (!pojos.isEmpty()) { FileUtils.writeLines(new File(tmpDir, "modelnames.txt"), pojos); modelCode = "null"; } else if (!rawfiles.isEmpty()) { FileUtils.writeLines(new File(tmpDir, "modelnames.txt"), rawfiles); modelCode = "MojoModel.load(fileName)"; } InstantiateJavaTemplateFile(tmpDir, modelCode, predictorClassName, "null", pythonenvfile == null ? "" : pythonenvfile, srcPath + "ServletUtil-TEMPLATE.java", "ServletUtil.java"); copyExtraFile(servletPath, srcPath, tmpDir, "PredictPythonServlet.java", "PredictPythonServlet.java"); copyExtraFile(servletPath, srcPath, tmpDir, "InfoServlet.java", "InfoServlet.java"); copyExtraFile(servletPath, srcPath, tmpDir, "StatsServlet.java", "StatsServlet.java"); copyExtraFile(servletPath, srcPath, tmpDir, "PingServlet.java", "PingServlet.java"); copyExtraFile(servletPath, srcPath, tmpDir, "Transform.java", "Transform.java"); copyExtraFile(servletPath, srcPath, tmpDir, "Logging.java", "Logging.java"); // compile extra runCmd(tmpDir, Arrays.asList("javac", "-target", JAVA_TARGET_VERSION, "-source", JAVA_TARGET_VERSION, "-J-Xmx" + MEMORY_FOR_JAVA_PROCESSES, "-cp", "WEB-INF/lib/*:WEB-INF/classes:extra/WEB-INF/lib/*", "-d", outDir.getPath(), "InfoServlet.java", "StatsServlet.java", "PredictPythonServlet.java", "ServletUtil.java", "PingServlet.java", "Transform.java", "Logging.java"), "Compilation of servlet failed"); // create the war jar file Collection<File> filesc = FileUtils.listFilesAndDirs(webInfDir, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE); filesc.add(new File(tmpDir, "index.html")); filesc.add(new File(tmpDir, "jquery.js")); filesc.add(new File(tmpDir, "predict.js")); filesc.add(new File(tmpDir, "custom.css")); filesc.add(new File(tmpDir, "modelnames.txt")); for (String m : pojos) { filesc.add(new File(tmpDir, m)); } for (String m : rawfiles) { filesc.add(new File(tmpDir, m)); } Collection<File> dirc = FileUtils.listFilesAndDirs(new File(tmpDir, "bootstrap"), TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE); filesc.addAll(dirc); dirc = FileUtils.listFilesAndDirs(new File(tmpDir, "fonts"), TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE); filesc.addAll(dirc); File[] files = filesc.toArray(new File[] {}); if (files.length == 0) throw new Exception("Can't list compiler output files (out)"); byte[] resjar = createJarArchiveByteArray(files, tmpDir.getPath() + File.separator); if (resjar == null) throw new Exception("Can't create war of compiler output"); logger.info("war created from {} files, size {}", files.length, resjar.length); // send jar back ServletOutputStream sout = response.getOutputStream(); response.setContentType("application/octet-stream"); String outputFilename = predictorClassName.length() > 0 ? predictorClassName : "h2o-predictor"; response.setHeader("Content-disposition", "attachment; filename=" + outputFilename + ".war"); response.setContentLength(resjar.length); sout.write(resjar); sout.close(); response.setStatus(HttpServletResponse.SC_OK); Long elapsedMs = System.currentTimeMillis() - startTime; logger.info("Done python war creation in {}", elapsedMs); } catch (Exception e) { logger.error("doPost failed", e); // send the error message back String message = e.getMessage(); if (message == null) message = "no message"; logger.error(message); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.getWriter().write(message); response.getWriter().write(Arrays.toString(e.getStackTrace())); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } finally { // if the temp directory is still there we delete it if (tmpDir != null && tmpDir.exists()) { try { FileUtils.deleteDirectory(tmpDir); } catch (IOException e) { logger.error("Can't delete tmp directory"); } } } }
From source file:Admin.products.ProductUpdateS.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w . jav a 2 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 { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { try { String product_id = null; String product_name = null; String description = null; String specifications_name = null; //[] String specifications_value = null;//[] String specifications_unit = null;//[] String purchase_date = null; String MFD = null; String EXP = null; String purchase_price = null; // String old_price = null; String discount = null; String selling_price = null; String w_years = null; String w_months = null; String w_dates = null; String QTY = null; String pickup = null; String delivery_pond = null; String delivery_days = null; String delivery_area = null;//[] String images0 = null; String images = null;//[] String rurl = null; Collecter01.i = 0; // ilagata sepe collect karanna kalin Collecter01.specifications.clear(); Collecter01.delivery_areas = ""; Collecter01.product_images.clear(); FileItemFactory item = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(item); List<FileItem> list = upload.parseRequest(request); for (FileItem fileItem : list) { if (fileItem.isFormField()) { //form field switch (fileItem.getFieldName()) { case "hid01n": System.out.println("PRODUCT_ID---------:" + fileItem.getString()); product_id = fileItem.getString(); if (checkDigit(product_id)) { rurl = "04_admin/product/product_update.jsp?upd01n=" + product_id + "&"; } else { rurl = "04_admin/product/product_update.jsp?upd01n=" + product_id + "&"; response.sendRedirect(rurl + "msg=Please enter the product id"); } break; case "txf01n": System.out.println("PRODUCT_NAME---------:" + fileItem.getString()); product_name = fileItem.getString(); if (checkString(product_name.trim())) { } else { response.sendRedirect(rurl + "msg=Please enter the product name"); } break; case "txa01n": System.out.println("DESCRIPTION----------:" + fileItem.getString()); description = fileItem.getString(); if (checkString(description.trim())) { } else { response.sendRedirect(rurl + "msg=Please enter the description"); } break; case "spe01n": System.out.println("SPECIFICATION_NAME----------:" + fileItem.getString()); specifications_name = fileItem.getString(); if (checkString(specifications_name.trim())) { Collecter01.collectSpec(specifications_name.trim()); } else { response.sendRedirect(rurl + "msg=Please enter the specifications name"); } break; case "spe02n": System.out.println("SPECIFICATION_VALUE---------:" + fileItem.getString()); specifications_value = fileItem.getString(); if (checkString(specifications_value.trim())) { Collecter01.collectSpec(specifications_value.trim()); } else { response.sendRedirect(rurl + "msg=Please enter the specifications value"); } break; case "spe03n": System.out.println("SPECIFICATION_UNIT----------:" + fileItem.getString()); specifications_unit = fileItem.getString(); if (specifications_unit == null || specifications_unit.equals("")) { specifications_unit = ""; } else { Collecter01.collectSpec(specifications_unit.trim()); } break; case "dat01n": System.out.println("PURCHASE_DATE--------:" + fileItem.getString()); purchase_date = fileItem.getString(); if (checkString(purchase_date)) { } else { response.sendRedirect(rurl + "msg=Please select the purchase date"); } break; case "dat02n": System.out.println("MFD------------------:" + fileItem.getString()); MFD = fileItem.getString(); if (checkString(MFD)) { } else { response.sendRedirect(rurl + "msg=Please select the MFD"); } break; case "dat03n": System.out.println("EXP------------------:" + fileItem.getString()); EXP = fileItem.getString(); if (checkString(EXP)) { } else { response.sendRedirect(rurl + "msg=Please enter the EXP"); } break; case "num01n": System.out.println("PURCHASE_price-------:" + fileItem.getString()); purchase_price = fileItem.getString(); if (checkDigit(purchase_price)) { } else { response.sendRedirect(rurl + "msg=Please enter the purchase price"); } break; case "num03n": System.out.println("DISCOUNT-------------:" + fileItem.getString() + " %"); discount = fileItem.getString(); if (checkDigit(discount)) { } else { response.sendRedirect(rurl + "msg=Please enter the discount"); } break; case "num04n": System.out.println("SELLING_PRICE--------:" + fileItem.getString()); selling_price = fileItem.getString(); if (checkDigit(selling_price)) { } else { response.sendRedirect(rurl + "msg=Please enter the selling price value"); } break; case "num05n": System.out.println("W_YEARS--------------:" + fileItem.getString()); w_years = fileItem.getString(); if (checkDigit(w_years)) { } else { response.sendRedirect(rurl + "msg=Please enter the warrenty years"); } break; case "num06n": System.out.println("W_MONTS--------------:" + fileItem.getString()); w_months = fileItem.getString(); if (checkDigit(w_months)) { } else { response.sendRedirect(rurl + "msg=Please enter the warrenty months"); } break; case "num07n": System.out.println("W_DATES--------------:" + fileItem.getString()); w_dates = fileItem.getString(); if (checkDigit(w_dates)) { } else { response.sendRedirect(rurl + "msg=Please enter th warrenty dates"); } break; case "num08n": System.out.println("QTY------------------:" + fileItem.getString()); QTY = fileItem.getString(); if (checkDigit(QTY)) { } else { response.sendRedirect(rurl + "msg=Please enter the QTY"); } break; case "sel05n": System.out.println("PICKUP---------------:" + fileItem.getString()); pickup = fileItem.getString(); if (checkString(pickup)) { } else { response.sendRedirect(rurl + "msg=Please select the pickup"); } break; case "sel06n": System.out.println("DELIVERY_POND--------:" + fileItem.getString()); delivery_pond = fileItem.getString(); if (checkString(delivery_pond)) { } else { response.sendRedirect(rurl + "msg=Please select the pay on delivery"); } break; case "num09n": System.out.println("DELIVERY_DAYS--------:" + fileItem.getString()); if (delivery_pond.trim().equals("Yes")) { delivery_days = fileItem.getString(); if (checkDigit(delivery_days)) { } else { response.sendRedirect(rurl + "msg=Please add the delivery dates"); } } else { } break; case "sel07n": System.out.println("DELIVERY_AREA--------:" + fileItem.getString());//[] if (delivery_pond.trim().equals("Yes")) { delivery_area = fileItem.getString(); if (checkString(delivery_area)) { // Collecter01.collectDeliveryArea(delivery_area.trim()); } else { response.sendRedirect(rurl + "msg=Please select the delivery areas"); } } else { } break; case "hid02n": System.out.println("DELETE--------:" + fileItem.getString()); images0 = fileItem.getString(); if (checkString(images0)) { for (String imn : images0.split(">")) { System.out.println(imn); } } else { System.out.println("delete natha"); // response.sendRedirect(rurl + "msg=Please select the pay on delivery"); } break; default: break; } } else { images = fileItem.getName(); System.out.println(images); if (checkString(images)) { Long time = System.currentTimeMillis(); System.out.println("IMAGES_name----------:" + time); String apath = request.getServletContext().getRealPath("/04_admin/product/img/") + "\\" + time + ".jpg"; System.out.println("IMAGES_AP------------:" + apath); String rpath = "04_admin\\product\\img\\" + time + ".jpg"; System.out.println("IMAGES_RP------------:" + rpath); fileItem.write(new File(apath)); Collecter01.collectImages(rpath); } else { // response.sendRedirect(rurl + "msg=Please select images"); } } } System.out.println(checkString(product_id)); System.out.println(checkString(product_name)); System.out.println(checkString(description)); // System.out.println(specifications_name); //null // System.out.println(specifications_value); //null // System.out.println(specifications_unit); //null System.out.println(checkString(purchase_date)); System.out.println(checkString(MFD)); System.out.println(checkString(EXP)); System.out.println(checkDigit(purchase_price)); System.out.println(checkDigit(selling_price)); System.out.println(checkDigit(discount)); System.out.println(checkDigit(w_years)); System.out.println(checkDigit(w_months)); System.out.println(checkDigit(w_dates)); System.out.println(checkDigit(QTY)); System.out.println(checkString(pickup)); System.out.println(checkString(delivery_pond)); System.out.println(delivery_pond.trim().equals("Yes") ? checkDigit(delivery_days) : true); System.out.println(delivery_pond.trim().equals("Yes") ? checkString(delivery_area) : true); System.out.println(checkString(images)); if (checkDigit(product_id) && checkString(product_name) && checkString(description) && checkString(purchase_date) && checkString(MFD) && checkString(EXP) && checkDigit(purchase_price) && checkDigit(selling_price) && checkDigit(discount) && checkDigit(w_years) && checkDigit(w_months) && checkDigit(w_dates) && checkDigit(QTY) && checkString(pickup) && checkString(delivery_pond) && delivery_pond.trim().equals("Yes") ? checkDigit(delivery_days) : true && delivery_pond.trim().equals("Yes") ? checkString(delivery_area) : true) { System.out.println( "UPDATE VALIDATION OK---------------------------------------------------------------------"); try { String sql00 = "UPDATE product SET name=?, description=? WHERE idproduct=?"; PreparedStatement ps00 = Controller.DB.con().prepareStatement(sql00); ps00.setString(1, product_name); ps00.setString(2, description); ps00.setInt(3, Integer.parseInt(product_id)); System.out.println(ps00); int x = ps00.executeUpdate(); if (x == 1) { try { String sql01 = "UPDATE stock SET purchase_date=?, purchase_price=?, discount=?, selling_price=?, warranty=?, QTY=?, pickup=?, MFD=?, EXP=? WHERE product_idproduct=?"; PreparedStatement ps01 = Controller.DB.con().prepareStatement(sql01); ps01.setString(1, purchase_date); ps01.setInt(2, Integer.parseInt(purchase_price)); ps01.setInt(3, Integer.parseInt(discount)); ps01.setInt(4, Integer.parseInt(selling_price)); ps01.setString(5, w_years + "," + w_months + "," + w_dates); ps01.setInt(6, Integer.parseInt(QTY)); ps01.setString(7, pickup); ps01.setInt(6, Integer.parseInt(QTY)); ps01.setString(7, pickup); ps01.setString(8, MFD); ps01.setString(9, EXP); ps01.setInt(10, Integer.parseInt(product_id)); System.out.println(ps01); int x1 = ps01.executeUpdate(); if (x1 == 1) { try { String sql04 = "SELECT * FROM delivery WHERE product_idproduct=?"; PreparedStatement ps04 = Controller.DB.con().prepareStatement(sql04); ps04.setInt(1, Integer.parseInt(product_id)); System.out.println(ps04); ResultSet rs04 = ps04.executeQuery(); if (rs04.next()) { System.out.println("update karanna delivery id ata"); try { String sql02 = "UPDATE delivery SET pay_on_delivery=?, days=?, area=? WHERE product_idproduct=?"; PreparedStatement ps02 = Controller.DB.con() .prepareStatement(sql02); try { if (delivery_pond.equals("Yes")) { ps02.setString(1, delivery_pond); ps02.setInt(2, Integer.parseInt(delivery_days)); ps02.setString(3, Collecter01.delivery_areas.substring(1)); ps02.setInt(4, Integer.parseInt(product_id)); } else { ps02.setString(1, "No"); ps02.setInt(2, 0); ps02.setString(3, "No"); ps02.setInt(4, Integer.parseInt(product_id)); } System.out.println(ps02); ps02.executeUpdate(); } catch (Exception e) { } finally { try { for (String imn : images0.split(">")) { if (imn.trim().equals("")) { } else { String sql5 = "DELETE FROM image WHERE path LIKE ?;"; PreparedStatement ps5 = Controller.DB.con() .prepareStatement(sql5); ps5.setString(1, "%" + imn + "%"); System.out.println(ps5); ps5.executeUpdate(); } } for (String img_path : Collecter01.product_images) { String sql4 = "INSERT INTO image VALUES (?,?)"; PreparedStatement ps4 = Controller.DB.con() .prepareStatement(sql4); ps4.setInt(1, Integer.parseInt(product_id)); ps4.setString(2, img_path); System.out.println(ps4); ps4.executeUpdate(); } } catch (Exception e) { } finally { try { String sql5 = "SELECT idSpecifications FROM specifications WHERE name=?"; PreparedStatement ps5 = Controller.DB.con() .prepareStatement(sql5); for (Map.Entry<String, List> entry : Collecter01.specifications .entrySet()) { System.out.println(entry.getKey() + "---" + entry.getValue().get(0) + "---" + entry.getValue().get(1)); ps5.setString(1, entry.getKey()); System.out.println(ps5); ResultSet rs5 = ps5.executeQuery(); // int idSpecifications = 0; try { if (rs5.first()) { System.out.println( "Specifications name/id ata____1"); // idSpecifications = rs5.getInt(1); } else { try { System.out.println( "Specifications name/id na____2"); String sql6 = "INSERT INTO specifications VALUES (null,?)"; PreparedStatement ps6 = Controller.DB .con().prepareStatement(sql6); ps6.setString(1, entry.getKey()); System.out.println(ps6); ps6.executeUpdate(); System.out.println( "Specifications new add karanawa____2-1"); try { String sql7 = "SELECT idSpecifications FROM specifications WHERE name=?"; PreparedStatement ps7 = Controller.DB .con() .prepareStatement(sql7); ps7.setString(1, entry.getKey()); System.out.println(ps7); ResultSet rs7 = ps7.executeQuery(); if (rs7.first()) { System.out.println( "new Specifications name/id ata____3-1"); // idSpecifications = rs7.getInt(1); } else { } } catch (Exception e9) { System.out.println( "new Specifications name/id na____3-2"); } } catch (Exception e8) { System.out.println( "Specifications new add fail____2-2"); } } } catch (Exception e7) { } finally { try { String sql8 = "DELETE FROM product_has_specifications WHERE product_idproduct=?;"; PreparedStatement ps8 = Controller.DB.con() .prepareStatement(sql8); ps8.setInt(1, Integer.parseInt(product_id)); System.out.println(ps8); ps8.executeUpdate(); } catch (Exception e) { } } } try { for (Map.Entry<String, List> entry : Collecter01.specifications .entrySet()) { // System.out.println(product_id); // System.out.println(entry.getKey()); // System.out.println(entry.getValue().get(0)); // System.out.println(entry.getValue().get(1)); int idSpecifications = 0; try { String sql9 = "SELECT idSpecifications FROM specifications WHERE name=?"; PreparedStatement ps9 = Controller.DB.con() .prepareStatement(sql9); ps9.setString(1, entry.getKey()); // System.out.println(ps7); ResultSet rs9 = ps9.executeQuery(); if (rs9.first()) { // System.out.println("new Specifications name/id ata____3-1"); idSpecifications = rs9.getInt(1); } else { } } catch (Exception e) { } // System.out.println(product_id); // System.out.println(idSpecifications); // System.out.println(entry.getValue().get(0)); // System.out.println(entry.getValue().get(1)); try { String sql10 = "INSERT INTO product_has_specifications VALUES (?,?,?,?)"; PreparedStatement ps10 = Controller.DB.con() .prepareStatement(sql10); ps10.setInt(1, Integer.parseInt(product_id)); ps10.setInt(2, idSpecifications); ps10.setString(3, (String) entry.getValue().get(0)); ps10.setString(4, (String) entry.getValue().get(1)); System.out.println(ps10); ps10.executeUpdate(); System.out.println("spec value save kara"); } catch (Exception e) { System.out.println("spec value save fail"); } } } catch (Exception e) { } } catch (Exception e) { } finally { String xv = rurl + "msg=Product update successful&cl=00bf6f"; response.sendRedirect(xv); } } } } catch (Exception e) { e.printStackTrace(); } } else { System.out.println("update karanna delivery id eka na"); } } catch (Exception e) { } } else { System.out.println("stock update fail"); } } catch (Exception e) { } } else { System.out.println("product update fail"); } } catch (Exception e) { } } else { } } catch (Exception e) { } } }