Exemple #1
0
  public static void renderFile(
      HttpServletResponse resp,
      String filename,
      InputStream cont_stream,
      boolean showpic,
      boolean ignorespace)
      throws IOException {
    if (cont_stream == null) return;

    if (ignorespace) filename = filename.replace(" ", "");

    if (!showpic)
      resp.addHeader(
          "Content-Disposition",
          "attachment; filename=" + new String(filename.getBytes(), "iso8859-1"));

    resp.setContentType(Mime.getContentType(filename));
    ServletOutputStream os = resp.getOutputStream();
    byte[] buf = new byte[1024];
    int len = 0;
    while ((len = cont_stream.read(buf)) != -1) {
      os.write(buf, 0, len);
    }

    os.flush();
  }
  public void processAction(HttpServletRequest request, HttpServletResponse response)
      throws IOException {

    System.out.println("processing test driver request ... ");

    processParams(request);
    boolean status = false;
    System.out.println("tc:" + tc);

    response.setContentType("text/plain");
    ServletOutputStream out = response.getOutputStream();
    out.println("TestCase: " + tc);

    if (tc != null) {

      try {
        Class<?> c = getClass();
        Object t = this;

        Method[] allMethods = c.getDeclaredMethods();
        for (Method m : allMethods) {
          String mname = m.getName();
          if (!mname.equals(tc.trim())) {
            continue;
          }

          System.out.println("Invoking : " + mname);
          try {
            m.setAccessible(true);
            Object o = m.invoke(t);
            System.out.println("Returned => " + (Boolean) o);
            status = new Boolean((Boolean) o).booleanValue();
            // Handle any methods thrown by method to be invoked
          } catch (InvocationTargetException x) {
            Throwable cause = x.getCause();

            System.err.format("invocation of %s failed: %s%n", mname, cause.getMessage());
          } catch (IllegalAccessException x) {
            x.printStackTrace();
          }
        }
      } catch (Exception ex) {
        ex.printStackTrace();
      }

      if (status) {
        out.println(tc + ":pass");
      } else {
        out.println(tc + ":fail");
      }
    }
  }
Exemple #3
0
  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;
  }
Exemple #4
0
  public static void renderXormFile(
      HttpServletRequest req,
      HttpServletResponse resp,
      Class xormc,
      String xormprop,
      long pkid,
      String filename,
      boolean showpic,
      Date lastmodify)
      throws ClassNotFoundException, Exception {
    filename = filename.replace(" ", "");

    if (!showpic)
      resp.addHeader(
          "Content-Disposition",
          "attachment; filename=" + new String(filename.getBytes(), "iso8859-1"));

    if (lastmodify != null) {
      resp.setDateHeader("Last-Modified", lastmodify.getTime());
    }

    if (req != null) {
      long l = req.getDateHeader("If-Modified-Since");
      if (l > 0) {
        if (lastmodify != null
            && lastmodify.getTime() / 1000 <= l / 1000) { // 由于文件系统的最后修改时间精确到秒,所以需要去除毫秒以便于计算
          resp.setStatus(304); // not modify
          return;
        }
      }
    }

    GDB g = GDB.getInstance();

    long filelen = g.getXORMFileContLength(xormc, xormprop, pkid);
    if (filelen < 0) return;

    resp.setContentLength((int) filelen);
    resp.setContentType(Mime.getContentType(filename));
    ServletOutputStream os = resp.getOutputStream();
    GDB.getInstance().loadXORMFileContToOutputStream(xormc, xormprop, pkid, os);
    os.flush();
  }
