/** * Permet de repondre a une requete web En affichant la liste des Spectacles et representations : * Utiliste JQuery javascript pour la mise en forme * * @param HttpServletRequest request requete * @param HttpServletResponse response reponse * @throw IOException, ServletException * @return void */ public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // Get the session object HttpSession session = req.getSession(true); // Get the output stream ServletOutputStream out = res.getOutputStream(); res.setContentType("text/html"); out.println("<HEAD><TITLE>Reservation de tickets </TITLE></HEAD><BODY>"); out.println("<h1> Reservations de tickets </h1>"); out.println("<BODY bgproperties=\"fixed\" background=\"/images/rideau.JPG\">"); out.println("<p align=\"Right\"><font face=\"Monotype Corsiva\"style=\"font-size: 16pt\">"); try { // Open the file that is the first // command line parameter String relativeWebPath = "/WEB-INF/files/JAVASCRIPTPROG.txt"; String absoluteDiskPath = this.getServletContext().getRealPath(relativeWebPath); File file = new File(absoluteDiskPath); FileInputStream fstream = new FileInputStream(file); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; // Read File Line By Line while ((strLine = br.readLine()) != null) { // Print the content on the console out.println(strLine); } // Close the input stream in.close(); } catch (Exception e) { // Catch exception if any out.println("Error: " + e.getMessage()); } if (session.isNew() || session.getAttribute("session.PanierListe") == null) out.println("<a href=\"admin/admin.html\">Caddie (vide)</a></font><br></p>"); else if (session.getAttribute("session.PanierListe") != null) if (((PanierListe) session.getAttribute("session.PanierListe")).getSize() > 0) out.println( "<a href=\"admin/admin.html\">afficher caddie(" + ((PanierListe) session.getAttribute("session.PanierListe")).Liste.size() + "Representations dans le panier)" + "</a></font><br></p>"); try { Utilisateur user = Utilitaires.Identification(this); out.println(Utilitaires.AffichageAchat(user)); } catch (Exception e) { out.println(e.getMessage()); } out.println("</BODY>"); out.close(); }
public void close() throws IOException { if (closed) { throw new IOException("This output stream has already been closed"); } gzipstream.finish(); byte[] bytes = baos.toByteArray(); response.addHeader("Content-Length", Integer.toString(bytes.length)); response.addHeader("Content-Encoding", "gzip"); output.write(bytes); output.flush(); output.close(); closed = true; }
/** * Shows Application Error message to the user. * * @param response an HttpServletResponse object that contains the response the servlet sends to * the client. * @param msg Message to be displayed. */ private void showError(HttpServletResponse response, String msg) { ServletOutputStream out = null; if (msg == null || msg.equals("")) { msg = "ERROR: An application error has occured."; } try { out = response.getOutputStream(); out.println(msg); out.flush(); } catch (IOException e) { debug.error("CDCClientServlet.showError::Could not show error " + "message to the user " + e); } finally { try { out.close(); } catch (IOException ignore) { } } }
/** * return OutputStream of JasperReport object, this page could only be viewed from localhost for * security concern. parameter can be (id), or (table and type) * * @param id - report id, or * @param table - table name * @param type - reporttype "s","l","o", case insensitive * @param client(*) - client domain * @param version - version number, default to -1 */ public void process(HttpServletRequest request, HttpServletResponse response) throws Exception { String clientName = request.getParameter("client"); int objectId = ParamUtils.getIntAttributeOrParameter(request, "id", -1); if (objectId == -1) { // try using table and type objectId = getReportId(clientName, request.getParameter("table"), request.getParameter("type")); } if (objectId == -1) { logger.error("report not found, request is:" + Tools.toString(request)); throw new NDSException("report not found"); } int version = ParamUtils.getIntAttributeOrParameter(request, "version", -1); File reportXMLFile = new File(ReportTools.getReportFile(objectId, clientName)); if (reportXMLFile.exists()) { // generate jasperreport if file not exists or not newer String reportName = reportXMLFile.getName().substring(0, reportXMLFile.getName().lastIndexOf(".")); File reportJasperFile = new File(reportXMLFile.getParent(), reportName + ".jasper"); if (!reportJasperFile.exists() || reportJasperFile.lastModified() < reportXMLFile.lastModified()) { JasperCompileManager.compileReportToFile( reportXMLFile.getAbsolutePath(), reportJasperFile.getAbsolutePath()); } InputStream is = new FileInputStream(reportJasperFile); response.setContentType("application/octetstream;"); response.setContentLength((int) reportJasperFile.length()); // response.setHeader("Content-Disposition","inline;filename=\""+reportJasperFile.getName()+"\""); ServletOutputStream os = response.getOutputStream(); byte[] b = new byte[8192]; int bInt; while ((bInt = is.read(b, 0, b.length)) != -1) { os.write(b, 0, bInt); } is.close(); os.flush(); os.close(); } else { throw new NDSException("Not found report template"); } }
/** * This method must be invoked at the end of processing. The streams are closed and their content * is analyzed. Actual XSLT processing takes place here. */ @SuppressWarnings("unchecked") void finishResponse() throws IOException { if (writer != null) { writer.close(); } else { if (stream != null) stream.close(); } /* * If we're not in passthrough mode, then we need to finalize XSLT transformation. */ if (false == passthrough) { if (stream != null) { final byte[] bytes = ((DeferredOutputStream) stream).getBytes(); final boolean processingSuppressed = (origRequest.getAttribute(XSLTFilterConstants.NO_XSLT_PROCESSING) != null) | (origRequest.getParameter(XSLTFilterConstants.NO_XSLT_PROCESSING) != null); if (processingSuppressed) { // Just copy the buffered data to the output directly. final OutputStream os = origResponse.getOutputStream(); os.write(bytes); os.close(); } else { // Otherwise apply XSLT transformation to it. try { processWithXslt( bytes, (Map<String, Object>) origRequest.getAttribute(XSLTFilterConstants.XSLT_PARAMS_MAP), origResponse); } catch (TransformerException e) { final Throwable t = unwrapCause(e); if (t instanceof IOException) { throw (IOException) t; } filterError("Error applying stylesheet.", e); } } } } }
/** * Shows Application Error message to the user. * * @param response an HttpServletResponse object that contains the response the servlet sends to * the client. * @param msg Message to be displayed. */ private void showError(HttpServletResponse response, String msg) throws IOException { ServletOutputStream out = null; if (msg == null || msg.equals("") || msg.contains(SERVER_ERROR_STR_MATCH)) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } try { out = response.getOutputStream(); out.println(msg); out.flush(); } catch (IOException e) { debug.error("CDCClientServlet.showError::Could not show error " + "message to the user " + e); } finally { try { out.close(); } catch (IOException ignore) { } } }
/** * Permet de repondre a une requete web affiche le contenu du panier ansi que les differentes * Places disponible pour la Representation passee via la methode POST HTML Creation du panier , * des différent Item mis dedans et le rajoute dans les cookie Du client si necessaire. * * @param HttpServletRequest request requete * @param HttpServletResponse response réponse * @throw IOException, ServletException * @return void */ public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { HttpSession session = req.getSession(true); ServletOutputStream out = res.getOutputStream(); res.setContentType("text/html"); try { out.println("<HEAD><TITLE>Panier</TITLE></HEAD><BODY>"); out.println("<h1>Contenu du panier:</h1>"); out.println("<BODY bgproperties=\"fixed\" background=\"/images/rideau.JPG\">"); String nom = req.getParameter("nom"); String num = req.getParameter("num"); String date = req.getParameter("date"); String place = req.getParameter("place"); String rang = req.getParameter("rang"); SimpleDateFormat s = new SimpleDateFormat("dd/MM/yyyy HH"); // ajout d'une place au panier if (place != null && rang != null && num != null && date != null) { if (session.getAttribute("session.PanierListe") != null) { ((PanierListe) session.getAttribute("session.PanierListe")) .addPlace(num, date, place, rang); if ((String) session.getAttribute("session.log") != null) { // utilisateur loggé out.println("votre panier est enregistre"); Utilisateur user = Utilitaires.Identification(this); out.println( Utilitaires.enregistrerPlacePanier( user, (String) session.getAttribute("session.log"), num, date, place, rang)); } } } if (nom != null && num != null && date != null) { if (session.getAttribute("session.PanierListe") != null) { if (!((PanierListe) session.getAttribute("session.PanierListe")) .In(new Integer(num), date)) ((PanierListe) session.getAttribute("session.PanierListe")) .Liste.add( new Item( new Spectacle(nom, new Integer(num)), new Representation(new Integer(num), s.parse(date)))); } else { // creation d'un nouveau panier PanierListe p = new PanierListe(); p.Liste.add( new Item( new Spectacle(new String(nom), new Integer(num)), new Representation(new Integer(num), s.parse(date)))); session.setAttribute("session.PanierListe", p); } } // attention desormais le caddie est obligatoirement alloué if (session.getAttribute("session.PanierListe") != null && date != null && num != null) { out.println("contenu actuel du caddie:<br>"); out.println(((PanierListe) session.getAttribute("session.PanierListe")).toString()); out.println( "<h1>Veuillez selectionner une place pour la representation numero: " + num + "a la date du : " + date + ":</h1><br>"); // Affichage des places Dispo pour la representation: Utilisateur user = Utilitaires.Identification(this); out.println(Utilitaires.AffichagePlaceAchat(user, num, date)); out.println("<form class=\"link\" action=Validate \"method=POST>\n"); out.println("<button type=\"submit\">VALIDER LE PANIER</button>\n"); out.println("</form>"); } else out.println("Le caddie est vide<br>"); out.println("<hr><p><font color=\"#FFFFFF\"><a href=\"/index.html\">Accueil</a></p>"); out.close(); } catch (Exception e) { // Catch exception if any out.println("Error: " + e.getMessage()); } }
/** * cette methode permet de Recuperation de la liste de tous les spectacles de la saison. ent * construisant une une page web decrivant ces spectacles. * * @param req an HttpServletRequest object that contains the request the client has made of the * servlet * @param res an HttpServletResponse object that contains the response the servlet sends to the * client * @throws ServletException if the request for the GET could not be handled * @throws IOException if an input or output error is detected when the servlet handles the GET * request */ public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { ServletOutputStream out = res.getOutputStream(); HttpSession session = req.getSession(true); res.setContentType("text/html"); out.println("<HEAD><TITLE> Programme de la saison </TITLE></HEAD>"); out.println("<BODY bgproperties=\"fixed\" background=\"/images/rideau.JPG\">"); out.println("<font color=\"#FFFFFF\"><h1> Programme de la saison </h1>"); out.println("<FORM METHOD=POST>"); if (session.isNew()) { session.putValue("expand", null); session.putValue("rslt", null); } int[] expand = (int[]) session.getValue("expand"); Vector<Spectacle> rslt = (Vector<Spectacle>) session.getValue("rslt"); try { Utilisateur user = Utilitaires.Identification(this); if (rslt == null) { out.println("<p><i><font color=\"#FFFFFF\">actualy NEW</i></p>"); rslt = Utilitaires.getProgramme(user); session.putValue("rslt", rslt); if (rslt.isEmpty()) { out.println(" Liste vide <br>"); } else { expand = new int[rslt.size()]; Arrays.fill(expand, 0); session.putValue("expand", expand); for (int i = 0; i < rslt.size(); i++) { out.println( "<INPUT TYPE=SUBMIT NAME=LR" + rslt.elementAt(i).getNum() + " VALUE=" + "\"+\" > " + rslt.elementAt(i).getNom() + "<br>"); } } } else { for (int i = 0; i < rslt.size(); i++) { if (req.getParameter("LR" + rslt.elementAt(i).getNum()) != null) { expand[i] = 1; } else if (req.getParameter("less" + rslt.elementAt(i).getNum()) != null) { expand[i] = 0; } if (expand[i] == 0) { out.println( "<INPUT TYPE=SUBMIT NAME=LR" + rslt.elementAt(i).getNum() + " VALUE=" + "\"+\" >" + rslt.elementAt(i).getNom() + "<br>"); } else { out.println( "<INPUT TYPE=SUBMIT NAME=less" + rslt.elementAt(i).getNum() + " VALUE=" + "\"-\" >" + rslt.elementAt(i).getNom() + "<br>"); out.println(Utilitaires.listerRepresentations(user, rslt.elementAt(i).getNum())); } } } } catch (Exception e) { out.println(e.getMessage()); } out.println("</FORM></BODY>"); out.println("<hr><p><font color=\"#FFFFFF\"><a href=\"/index.html\">Accueil</a></p>"); out.close(); }
/** * Write a file to the response stream. Handles Range requests. * * @param req request * @param res response * @param file must exists and not be a directory * @param contentType must not be null * @throws IOException or error */ public static void returnFile( HttpServletRequest req, HttpServletResponse res, File file, String contentType) throws IOException { res.setContentType(contentType); // see if its a Range Request boolean isRangeRequest = false; long startPos = 0, endPos = Long.MAX_VALUE; String rangeRequest = req.getHeader("Range"); if (rangeRequest != null) { // bytes=12-34 or bytes=12- int pos = rangeRequest.indexOf("="); if (pos > 0) { int pos2 = rangeRequest.indexOf("-"); if (pos2 > 0) { String startString = rangeRequest.substring(pos + 1, pos2); String endString = rangeRequest.substring(pos2 + 1); startPos = Long.parseLong(startString); if (endString.length() > 0) endPos = Long.parseLong(endString) + 1; isRangeRequest = true; } } } // set content length long fileSize = file.length(); long contentLength = fileSize; if (isRangeRequest) { endPos = Math.min(endPos, fileSize); contentLength = endPos - startPos; } if (contentLength > Integer.MAX_VALUE) res.addHeader( "Content-Length", Long.toString(contentLength)); // allow content length > MAX_INT else res.setContentLength((int) contentLength); // note HEAD only allows this String filename = file.getPath(); boolean debugRequest = Debug.isSet("returnFile"); if (debugRequest) log.debug( "returnFile(): filename = " + filename + " contentType = " + contentType + " contentLength = " + contentLength); // indicate we allow Range Requests res.addHeader("Accept-Ranges", "bytes"); if (req.getMethod().equals("HEAD")) { log.info( "returnFile(): " + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_OK, 0)); return; } try { if (isRangeRequest) { // set before content is sent res.addHeader("Content-Range", "bytes " + startPos + "-" + (endPos - 1) + "/" + fileSize); res.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); FileCacheRaf.Raf craf = null; try { craf = fileCacheRaf.acquire(filename); IO.copyRafB( craf.getRaf(), startPos, contentLength, res.getOutputStream(), new byte[60000]); log.info( "returnFile(): " + UsageLog.closingMessageForRequestContext( HttpServletResponse.SC_PARTIAL_CONTENT, contentLength)); return; } finally { if (craf != null) fileCacheRaf.release(craf); } } // Return the file ServletOutputStream out = res.getOutputStream(); IO.copyFileB(file, out, 60000); res.flushBuffer(); out.close(); if (debugRequest) log.debug("returnFile(): returnFile ok = " + filename); log.info( "returnFile(): " + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_OK, contentLength)); } // @todo Split up this exception handling: those from file access vs those from dealing with // response // File access: catch and res.sendError() // response: don't catch (let bubble up out of doGet() etc) catch (FileNotFoundException e) { log.error("returnFile(): FileNotFoundException= " + filename); log.info( "returnFile(): " + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_NOT_FOUND, 0)); if (!res.isCommitted()) res.sendError(HttpServletResponse.SC_NOT_FOUND); } catch (java.net.SocketException e) { log.info("returnFile(): SocketException sending file: " + filename + " " + e.getMessage()); log.info("returnFile(): " + UsageLog.closingMessageForRequestContext(STATUS_CLIENT_ABORT, 0)); } catch (IOException e) { String eName = e.getClass().getName(); // dont want compile time dependency on ClientAbortException if (eName.equals("org.apache.catalina.connector.ClientAbortException")) { log.info( "returnFile(): ClientAbortException while sending file: " + filename + " " + e.getMessage()); log.info( "returnFile(): " + UsageLog.closingMessageForRequestContext(STATUS_CLIENT_ABORT, 0)); return; } log.error("returnFile(): IOException (" + e.getClass().getName() + ") sending file ", e); log.error( "returnFile(): " + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_NOT_FOUND, 0)); if (!res.isCommitted()) res.sendError(HttpServletResponse.SC_NOT_FOUND, "Problem sending file: " + e.getMessage()); } }
@Override public void close() throws IOException { offset = 0; target.close(); super.close(); }