List of usage examples for javax.servlet.http HttpServletRequest getPart
public Part getPart(String name) throws IOException, ServletException;
From source file:org.mhi.servlets.ImageUpload.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); // Service Class for DB - Actions ServiceQuery query = new ServiceQuery(); ServiceUpdate update = new ServiceUpdate(); String imgName = request.getParameter("name"); String imgDesc = request.getParameter("desc"); String imgCat = request.getParameter("category"); String fileSize = null;//from w ww . j av a 2 s . co m String fileName = null; String contentType = null; String[] parts = null; InputStream inputStream = null; // input stream of the upload file // obtains the upload file part in this multipart request Part filePart = request.getPart("files"); if (filePart != null) { // Fill up Information extract from File fileSize = "" + filePart.getSize(); parts = filePart.getSubmittedFileName().split("\\."); contentType = filePart.getContentType(); // obtains input stream of the upload file inputStream = filePart.getInputStream(); // new Image Images img = new Images(); // Set Parameters img.setFileName(imgName + "." + parts[1]); img.setName(imgName); img.setDescription(imgDesc); img.setFileBlob(IOUtils.toByteArray(inputStream)); img.setFileSize(fileSize); img.setcTyp(contentType); // Relationship to Category ImgCat cat = query.getCategoryByID(Long.valueOf(imgCat)); img.setCategory(cat); // Persist to Database update.insertImage(img); } response.sendRedirect(request.getServletContext().getContextPath() + "/admin/upload"); }
From source file:es.uma.inftel.blog.servlet.RegistroServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request servlet request//from w w w .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 */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String username = request.getParameter("username"); String password = request.getParameter("password"); RegistroViewFacade registroViewFacade = new RegistroViewFacade(postFacade); RequestDispatcher registroRequestDispatcher = request.getRequestDispatcher("registro.jsp"); if (username == null && password == null) { request.setAttribute("registroView", registroViewFacade.createView(false)); registroRequestDispatcher.forward(request, response); return; } String email = request.getParameter("email"); Part filePart = request.getPart("avatar"); InputStream inputStream = filePart.getInputStream(); byte[] avatar = IOUtils.toByteArray(inputStream); Usuario usuario = registrarUsuario(username, password, email, avatar); if (usuario == null) { request.setAttribute("registroView", registroViewFacade.createView(true)); registroRequestDispatcher.forward(request, response); } else { HttpSession session = request.getSession(); session.setAttribute("usuario", usuario); response.sendRedirect("index"); } }
From source file:Controllers.MurController.java
@RequestMapping(value = "{path}/ajoutStatut", method = RequestMethod.POST) public ModelAndView ajoutStatut(HttpServletRequest request, HttpServletResponse response, @PathVariable String path) throws Exception { ModelAndView mv;//from w w w . j a v a 2 s . c o m // Rcupration de la session HttpSession session = request.getSession(false); // Accs sans tre connect if (session == null || session.getAttribute("idUtilisateur") == null) { mv = new ModelAndView("connexion"); mv.addObject("inscriptionMessage", "Veuillez vous connecter pour accder cette page"); return mv; } Part p = request.getPart("file"); // Rcupration de l'id de l'utilisateur courant int idUtilisateur = (int) session.getAttribute("idUtilisateur"); int idPersonne = Integer.parseInt(request.getParameter("idPersonne")); // Rcupration du texte du statut post String statut = request.getParameter("statut"); // Ajout du statut int idStatut = 0; if (idPersonne == idUtilisateur) { idStatut = murService.ajoutStatut(idUtilisateur, statut); } else { idStatut = murService.posterStatut(idUtilisateur, idPersonne, statut); } if (p.getSize() != 0 && idStatut != 0) { fichierService.ajoutFichier(p, idStatut); } mv = getRedirect(path, idPersonne, idStatut); return mv; }
From source file:Package.Projectoverviewservlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { frame.setAlwaysOnTop(true);//w w w. j a va2 s . co m if (request.getParameter("submit") != null) { Database database = null; try { database = new Database(); database.Connect(); } catch (SQLException | ClassNotFoundException ex) { Logger.getLogger(Projectoverviewservlet.class.getName()).log(Level.SEVERE, null, ex); } try { String contentType = request.getContentType(); if ((contentType.indexOf("multipart/form-data") >= 0)) { try { Part filePart = request.getPart("fileupload"); Image image = ImageIO.read(filePart.getInputStream()); String INSERT_PICTURE = "INSERT INTO \"PICTURE\"(\"PICTUREID\", \"PROJECTID\", \"HEIGHT\", \"WIDTH\", \"COLORTYPE\", \"PICTURE\") VALUES (PictureSequence.nextval, 1," + image.getHeight(null) + "," + image.getWidth(null) + ", 'Color', ?)"; InputStream is = null; PreparedStatement ps = null; try { is = filePart.getInputStream(); ps = database.myConn.prepareStatement(INSERT_PICTURE); ps.setBlob(1, is); ps.executeUpdate(); database.myConn.commit(); JOptionPane.showMessageDialog(frame, "De afbeelding is succesvol geupload."); } finally { try { ps.close(); is.close(); } catch (Exception exception) { } } } catch (IOException | ServletException | SQLException ex) { System.out.println(ex); } } else { JOptionPane.showMessageDialog(frame, "Er is iets fout gegaan probeer het opnieuw"); } } catch (Exception ex) { JOptionPane.showMessageDialog(frame, ex.getMessage()); } response.sendRedirect("projectoverview.jsp"); } if (request.getParameter("deleteproject") != null) { String[] selectresults = request.getParameterValues("selectproject"); po.deleteProject(Integer.parseInt(selectresults[0])); } if (request.getParameter("openproject") != null) { try { String[] selectresults = request.getParameterValues("selectproject"); Project project = po.getProject(Integer.parseInt(selectresults[0])); request.setAttribute("project", project); request.getRequestDispatcher("projectoverview.jsp").forward(request, response); } catch (Exception ex) { JOptionPane.showMessageDialog(frame, ex.getMessage()); } } if (request.getParameter("Save") != null) { Project project = (Project) request.getAttribute("project"); if (project != null) { try { System.out.println(request.getParameter("startdate")); po.updateProject(project.getProjectID(), request.getParameter("name"), request.getParameter("client"), new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("startdate")), new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("enddate"))); } catch (Exception ex) { } } else { String username = ""; for (Cookie cookie : request.getCookies()) { if (cookie.getName().equals("Email")) { username = cookie.getValue(); } } if (!username.isEmpty()) { try { po.createProject(po.connection.getCompanyID(username), request.getParameter("name"), request.getParameter("client"), new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("startdate")), new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("enddate"))); } catch (ParseException ex) { Logger.getLogger(Projectoverviewservlet.class.getName()).log(Level.SEVERE, null, ex); } } //roep create aan } request.getRequestDispatcher("projectoverview.jsp").forward(request, response); } if (request.getParameter("deleteimage") != null) { } if (request.getParameter("importimage") != null) { } if (request.getParameter("koppel") != null) { } if (request.getParameter("addemail") != null) { } if (request.getParameter("deleteemail") != null) { } if (request.getParameter("importemail") != null) { } }
From source file:org.ohmage.request.Request.java
/** * <p>/*from w ww. j a v a 2s. c o m*/ * Retrieves a parameter from either parts or the servlet container's * deserialization. * </p> * * <p> * This supersedes {@link #getMultipartValue(HttpServletRequest, String)}. * </p> * * @param httpRequest * The HTTP request. * * @param key * The parameter key. * * @return The parameter if given otherwise null. * * @throws ValidationException * There was a problem reading from the request. */ protected byte[] getParameter(final HttpServletRequest httpRequest, final String key) throws ValidationException { // First, attempt to decode it as a multipart/form-data post. try { // Get the part. If it isn't a multipart/form-data post, an // exception will be thrown. If it is and such a part does not // exist, return null. Part part = httpRequest.getPart(key); if (part == null) { return null; } // If the part exists, attempt to retrieve it. InputStream partInputStream = part.getInputStream(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] chunk = new byte[4096]; int amountRead; while ((amountRead = partInputStream.read(chunk)) != -1) { outputStream.write(chunk, 0, amountRead); } // If the buffer is empty, return null. Otherwise, return the byte // array. if (outputStream.size() == 0) { return null; } else { return outputStream.toByteArray(); } } // This will be thrown if it isn't a multipart/form-post, at which // point we can attempt to use the servlet container's deserialization // of the parameters. catch (ServletException e) { // Get the parameter. String result = httpRequest.getParameter(key); // If it doesn't exist, return null. if (result == null) { return null; } // Otherwise, return its bytes. else { return result.getBytes(); } } // If we could not read a parameter, something more severe happened, // and we need to fail the request and throw an exception. catch (IOException e) { LOGGER.info("There was an error reading the message from the input " + "stream.", e); setFailed(); throw new ValidationException(e); } }
From source file:mx.edu.ittepic.AEEcommerce.servlets.NewUsers.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/* w ww. j av a 2 s .com*/ * @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 { response.setContentType("application/json;charset=UTF-8"); response.setHeader("Cache-Control", "no-store"); PrintWriter out = response.getWriter(); String username = request.getParameter("username"); String password = request.getParameter("password"); String email = request.getParameter("email"); String country = request.getParameter("country"); String state = request.getParameter("state"); String city = request.getParameter("city"); String region = request.getParameter("region"); String neigborhood = request.getParameter("neigborhood"); String street = request.getParameter("street"); String streetnumber = request.getParameter("streetnumber"); String zipcode = request.getParameter("zipcode"); Part file = request.getPart("img"); String phone = request.getParameter("phone"); String cellphone = request.getParameter("cellphone"); String gender = request.getParameter("gender"); String roleid = request.getParameter("roleid"); String companyid = request.getParameter("companyid"); password = DigestUtils.md5Hex(password); out.print(ejb.newUser(username, password, phone, neigborhood, zipcode, city, country, state, region, street, email, streetnumber, file, cellphone, companyid, roleid, gender)); }
From source file:org.cirdles.webServices.calamari.CalamariServlet.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request// ww w . j a v a2 s.com * @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 { HttpSession session = request.getSession(); Integer accessCount; synchronized (session) { accessCount = (Integer) session.getAttribute("accessCount"); if (accessCount == null) { accessCount = 0; // autobox int to Integer } else { accessCount = accessCount + 1; } session.setAttribute("accessCount", accessCount); } response.setContentType("application/zip"); response.setHeader("Content-Disposition", "attachment; filename=calamari-reports.zip"); boolean useSBM = ServletRequestUtils.getBooleanParameter(request, "useSBM", true); boolean useLinFits = ServletRequestUtils.getBooleanParameter(request, "userLinFits", false); String firstLetterRM = ServletRequestUtils.getStringParameter(request, "firstLetterRM", "T"); Part filePart = request.getPart("prawnFile"); String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); InputStream fileStream = filePart.getInputStream(); File myFile = new File(fileName); PrawnFileHandlerService handler = new PrawnFileHandlerService(); String fileExt = FilenameUtils.getExtension(fileName); try { File report = null; if (fileExt.equals("zip")) { report = handler.generateReportsZip(fileName, fileStream, useSBM, useLinFits, firstLetterRM) .toFile(); } else if (fileExt.equals("xml")) { report = handler.generateReports(fileName, fileStream, useSBM, useLinFits, firstLetterRM).toFile(); } response.setContentLengthLong(report.length()); IOUtils.copy(new FileInputStream(report), response.getOutputStream()); } catch (Exception e) { System.err.println(e); } }
From source file:uk.ac.ncl.ssip.webserver.StartDBServlet.java
private void dataHandling(HttpServletRequest request) throws ServletException, IOException { //configure embedded database String fileRoot = new File(".").getCanonicalPath(); File dbroot = new File(fileRoot + "/neo4j-databases/"); if (!dbroot.exists()) { if (!dbroot.mkdir()) { System.out.println("Unable to create neo4j directory"); }//from ww w .ja v a2s. c om } int dbversion = 1; for (int i = 0; i < dbroot.list().length; i++) { dbversion++; } Neo4J backend = new Neo4J(fileRoot + "/neo4j-databases/BioSSIPv0.1." + dbversion, fileRoot + "/target/webapp/results/performance"); backend.initialiseDatabaseConnection(); backend.createIndex(); //parse each file uploaded using parsers specified for (int i = 0; i < fileNum; i++) { String fileName = getFileName(request.getPart("file" + i)); if (fileName.equals("")) { String[] urlSplit = request.getParameter("url" + i).split("/"); fileName = urlSplit[urlSplit.length - 1]; } String inputParser = request.getParameter("parser" + i); ParserInterface parserObj = null; try { parserObj = (ParserInterface) Class.forName("uk.ac.ncl.ssip.parsers." + inputParser).newInstance(); } catch (Exception ex) { ex.printStackTrace(); } parserObj.setFilepath(fileRoot + "/target/webapp/uploads/" + fileName); parserObj.setHandler(backend); System.out.println("Parser initialised: " + inputParser); parserObj.parseFile(); System.out.println("Parser complete: " + inputParser); } backend.finaliseDatabaseConnection(); }
From source file:servlets.post.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//w w w . j a va2s . 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(); JsonObject resp = new JsonObject(); try { String tipo = request.getParameter("tipo") == null ? "" : request.getParameter("tipo"); String titulo = request.getParameter("titulo") == null ? "" : request.getParameter("titulo"); String descripcion = request.getParameter("descripcion") == null ? "" : request.getParameter("descripcion"); int categoria = request.getParameter("categoria") == null ? -1 : Integer.parseInt(request.getParameter("categoria")); //Si los campos estan vacios: error de validacion if (tipo.equals("") || titulo.equals("") || descripcion.equals("") || categoria == -1) { throw new Exception("W::No puedes dejar campos vacios. Intentalo nuevamente"); } Part imagen = request.getPart("contenido"); Part audio = request.getPart("audio"); String cabeceraI = ""; String cabeceraA = ""; boolean siimagen = false; if (imagen != null && !imagen.getContentType().equals("application/octet-stream")) { cabeceraI = request.getParameter("cabeceraI") == null ? "" : request.getParameter("cabeceraI"); if (cabeceraI.equals("")) throw new Exception("W::tu imagen no tiene cabecera. Agregale una antes de enviar los datos"); else siimagen = true; } boolean siaudio = false; if (audio != null && !audio.getContentType().equals("application/octet-stream")) { cabeceraA = request.getParameter("cabeceraA") == null ? "" : request.getParameter("cabeceraA"); if (cabeceraA.equals("")) throw new Exception("W::tu archivo no tiene cabecera. Agregale uno antes de enviar los datos"); else siaudio = true; } HttpSession ss = request.getSession(); int db = ss.getAttribute("bd") == null ? -1 : Integer.parseInt(ss.getAttribute("bd").toString()); int id = ss.getAttribute("id") == null ? -1 : Integer.parseInt(ss.getAttribute("id").toString()); if (db == -1 || id == -1) throw new Exception("Problemas con la base de datos. Por favor, intentalo mas tarde"); ldn.cPost post = new ldn.cPost(db); String msg = post.nuevoPost(id, categoria, titulo, descripcion); if (post.getIdP() == -1) throw new Exception(msg); //msg se manda como error si idP = -1 String result = ""; if (siimagen) { String extension = FilenameUtils.getExtension(imagen.getSubmittedFileName()); result = Clases.Utilities.saveFile(imagen, "imagenPost", "imagen", "." + extension); if (result.startsWith("/")) result = post.registraContenidoP(Integer.toString(post.getIdP()), result, cabeceraI); else throw new Exception(result); msg += "\n" + result; } if (siaudio) { String extension = FilenameUtils.getExtension(audio.getSubmittedFileName()); System.out.println(extension); result = Clases.Utilities.saveFile(audio, "audioPost", "audio", "." + extension); if (result.startsWith("/")) result = post.registraContenidoP(Integer.toString(post.getIdP()), result, cabeceraA); else throw new Exception(result); msg += "\n" + result; } resp.addProperty("status", "OK"); resp.addProperty("msg", msg); } catch (Exception e) { if (e.getMessage().startsWith("W::")) { resp.addProperty("status", "WARNING"); resp.addProperty("msg", e.getMessage().substring(3)); } else { resp.addProperty("status", "ERROR"); resp.addProperty("msg", e.getMessage()); } } out.print(resp.toString()); }
From source file:com.esri.gpt.control.rest.ManageDocumentServlet.java
private void createAndUpload(HttpServletRequest request, HttpServletResponse response, RequestContext context, Publisher publisher) throws IOException, IllegalStateException, ServletException, SchemaException, CatalogIndexException, ImsServiceException, SQLException, NotAuthorizedException, IdentityException { //XML/*from ww w .ja va2 s . c o m*/ InputStream xmlStream = request.getPart("xml").getInputStream(); String xml = IOUtils.toString(xmlStream, "UTF-8"); xml = Val.chkStr(Val.removeBOM(xml)); //read file OutputStream out = null; InputStream filecontent = request.getPart("file").getInputStream(); //ID InputStream idStream = request.getPart("id").getInputStream(); String id = IOUtils.toString(idStream, "UTF-8"); /**Collection<Part> x = request.getParts(); Part[] array = x.toArray (new Part[x.size ()]); for(int f=0; f<array.length;f++){ System.out.println(array[f].getName() + " " + array[f].getSize()); }*/ //verify - throw servlet exception ValidationRequest vRequest = new ValidationRequest(context, "id", xml); // in case of schema problems verify method would throw exception try { vRequest.verify(); } catch (ValidationException e) { System.out.println("valid error: " + e); throw new ServletException("409: Document failed to validate."); } //Save Zip file String webDataPath = Constant.UPLOAD_FOLDER, folder = id; new File(webDataPath + File.separator + folder).mkdir(); try { //initiate output stream out = new FileOutputStream(new File( webDataPath + File.separator + folder + File.separator + Constant.XML_OUTPUT_ZIP_NAME)); int read = 0; final byte[] bytes = new byte[1024]; while ((read = filecontent.read(bytes)) != -1) { out.write(bytes, 0, read); } } finally { //close all open streams if necessary if (out != null) { out.close(); } if (filecontent != null) { filecontent.close(); } } //save xml in mcp saveXml2Package(xml, id); //save xml in db if (xml.length() > 0) { //PublicationRequest pubRequest = new PublicationRequest(context,publisher,xml); //PublicationRecord pubRecord = pubRequest.getPublicationRecord(); //pubRecord.setPublicationMethod("editor"); //pubRequest.publish(); MovingCodePackage mvp = new MovingCodePackage(new File( webDataPath + File.separator + folder + File.separator + Constant.XML_OUTPUT_ZIP_NAME)); McpPublish mcpP = new McpPublish(mvp, webDataPath + File.separator + folder + File.separator + Constant.XML_OUTPUT_ZIP_NAME, id, context); if (mcpP.publish(false)) System.out.println("publishing successfully"); } response.setStatus(HttpServletResponse.SC_CREATED); }