Exemple #5
0
  /**
   * 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");
    }
  }
  protected void respondAdmin(HttpServletRequest req, HttpServletResponse res) throws IOException {
    res.setContentType("text/xml");
    StringBuffer buf = new StringBuffer();

    String _details = req.getParameter("details");
    boolean details = (_details != null && _details.equals("1"));

    ConnectionGroup.dumpGroupsXML(buf, details);

    String appName = req.getParameter("application");
    if (appName != null && !appName.equals("")) {
      if (appName.equals("*")) {
        Application.dumpApplicationsXML(buf, details);
      } else {
        Application application = Application.getApplication(appName, false);
        if (application != null) application.toString();
      }
    }

    ConnectionAgent.dumpAgentsXML(buf, details);

    ServletOutputStream out = res.getOutputStream();
    try {
      out.println(
          "<connection-info "
              + " max-message-length=\""
              + HTTPConnection.getMaxMessageLen()
              + "\""
              + " connection-length=\""
              + HTTPConnection.getConnectionLength()
              + "\""
              + " reconnection-wait-interval=\""
              + HTTPConnection.getReconnectionWaitInterval()
              + "\""
              + " >");
      out.println(buf.toString());
      out.println("</connection-info>");
    } finally {
      FileUtils.close(out);
    }
  }
Exemple #7
0
  public static void renderFile(
      HttpServletRequest req,
      HttpServletResponse resp,
      String filename,
      byte[] file_cont,
      boolean showpic,
      Date lastmodify)
      throws IOException {
    if (file_cont == null) return;

    //		if(!showpic)
    //			resp.addHeader("Content-Disposition", "attachment;
    // filename=\""+MimeUtility.encodeText(filename,"UTF-8",null)+"\"");
    filename = filename.replace(" ", "");
    if (!showpic)
      resp.addHeader(
          "Content-Disposition",
          "attachment; filename=" + new String(filename.getBytes(), "iso8859-1"));

    if (lastmodify != null) {
      resp.setDateHeader("Last-Modified", lastmodify.getTime());
    }

    if (req != null) {
      long l = req.getDateHeader("If-Modified-Since");
      if (l > 0) {
        if (lastmodify != null
            && lastmodify.getTime() / 1000 <= l / 1000) { // 由于文件系统的最后修改时间精确到秒,所以需要去除毫秒以便于计算
          resp.setStatus(304);
          return;
        }
      }
    }

    resp.setContentType(Mime.getContentType(filename));
    ServletOutputStream os = resp.getOutputStream();
    os.write(file_cont);
    os.flush();
  }
Exemple #8
0
  /**
   * this is the main method of the servlet that will service all get requests.
   *
   * @param request HttpServletRequest
   * @param responce HttpServletResponce
   */
  public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    try {
      res.setContentType("text/html");

      // The following 2 lines are the difference between PingServlet and PingServletWriter
      //   the latter uses a PrintWriter for output versus a binary output stream.
      ServletOutputStream out = res.getOutputStream();
      // java.io.PrintWriter out = res.getWriter();
      hitCount++;
      out.println(
          "<html><head><title>Ping Servlet</title></head>"
              + "<body><HR><BR><FONT size=\"+2\" color=\"#000066\">Ping Servlet<BR></FONT><FONT size=\"+1\" color=\"#000066\">Init time : "
              + initTime
              + "<BR><BR></FONT>  <B>Hit Count: "
              + hitCount
              + "</B></body></html>");
    } catch (Exception e) {
      Log.error(e, "PingServlet.doGet(...): general exception caught");
      res.sendError(500, e.toString());
    }
  }
