List of usage examples for javax.servlet.http HttpServletRequest getPart
public Part getPart(String name) throws IOException, ServletException;
From source file:codes.thischwa.c5c.DispatcherPUT.java
@Override GenericResponse doRequest() {/* ww w . j a va 2 s . c o m*/ logger.debug("Entering DispatcherPUT#doRequest"); InputStream in = null; try { Context ctx = RequestData.getContext(); FilemanagerAction mode = ctx.getMode(); HttpServletRequest req = ctx.getServletRequest(); FilemanagerConfig conf = UserObjectProxy.getFilemanagerUserConfig(req); switch (mode) { case UPLOAD: { boolean overwrite = conf.getUpload().isOverwrite(); String currentPath = IOUtils.toString(req.getPart("currentpath").getInputStream()); String backendPath = buildBackendPath(currentPath); Part uploadPart = req.getPart("newfile"); String newName = getFileName(uploadPart); // Some browsers transfer the entire source path not just the filename String fileName = FilenameUtils.getName(newName); // TODO check forceSingleExtension String sanitizedName = FileUtils.sanitizeName(fileName); if (!overwrite) sanitizedName = getUniqueName(backendPath, sanitizedName); logger.debug("* upload -> currentpath: {}, filename: {}, sanitized filename: {}", currentPath, fileName, sanitizedName); // check 'overwrite' and unambiguity String uniqueName = getUniqueName(backendPath, sanitizedName); if (!overwrite && !uniqueName.equals(sanitizedName)) { throw new FilemanagerException(FilemanagerAction.UPLOAD, FilemanagerException.Key.FileAlreadyExists, sanitizedName); } sanitizedName = uniqueName; in = uploadPart.getInputStream(); // save the file temporary Path tempPath = saveTemp(in, sanitizedName); // pre-process the upload imageProcessingAndSizeCheck(tempPath, sanitizedName, uploadPart.getSize(), conf); connector.upload(backendPath, sanitizedName, new BufferedInputStream(Files.newInputStream(tempPath))); logger.debug("successful uploaded {} bytes", uploadPart.getSize()); Files.delete(tempPath); UploadFile ufResp = new UploadFile(currentPath, sanitizedName); ufResp.setName(newName); ufResp.setPath(currentPath); return ufResp; } case REPLACE: { String newFilePath = IOUtils.toString(req.getPart("newfilepath").getInputStream()); String backendPath = buildBackendPath(newFilePath); Part uploadPart = req.getPart("fileR"); logger.debug("* replacefile -> urlPath: {}, backendPath: {}", newFilePath, backendPath); // check if backendPath is protected boolean protect = connector.isProtected(backendPath); if (protect) { throw new FilemanagerException(FilemanagerAction.UPLOAD, FilemanagerException.Key.NotAllowedSystem, backendPath); } // check if file already exits VirtualFile vf = new VirtualFile(backendPath, false); String fileName = vf.getName(); String uniqueName = getUniqueName(vf.getFolder(), fileName); if (uniqueName.equals(fileName)) { throw new FilemanagerException(FilemanagerAction.UPLOAD, FilemanagerException.Key.FileNotExists, backendPath); } in = uploadPart.getInputStream(); // save the file temporary Path tempPath = saveTemp(in, fileName); // pre-process the upload imageProcessingAndSizeCheck(tempPath, fileName, uploadPart.getSize(), conf); connector.replace(backendPath, new BufferedInputStream(Files.newInputStream(tempPath))); logger.debug("successful replaced {} bytes", uploadPart.getSize()); VirtualFile vfUrlPath = new VirtualFile(newFilePath, false); return new Replace(vfUrlPath.getFolder(), vfUrlPath.getName()); } case SAVEFILE: { String urlPath = req.getParameter("path"); String backendPath = buildBackendPath(urlPath); logger.debug("* savefile -> urlPath: {}, backendPath: {}", urlPath, backendPath); String content = req.getParameter("content"); connector.saveFile(backendPath, content); return new SaveFile(urlPath); } default: { logger.error("Unknown 'mode' for POST: {}", req.getParameter("mode")); throw new C5CException(UserObjectProxy.getFilemanagerErrorMessage(Key.ModeError)); } } } catch (C5CException e) { return ErrorResponseFactory.buildErrorResponseForUpload(e.getMessage()); } catch (ServletException e) { logger.error("A ServletException was thrown while uploading: " + e.getMessage(), e); return ErrorResponseFactory.buildErrorResponseForUpload(e.getMessage(), 200); } catch (IOException e) { logger.error("A IOException was thrown while uploading: " + e.getMessage(), e); return ErrorResponseFactory.buildErrorResponseForUpload(e.getMessage(), 200); } finally { IOUtils.closeQuietly(in); } }
From source file:vista.RegistroVideojuegoServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w. ja v a 2s . com * * @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"); Videojuego videojuego = new Videojuego(); videojuego.setNombre(request.getParameter("nombre")); videojuego.setCosto(Double.parseDouble(request.getParameter("costo"))); videojuego.setDescripcion(request.getParameter("descripcion")); byte[] imagen; imagen = convierteArchivo(request.getPart("imagena"), 0); videojuego.setImagena(imagen); imagen = convierteArchivo(request.getPart("imagenb"), 0); videojuego.setImagenb(imagen); imagen = convierteArchivo(request.getPart("imagenc"), 0); videojuego.setImagenc(imagen); imagen = convierteArchivo(request.getPart("video"), 1); videojuego.setVideo(imagen); imagen = convierteArchivo(request.getPart("archivo"), 2); videojuego.setArchivo(imagen); videojuego.setLinkdescarga("down_" + videojuego.getNombre().replace(" ", "_")); RegistroVideojuegoController controller = new RegistroVideojuegoController(utx, emf); String mensaje = controller.registrar(videojuego); HttpSession session = request.getSession(); Desarrollador desarrollador = (Desarrollador) session.getAttribute("desarrollador"); if (desarrollador == null) { response.sendRedirect("loginDesarrollador.jsp"); } else if (mensaje.equals("")) { response.sendRedirect("Galeria"); } else { session.setAttribute("mensaje", mensaje); response.sendRedirect("subirVideojuego.jsp"); } }
From source file:controller.servlet.ImportAmenities.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request//from w w w . j a v a2 s . c om * @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 { // Obtencin de la regin String regionName = request.getParameter("regionname"); boolean isXML = false; // Procesado del fichero para subirlo al servidor. for (Part part : request.getParts()) { if (part.getName().equals("file")) { try (InputStream is = request.getPart(part.getName()).getInputStream()) { int i = is.available(); byte[] b = new byte[i]; if (b.length == 0) { break; } is.read(b); String fileName = obtenerNombreFichero(part); String extension = FilenameUtils.getExtension(fileName); String path = this.getServletContext().getRealPath(""); String ruta = path + File.separator + Path.POIS_FOLDER + File.separator + fileName; File directory = new File(path + File.separator + Path.POIS_FOLDER); fileName = FilenameUtils.getBaseName(fileName); if (!directory.exists()) { directory.mkdirs(); } try (FileOutputStream os = new FileOutputStream(ruta)) { os.write(b); } // Comprobacin de que sea un fichero xml. if (extension.equals("xml")) { isXML = true; } else { break; } if (isXML) { // Crear entrada en la tabla de ficheros de PDIs. UploadedPoiFileDaoImpl uPFDao = new UploadedPoiFileDaoImpl(); UploadedFile uFile = new UploadedFile(); uFile.setName(fileName); uFile.setProcessedDate(new java.sql.Date(new java.util.Date().getTime())); uPFDao.createFile(uFile); // Almacenado de los datos en la Base de Datos. NotifyingThread nT = new AmenityProcessing(ruta, regionName); nT.addListener(this); nT.setName(ThreadName.AMENITIES_THREAD_NAME); nT.start(); } } } } HttpSession session = request.getSession(true); session.setAttribute("isXML", isXML); if (!isXML) { session.setAttribute("error", true); String page = "/pages/amenitiesmanage.jsp"; RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher(page); requestDispatcher.forward(request, response); } else { session.setAttribute("error", false); processRequest(request, response); } }
From source file:org.ohmage.request.Request.java
/** * Reads the HttpServletRequest for a key-value pair and returns the value * where the key is equal to the given key. * //w w w. j a v a 2 s . c o m * @param httpRequest A "multipart/form-data" request that contains the * parameter that has a key value 'key'. * * @param key The key for the value we are after in the 'httpRequest'. * * @return Returns null if there is no such key in the request or if, * after reading the object, it has a length of 0. Otherwise, it * returns the value associated with the key as a byte array. * * @throws ServletException Thrown if the 'httpRequest' is not a * "multipart/form-data" request. * * @throws IOException Thrown if there is an error reading the value from * the request's input stream. * * @throws IllegalStateException Thrown if the entire request is larger * than the maximum allowed size for a * request or if the value of the requested * key is larger than the maximum allowed * size for a single value. */ protected byte[] getMultipartValue(HttpServletRequest httpRequest, String key) throws ValidationException { try { Part part = httpRequest.getPart(key); if (part == null) { return null; } // Get the input stream. InputStream partInputStream = part.getInputStream(); // Wrap the input stream in a GZIP de-compressor if it is GZIP'd. String contentType = part.getContentType(); if ((contentType != null) && contentType.contains("gzip")) { LOGGER.info("Part was GZIP'd: " + key); partInputStream = new GZIPInputStream(partInputStream); } // Parse the data. ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] chunk = new byte[4096]; int amountRead; while ((amountRead = partInputStream.read(chunk)) != -1) { outputStream.write(chunk, 0, amountRead); } if (outputStream.size() == 0) { return null; } else { return outputStream.toByteArray(); } } catch (ServletException e) { LOGGER.error("This is not a multipart/form-data POST.", e); setFailed(ErrorCode.SYSTEM_GENERAL_ERROR, "This is not a multipart/form-data POST which is what we expect for the current API call."); throw new ValidationException(e); } catch (IOException e) { LOGGER.info("There was a problem with the zipping of the data.", e); throw new ValidationException(ErrorCode.SERVER_INVALID_GZIP_DATA, "The zipped data was not valid zip data.", e); } }
From source file:controller.servlet.Upload.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request//from www . j a v 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 { // Subida de los ficheros al sistema. UploadedFile uF; UploadedFileDaoImpl uFD = new UploadedFileDaoImpl(); int numberOfCsvFiles = 0; int numberOfNotCsvFiles = 0; for (Part part : request.getParts()) { if (part.getName().equals("file")) { try (InputStream is = request.getPart(part.getName()).getInputStream()) { int i = is.available(); byte[] b = new byte[i]; if (b.length == 0) { break; } is.read(b); String fileName = obtenerNombreFichero(part); String extension = FilenameUtils.getExtension(fileName); String path = this.getServletContext().getRealPath(""); String ruta = path + File.separator + Path.UPLOADEDFILES_FOLDER + File.separator + fileName; File directorio = new File(path + File.separator + Path.UPLOADEDFILES_FOLDER); if (!directorio.exists()) { directorio.mkdirs(); } // Se sube el fichero en caso de ser zip o csv. if (extension.equals(Path.CSV_EXTENSION) || extension.equals(Path.ZIP_EXTENSION)) { try (FileOutputStream os = new FileOutputStream(ruta)) { os.write(b); } if (extension.equals(Path.CSV_EXTENSION)) { numberOfCsvFiles++; } } else { numberOfNotCsvFiles++; } // Extraccin de los ficheros incluidos en el zip. if (extension.equals(Path.ZIP_EXTENSION)) { ZipInputStream zis = new ZipInputStream( new FileInputStream(directorio + File.separator + fileName)); ZipEntry eachFile; while (null != (eachFile = zis.getNextEntry())) { File newFile = new File(directorio + File.separator + eachFile.getName()); // Se guardan los csv. if (FilenameUtils.getExtension(directorio + File.separator + eachFile.getName()) .equals(Path.CSV_EXTENSION)) { numberOfCsvFiles++; try (FileOutputStream fos = new FileOutputStream(newFile)) { int len; byte[] buffer = new byte[1024]; while ((len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); } } zis.closeEntry(); // Insertar en BD uF = new UploadedFile(0, eachFile.getName(), new java.sql.Date(new Date().getTime()), false, null); uFD.createFile(uF); } else { numberOfNotCsvFiles++; } } File fileToDelete = new File( path + File.separator + Path.UPLOADEDFILES_FOLDER + File.separator + fileName); fileToDelete.delete(); } else { // Insertar en BD uF = new UploadedFile(0, fileName, new java.sql.Date(new Date().getTime()), false, null); uFD.createFile(uF); } } } } // Asignacin de valores. HttpSession session = request.getSession(true); session.setAttribute("numberOfCsvFiles", numberOfCsvFiles); session.setAttribute("numberOfNotCsvFiles", numberOfNotCsvFiles); if (numberOfCsvFiles == 0 && numberOfNotCsvFiles == 0) { session.setAttribute("error", true); } else { session.setAttribute("error", false); } processRequest(request, response); }
From source file:saludtec.admincloud.web.servicios.ArchivosWeb.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ String servicio = request.getPathInfo(); String metodo = request.getMethod(); String idPaciente = contenidoFormData(request.getPart("paciente").getInputStream()); String contentType = request.getPart("file").getContentType(); String ext = ""; String ruta = "/var/www/AdminCloud/clinicas/" + sesion.clinica(request.getSession()).getIdClinica() + "/pacientes/" + idPaciente; switch (metodo) { case "POST": switch (servicio) { case "guardarPerfil": ruta += "perfil/"; guardarFotoPerfil(request).writeJSONString(out); break; case "guardarGaleria": ruta += "galeria/"; guardarArchivo(request, idPaciente, ext, ruta).writeJSONString(out); break; case "guardarGalerias": ruta += "galeria/"; guardarArchivos(request, idPaciente, ext, ruta).writeJSONString(out); break; case "guardarAnexo": ruta += "anexos/"; guardarArchivo(request, idPaciente, ext, ruta).writeJSONString(out); break; case "guardarAnexos": ruta += "anexos/"; guardarArchivos(request, idPaciente, ext, ruta).writeJSONString(out); break; }//from w ww . java2 s.c o m break; case "GET": response.sendRedirect("http://localhost/AdminCloudData" + request.getPathInfo()); break; default: response.sendError(501, "Metodo " + metodo + " no soportado"); break; } } }
From source file:marketDB.add_db.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String path = "C:\\Users\\Asus X550ZE\\Documents\\NetBeansProjects\\Web App\\web\\img"; Cookie[] cookies = request.getCookies(); String access_token = ""; for (int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equals("access_token")) { access_token = cookies[i].getValue(); }/*from www. j ava2 s .c om*/ } String product_name = request.getParameter("prod_name"); String desc = request.getParameter("desc_box"); String price = request.getParameter("price_box"); Part filePart = request.getPart("imgcatch"); String fileName = getFileName(filePart); InputStream in = filePart.getInputStream(); byte[] imgByte = readFully(in); int status = 0; try { status = addProduct(access_token, product_name, desc, price, fileName, imgByte); } catch (ProtocolException_Exception ex) { Logger.getLogger(add_db.class.getName()).log(Level.SEVERE, null, ex); } catch (ParseException_Exception ex) { Logger.getLogger(add_db.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException_Exception ex) { Logger.getLogger(add_db.class.getName()).log(Level.SEVERE, null, ex); } if (status == 1) { //WEB SERVICE ADD PRODUCT JSONObject arrayObj = new JSONObject(); //arrayObj.put("status",status); //response.setContentType("application/json:charset=UTF-8"); //response.getWriter().write(arrayObj.toString()); response.sendRedirect("your_product.jsp"); } else { response.sendRedirect("login.jsp"); } }
From source file:es.uma.inftel.blog.servlet.PerfilServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w .j av a2 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 { request.setCharacterEncoding("UTF-8"); BaseView baseView = new BaseView(); BaseViewFacade<BaseView> baseViewFacade = new BaseViewFacade<>(postFacade); baseViewFacade.initView(baseView); RequestDispatcher requestDispatcher = request.getRequestDispatcher("perfil.jsp"); String password = request.getParameter("password"); if (password == null) { request.setAttribute("perfilView", baseView); requestDispatcher.forward(request, response); } String email = request.getParameter("email"); Part filePart = request.getPart("avatar"); byte[] avatar = null; if (!filePart.getSubmittedFileName().isEmpty()) { InputStream inputStream = filePart.getInputStream(); avatar = IOUtils.toByteArray(inputStream); } HttpSession session = request.getSession(); Usuario usuario = (Usuario) session.getAttribute("usuario"); modificarUsuario(usuario, password, email, avatar); response.sendRedirect("perfil"); }
From source file:marketDB.update_db.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String path = "C:\\Users\\Asus X550ZE\\Documents\\NetBeansProjects\\Web App\\web\\img"; Cookie[] cookies = request.getCookies(); String access_token = ""; for (int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equals("access_token")) { access_token = cookies[i].getValue(); }/*from w w w. j a v a 2s .c o m*/ } String product_id = request.getParameter("product_id"); String product_name = request.getParameter("prod_name"); String desc = request.getParameter("desc_box"); String price = request.getParameter("price_box"); Part filePart = request.getPart("imgcatch"); String fileName = getFileName(filePart); InputStream in = filePart.getInputStream(); byte[] imgByte = readFully(in); int status = 0; try { status = editProduct(access_token, product_id, product_name, desc, price, fileName, imgByte); //WEB SERVICE UPDATE PRODUCT } catch (IOException_Exception ex) { Logger.getLogger(update_db.class.getName()).log(Level.SEVERE, null, ex); } catch (ProtocolException_Exception ex) { Logger.getLogger(update_db.class.getName()).log(Level.SEVERE, null, ex); } catch (ParseException_Exception ex) { Logger.getLogger(update_db.class.getName()).log(Level.SEVERE, null, ex); } JSONObject arrayObj = new JSONObject(); arrayObj.put("status", status); if (status == 1) { response.sendRedirect("your_product.jsp"); } else { response.sendRedirect("login.jsp"); } }
From source file:com.shoylpik.controller.AddProduct.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String SAVE_DIRECTORY = "menu_assets/ProductImage"; String absolutePath = request.getServletContext().getRealPath(""); String savePath = absolutePath + File.separator + SAVE_DIRECTORY; File imageSaveDirectory = new File(savePath); if (!imageSaveDirectory.exists()) { imageSaveDirectory.mkdir();//from www . j av a 2 s. c om } System.out.println("absolutePath: " + absolutePath); System.out.println("SavePath: " + savePath); // System.out.println("imageSaveDirectory.getAbsolutePath(): " + imageSaveDirectory.getAbsolutePath()); String fileName = null; try { Part filePart = request.getPart("IPimage"); String filename = getFilename(filePart); // System.out.println("filename: " + filename); InputStream imageInputStream = filePart.getInputStream(); byte[] bytes = IOUtils.toByteArray(imageInputStream); Product product = new Product(); product.setProductId(Integer.parseInt(request.getParameter("IPID"))); product.setProductName(request.getParameter("IPname")); product.setProductImageName(filename); product.setProductCategory(request.getParameter("IPcat")); product.setProductPrice(Float.parseFloat(request.getParameter("IPprice"))); product.setProductQuantity(Integer.parseInt(request.getParameter("IPQuant"))); ProductBean pBean = new ProductBean(); pBean.addProduct(product); // String fullImagePath = "menu_assets/images/"+filename; String fullImagePath = savePath + File.separator + filename; File file = new File(fullImagePath); // System.out.println("fullImagePath : " + fullImagePath); FileOutputStream fos = new FileOutputStream(file); fos.write(bytes); } catch (SQLException ex) { Logger.getLogger(AddProduct.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException | ServletException | NumberFormatException ex) { Logger.getLogger(AddProduct.class.getName()).log(Level.SEVERE, null, ex); } response.sendRedirect("AdministrationPage.jsp"); }