Exemple #9
0
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @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 {

    Player player = ((Player) (request.getSession().getAttribute(CONFIG.PLAYERNAME)));

    String uri = request.getRequestURI();
    String file = uri.substring(uri.lastIndexOf("/") + 1);
    String mima = file.substring(file.lastIndexOf(".") + 1).toLowerCase();

    String type = null;
    if (mima.equals("gif")) {
      type = "gif";
    }
    if (mima.equals("jpg")) {
      type = "jpg";
    }
    if (mima.equals("png")) {
      type = "png";
    }
    if (type == null) {
      System.out.println("Unrecognized image file type." + " - " + mima);
    } else {
      byte[] image = readImageFile.getContent(player, file);

      if (image != null) {
        response.setContentType(type);
        ServletOutputStream out = response.getOutputStream();
        try {
          out.write(image);
        } finally {
          out.close();
        }
      } else {
        System.out.println("NULL image");
      }
    }
  }
  /**
   * 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);
          }
        }
      }
    }
  }
Exemple #11
0
  protected void service(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, java.io.IOException {
    String p = req.getParameter("r");
    if (p == null || (p = p.trim()).equals("")) {
      String pi = req.getPathInfo();

      return;
    }

    byte[] cont = res2cont.get(p);
    if (cont != null) {
      resp.setContentType(Mime.getContentType(p));
      ServletOutputStream os = resp.getOutputStream();
      os.write(cont);
      os.flush();
      return;
    }

    InputStream is = null;
    try {
      is = appCL.getResourceAsStream(p); // getInputStreamByPath(p) ;
      if (is == null) {
        is = new Object().getClass().getResourceAsStream(p);
        if (is == null) return;
      }

      byte[] buf = new byte[1024];
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      int len;
      while ((len = is.read(buf)) >= 0) {
        baos.write(buf, 0, len);
      }

      cont = baos.toByteArray();
      res2cont.put(p, cont);
      resp.setContentType(Mime.getContentType(p));
      ServletOutputStream os = resp.getOutputStream();
      os.write(cont);
      os.flush();
      return;
    } finally {
      if (is != null) is.close();
    }
  }
Exemple #12
0
 @Override
 public void close() throws IOException {
   offset = 0;
   target.close();
   super.close();
 }
Exemple #13
0
  /**
   * 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());
    }
  }
 public void printApplications(ServletOutputStream out) throws IOException {
   out.println("<application-list>");
   out.println("</application-list>");
 }
Exemple #15
0
  /**
   * this is the main method of the servlet that will service all get requests.
   *
   * @param request HttpServletRequest
   * @param responce HttpServletResponce
   */
  public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    try {
      res.setContentType("text/html");

      ServletOutputStream out = res.getOutputStream();
      hitCount++;
      long totalMemory = Runtime.getRuntime().totalMemory();

      long maxMemoryBeforeGC = Runtime.getRuntime().maxMemory();
      long freeMemoryBeforeGC = Runtime.getRuntime().freeMemory();
      long startTime = System.currentTimeMillis();

      System.gc(); // Invoke the GC.

      long endTime = System.currentTimeMillis();
      long maxMemoryAfterGC = Runtime.getRuntime().maxMemory();
      long freeMemoryAfterGC = Runtime.getRuntime().freeMemory();

      out.println(
          "<html><head><title>ExplicitGC</title></head>"
              + "<body><HR><BR><FONT size=\"+2\" color=\"#000066\">Explicit Garbage Collection<BR></FONT><FONT size=\"+1\" color=\"#000066\">Init time : "
              + initTime
              + "<BR><BR></FONT>  <B>Hit Count: "
              + hitCount
              + "<br>"
              + "<table border=\"0\"><tr>"
              + "<td align=\"right\">Total Memory</td><td align=\"right\">"
              + totalMemory
              + "</td>"
              + "</tr></table>"
              + "<table width=\"350\"><tr><td colspan=\"2\" align=\"left\">"
              + "Statistics before GC</td></tr>"
              + "<tr><td align=\"right\">"
              + "Max Memory</td><td align=\"right\">"
              + maxMemoryBeforeGC
              + "</td></tr>"
              + "<tr><td align=\"right\">"
              + "Free Memory</td><td align=\"right\">"
              + freeMemoryBeforeGC
              + "</td></tr>"
              + "<tr><td align=\"right\">"
              + "Used Memory</td><td align=\"right\">"
              + (totalMemory - freeMemoryBeforeGC)
              + "</td></tr>"
              + "<tr><td colspan=\"2\" align=\"left\">Statistics after GC</td></tr>"
              + "<tr><td align=\"right\">"
              + "Max Memory</td><td align=\"right\">"
              + maxMemoryAfterGC
              + "</td></tr>"
              + "<tr><td align=\"right\">"
              + "Free Memory</td><td align=\"right\">"
              + freeMemoryAfterGC
              + "</td></tr>"
              + "<tr><td align=\"right\">"
              + "Used Memory</td><td align=\"right\">"
              + (totalMemory - freeMemoryAfterGC)
              + "</td></tr>"
              + "<tr><td align=\"right\">"
              + "Total Time in GC</td><td align=\"right\">"
              + Float.toString((endTime - startTime) / 1000)
              + "s</td></tr>"
              + "</table>"
              + "</body></html>");
    } catch (Exception e) {
      Log.error(e, "ExplicitGC.doGet(...): general exception caught");
      res.sendError(500, e.toString());
    }
  }
  /**
   * 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());
    }
  }
Exemple #17
0
  /** @service the servlet service request. called once for each servlet request. */
  public void service(HttpServletRequest servReq, HttpServletResponse servRes) throws IOException {
    String name;
    String value[];
    String val;

    servRes.setHeader("AUTHORIZATION", "user fred:mypassword");
    ServletOutputStream out = servRes.getOutputStream();

    HttpSession session = servReq.getSession(true);
    session.setAttribute("timemilis", new Long(System.currentTimeMillis()));
    if (session.isNew()) {
      out.println("<p> Session is new ");
    } else {
      out.println("<p> Session is not new ");
    }
    Long l = (Long) session.getAttribute("timemilis");
    out.println("<p> Session id = " + session.getId());
    out.println("<p> TimeMillis = " + l);

    out.println("<H2>Servlet Params</H2>");
    Enumeration e = servReq.getParameterNames();
    while (e.hasMoreElements()) {
      name = (String) e.nextElement();
      value = servReq.getParameterValues(name);
      out.println(name + " : ");
      for (int i = 0; i < value.length; ++i) {
        out.println(value[i]);
      }
      out.println("<p>");
    }

    out.println("<H2> Request Headers : </H2>");
    e = servReq.getHeaderNames();
    while (e.hasMoreElements()) {
      name = (String) e.nextElement();
      val = (String) servReq.getHeader(name);
      out.println("<p>" + name + " : " + val);
    }
    try {
      BufferedReader br = servReq.getReader();
      String line = null;
      while (null != (line = br.readLine())) {
        out.println(line);
      }
    } catch (IOException ie) {
      ie.printStackTrace();
    }

    session.invalidate();
  }
Exemple #18
0
  public void service(ServletRequest request, ServletResponse response) {
    int font;
    pdflib p = null;
    int i, blockcontainer, page;
    String infile = "boilerplate.pdf";
    /* This is where font/image/PDF input files live. Adjust as necessary.
     *
     * Note that this directory must also contain the LuciduxSans font
     * outline and metrics files.
     */
    String searchpath = "../data";
    String[][] data = {
      {"name", "Victor Kraxi"},
      {"business.title", "Chief Paper Officer"},
      {"business.address.line1", "17, Aviation Road"},
      {"business.address.city", "Paperfield"},
      {"business.telephone.voice", "phone +1 234 567-89"},
      {"business.telephone.fax", "fax +1 234 567-98"},
      {"business.email", "*****@*****.**"},
      {"business.homepage", "www.kraxi.com"},
    };
    byte[] buf;
    ServletOutputStream out;

    try {
      p = new pdflib();

      // Generate a PDF in memory; insert a file name to create PDF on disk
      if (p.begin_document("", "") == -1) {
        throw new Exception("Error: " + p.get_errmsg());
      }

      /*Set the search path for fonts and PDF files */
      p.set_parameter("SearchPath", searchpath);

      p.set_info("Creator", "businesscard.java");
      p.set_info("Author", "Thomas Merz");
      p.set_info("Title", "PDFlib block processing sample (Java)");

      blockcontainer = p.open_pdi(infile, "", 0);
      if (blockcontainer == -1) {
        throw new Exception("Error: " + p.get_errmsg());
      }

      page = p.open_pdi_page(blockcontainer, 1, "");
      if (page == -1) {
        throw new Exception("Error: " + p.get_errmsg());
      }

      p.begin_page_ext(20, 20, ""); // dummy page size

      // This will adjust the page size to the block container's size.
      p.fit_pdi_page(page, 0, 0, "adjustpage");

      // Fill all text blocks with dynamic data
      for (i = 0; i < (int) data.length; i++) {
        if (p.fill_textblock(page, data[i][0], data[i][1], "embedding encoding=unicode") == -1) {
          System.err.println("Warning: " + p.get_errmsg());
        }
      }

      p.end_page_ext(""); // close page
      p.close_pdi_page(page);

      p.end_document(""); // close PDF document
      p.close_pdi(blockcontainer);

      buf = p.get_buffer();

      response.setContentType("application/pdf");
      response.setContentLength(buf.length);

      out = response.getOutputStream();
      out.write(buf);
      out.close();

    } catch (PDFlibException e) {
      System.err.print("PDFlib exception occurred in businesscard sample:\n");
      System.err.print(
          "[" + e.get_errnum() + "] " + e.get_apiname() + ": " + e.get_errmsg() + "\n");
    } catch (Exception e) {
      System.err.println(e.getMessage());
    } finally {
      if (p != null) {
        p.delete(); /* delete the PDFlib object */
      }
    }
  }
 /**
  * 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();
 }