/**
   * This method will open the sample report pdf.
   *
   * @param reportFilePath - full path of the sample report to be shown.
   * @param request - instance of HttpServletRequest
   * @param response - instance of HttpServletResponse
   * @throws ServletException - error
   * @throws IOException - error
   */
  private static void showSampleReport(
      String reportFilePath, HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    if (null != request.getSession().getAttribute(ReportServiceConstant.VIEW_SAMPLE_REPORT)
        && request
            .getSession()
            .getAttribute(ReportServiceConstant.VIEW_SAMPLE_REPORT)
            .toString()
            .equalsIgnoreCase("Y")) {
      ServletOutputStream output = null;
      try {

        FileInputStream fis = new FileInputStream(reportFilePath);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buf = new byte[256];
        try {
          for (int readNum; (readNum = fis.read(buf)) != -1; ) {
            baos.write(buf, 0, readNum); // no doubt here is 0
            // Writes len bytes from the specified byte array starting at offset off to this byte
            // array output stream.
          }

        } catch (IOException ex) {
          ex.printStackTrace();
        }

        if (null != baos) {

          // Init servlet response.
          response.reset();
          response.setContentType("application/pdf");
          response.setContentLength(baos.size());
          response.setHeader("Content-disposition", "inline; filename=\"" + reportFilePath);
          response.setHeader("Expires", "0");
          response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
          //                  response.setHeader("Transfer-Encoding", "identity");
          output = response.getOutputStream();

          output.write(baos.toByteArray(), 0, baos.size());

          // Finalize task.
          output.flush();
        }
      } catch (Exception exception) {
        OPPE_LOG.error("ERROR.SHOW_PDF.ERROR", exception);
      } finally {

        // Gently close streams.
        close((Closeable) output);
      }
    }
  }
예제 #2
0
  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");
      }
    }
  }
예제 #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;
  }
예제 #4
0
 /**
  * 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) {
     }
   }
 }
예제 #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);
    }
  }
예제 #7
0
  /**
   * 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) {
      }
    }
  }
예제 #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());
    }
  }
예제 #9
0
  /**
   * 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);
          }
        }
      }
    }
  }
예제 #10
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());
    }
  }
 /**
  * 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();
 }
예제 #12
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());
    }
  }
  /**
   * This method handles response of showing pdf servlet.
   *
   * @param request - instance of HttpServletRequest
   * @param response - instance of HttpServletResponse
   * @throws ServletException - error
   * @throws IOException - error
   */
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String preview = request.getParameter(PREVIEW_REPORT_PARAMETER);
    String sampleReportParam = request.getParameter(SAMPLE_REPORT_PARAM);
    if (null != sampleReportParam) {
      String sampleReportPath = "";
      if (sampleReportParam.equalsIgnoreCase(ReportServiceConstant.PROVIDER_SUMMARY)) {
        sampleReportPath =
            WL_HOME_PATH + RESOURCES_PATH + ReportServiceConstant.PROVIDER_SUMMARY_SAMPLE_FILE;
        showSampleReport(sampleReportPath, request, response);
      } else if (sampleReportParam.equalsIgnoreCase(ReportServiceConstant.COMPARATIVE_SUMMARY)) {
        sampleReportPath =
            WL_HOME_PATH + RESOURCES_PATH + ReportServiceConstant.COMPARITIVE_SUMMARY_SAMPLE_FILE;
        showSampleReport(sampleReportPath, request, response);
      } else if (sampleReportParam.equalsIgnoreCase(ReportServiceConstant.EXECUTIVE_SUMMARY)) {
        sampleReportPath =
            WL_HOME_PATH + RESOURCES_PATH + ReportServiceConstant.EXECUTIVE_SUMMARY_SAMPLE_FILE;
        showSampleReport(sampleReportPath, request, response);
      }
    } else if (null != preview && STR_TRUE.equals(preview)) {
      // report generation using OracleBI
      ServletOutputStream output = null;
      byte[] rawBinaryFile = null;
      Map<String, String> parameterMap = null;
      PublicReportServicePortClient client = null;
      FileStream fileStream = null;
      try {

        if (null != request.getSession().getAttribute(REPORTS_PARAMETERS_MAP)) {
          parameterMap =
              (Map<String, String>) request.getSession().getAttribute(REPORTS_PARAMETERS_MAP);
          //                    request.getSession().removeAttribute(REPORTS_PARAMETERS_MAP);
        }

        if (null != parameterMap && parameterMap.containsKey("REPORT_PATH")) {
          client = new PublicReportServicePortClient();
          fileStream = client.generateReport(parameterMap);
          rawBinaryFile = fileStream.getFileContent();
        }

        if (null != rawBinaryFile) {

          // Init servlet response.
          response.reset();
          response.setContentType("application/pdf");
          response.setContentLength(rawBinaryFile.length);
          response.setHeader(
              "Content-disposition", "inline; filename=\"" + fileStream.getFileName() + ".pdf\"");
          response.setHeader("Expires", "0");
          response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
          //                  response.setHeader("Transfer-Encoding", "identity");
          output = response.getOutputStream();

          output.write(rawBinaryFile, 0, rawBinaryFile.length);

          // Finalize task.
          output.flush();
        }
      } catch (Exception exception) {
        OPPE_LOG.error("ERROR.SHOW_PDF.ERROR", exception);
      } finally {

        // Gently close streams.
        close((Closeable) output);
      }
    }
  }
예제 #14
0
  /**
   * Get Query By Form results throught response output stream.
   *
   * @param queryspec Name of XML file containing the Query Specification
   * @param columnlist List of comma separated column names to retrieve
   * @param where SQL WHERE clause to apply
   * @param order by SQL ORDER BY clause to apply
   * @param showas Output format. One of { "CSV" <i>(comma separated)</i>, "TSV" <i>(tabbed
   *     separated)</i>, "XLS" <i>(Excel)</i> }
   * @throws IOException
   * @throws FileNotFoundException
   * @throws ServletException
   */
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException, FileNotFoundException, ServletException {
    Class oDriver;
    Connection oConn = null;
    ServletOutputStream oOut = response.getOutputStream();
    QueryByForm oQBF;
    String sQuerySpec;
    String sColumnList;
    String sWhere;
    String sOrderBy;
    String sShowAs;
    String sStorage;

    if (DebugFile.trace) {
      DebugFile.writeln("Begin HttpQueryServlet.doGet(...)");
      DebugFile.incIdent();
    }

    sStorage = Environment.getProfileVar("hipergate", "storage");

    if (DebugFile.trace) DebugFile.writeln("storage=" + sStorage);

    try {
      oDriver = Class.forName(jdbcDriverClassName);
    } catch (ClassNotFoundException ignore) {
      oDriver = null;
      if (DebugFile.trace)
        DebugFile.writeln("Class.forName(" + jdbcDriverClassName + ") : " + ignore.getMessage());
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Database driver not found");
    }

    if (null == oDriver) return;

    try {

      sQuerySpec = request.getParameter("queryspec");
      sColumnList = request.getParameter("columnlist");
      if (null == sColumnList) sColumnList = "*";
      sWhere = request.getParameter("where");
      if (null == sWhere) sWhere = "1=1";
      sOrderBy = request.getParameter("orderby");
      if (null == sOrderBy) sOrderBy = "";
      sShowAs = request.getParameter("showas");
      if (null == sShowAs) sShowAs = "CSV";

      if (DebugFile.trace)
        DebugFile.writeln("queryspec=" + sQuerySpec != null ? sQuerySpec : "null");
      if (DebugFile.trace) DebugFile.writeln("where=" + sWhere);
      if (DebugFile.trace) DebugFile.writeln("orderby=" + sOrderBy);

      if (hasSqlSignature(sColumnList)) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid Column List Syntax");
        return;
      }

      oQBF = new QueryByForm("file://" + sStorage + "/qbf/" + sQuerySpec + ".xml");

      if (DebugFile.trace) DebugFile.writeln("DriverManager.getConnection(" + jdbcURL + ",...)");
      oConn = DriverManager.getConnection(jdbcURL, dbUserName, dbUserPassword);

      // Send some basic http headers to support binary d/l.
      if (sShowAs.equalsIgnoreCase("XLS")) {
        response.setContentType("application/x-msexcel");
        response.setHeader(
            "Content-Disposition",
            "inline; filename=\"" + oQBF.getTitle(request.getLocale().getLanguage()) + " 1.csv\"");
      } else if (sShowAs.equalsIgnoreCase("CSV")) {
        response.setContentType("text/plain");
        response.setHeader(
            "Content-Disposition",
            "attachment; filename=\""
                + oQBF.getTitle(request.getLocale().getLanguage())
                + " 1.csv\"");
      } else if (sShowAs.equalsIgnoreCase("TSV")) {
        response.setContentType("text/tab-separated-values");
        response.setHeader(
            "Content-Disposition",
            "attachment; filename=\""
                + oQBF.getTitle(request.getLocale().getLanguage())
                + " 1.tsv\"");
      } else {
        response.setContentType("text/plain");
        response.setHeader(
            "Content-Disposition",
            "inline; filename=\"" + oQBF.getTitle(request.getLocale().getLanguage()) + " 1.txt\"");
      }

      if (0 == sOrderBy.length())
        oQBF.queryToStream(
            oConn, sColumnList, oQBF.getBaseFilter(request) + " " + sWhere, oOut, sShowAs);
      else
        oQBF.queryToStream(
            oConn,
            sColumnList,
            oQBF.getBaseFilter(request) + " " + sWhere + " ORDER BY " + sOrderBy,
            oOut,
            sShowAs);

      oConn.close();
      oConn = null;

      oOut.flush();
    } catch (SQLException e) {
      if (DebugFile.trace) DebugFile.writeln("SQLException " + e.getMessage());
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } catch (ClassNotFoundException e) {
      if (DebugFile.trace) DebugFile.writeln("ClassNotFoundException " + e.getMessage());
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } catch (IllegalAccessException e) {
      if (DebugFile.trace) DebugFile.writeln("IllegalAccessException " + e.getMessage());
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } catch (Exception e) {
      if (DebugFile.trace) DebugFile.writeln("Exception " + e.getMessage());
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } finally {
      try {
        if (null != oConn) if (!oConn.isClosed()) oConn.close();
      } catch (SQLException e) {
        if (DebugFile.trace) DebugFile.writeln("SQLException " + e.getMessage());
      }
    }

    if (DebugFile.trace) {
      DebugFile.decIdent();
      DebugFile.writeln("End HttpQueryServlet.doGet()");
    }
  } // doGet()
 public void printApplications(ServletOutputStream out) throws IOException {
   out.println("<application-list>");
   out.println("</application-list>");
 }
예제 #16
0
  /**
   * 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();
  }
예제 #17
0
 @Override
 public void close() throws IOException {
   offset = 0;
   target.close();
   super.close();
 }
예제 #18
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();
  }
  // authentication request
  public String authRequest(
      String userSuppliedString, HttpServletRequest httpReq, HttpServletResponse httpResp)
      throws IOException, ServletException {

    if (OpenIDRealm.instance == null) {
      ServletOutputStream out = httpResp.getOutputStream();
      httpResp.setContentType("text/html; charset=\"UTF-8\"");
      httpResp.addHeader("pragma", "no-cache");
      httpResp.addHeader("Cache-Control", "no-cache");

      httpResp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

      out.print("<html><head>");
      out.print("<title>OpenIDServlet Error</title>");
      out.print("<link rel=\"stylesheet\" type=\"text/css\" href=\"error.css\"></link></head>");
      out.print("<body><div id=\"container\"><h1>Error found</h1>");

      out.print("<h2>Message:");
      out.print("OpenID realm wasn't initialized.");
      out.print("</h2>");

      // out.print(HTTPUtils.printStackTraceHTML(t));

      out.print("</div></body></html>");
      return null;
    }
    try {
      String returnAfterAuthentication = httpReq.getParameter("return_to");

      // configure the return_to URL where your application will receive
      // the authentication responses from the OpenID provider
      String returnToUrl =
          httpReq.getRequestURL().toString()
              + "?is_return=true&exist_return="
              + returnAfterAuthentication;

      // perform discovery on the user-supplied identifier
      List<?> discoveries = manager.discover(userSuppliedString);

      // attempt to associate with the OpenID provider
      // and retrieve one service endpoint for authentication
      DiscoveryInformation discovered = manager.associate(discoveries);

      // store the discovery information in the user's session
      httpReq.getSession().setAttribute("openid-disc", discovered);

      // obtain a AuthRequest message to be sent to the OpenID provider
      AuthRequest authReq = manager.authenticate(discovered, returnToUrl);

      if (authReq.getOPEndpoint().indexOf("myopenid.com") > 0) {
        SRegRequest sregReq = SRegRequest.createFetchRequest();

        sregReq.addAttribute(AXSchemaType.FULLNAME.name().toLowerCase(), true);
        sregReq.addAttribute(AXSchemaType.EMAIL.name().toLowerCase(), true);
        sregReq.addAttribute(AXSchemaType.COUNTRY.name().toLowerCase(), true);
        sregReq.addAttribute(AXSchemaType.LANGUAGE.name().toLowerCase(), true);

        authReq.addExtension(sregReq);
      } else {

        FetchRequest fetch = FetchRequest.createFetchRequest();

        fetch.addAttribute(
            AXSchemaType.FIRSTNAME.getAlias(), AXSchemaType.FIRSTNAME.getNamespace(), true);
        fetch.addAttribute(
            AXSchemaType.LASTNAME.getAlias(), AXSchemaType.LASTNAME.getNamespace(), true);
        fetch.addAttribute(AXSchemaType.EMAIL.getAlias(), AXSchemaType.EMAIL.getNamespace(), true);
        fetch.addAttribute(
            AXSchemaType.COUNTRY.getAlias(), AXSchemaType.COUNTRY.getNamespace(), true);
        fetch.addAttribute(
            AXSchemaType.LANGUAGE.getAlias(), AXSchemaType.LANGUAGE.getNamespace(), true);

        // wants up to three email addresses
        fetch.setCount(AXSchemaType.EMAIL.getAlias(), 3);

        authReq.addExtension(fetch);
      }

      if (!discovered.isVersion2()) {
        // Option 1: GET HTTP-redirect to the OpenID Provider endpoint
        // The only method supported in OpenID 1.x
        // redirect-URL usually limited ~2048 bytes
        httpResp.sendRedirect(authReq.getDestinationUrl(true));
        return null;

      } else {
        // Option 2: HTML FORM Redirection (Allows payloads >2048 bytes)

        Object OPEndpoint = authReq.getDestinationUrl(false);

        ServletOutputStream out = httpResp.getOutputStream();

        httpResp.setContentType("text/html; charset=UTF-8");
        httpResp.addHeader("pragma", "no-cache");
        httpResp.addHeader("Cache-Control", "no-cache");

        out.println("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
        out.println("<head>");
        out.println("    <title>OpenID HTML FORM Redirection</title>");
        out.println("</head>");
        out.println("<body onload=\"document.forms['openid-form-redirection'].submit();\">");
        out.println(
            "    <form name=\"openid-form-redirection\" action=\""
                + OPEndpoint
                + "\" method=\"post\" accept-charset=\"utf-8\">");

        Map<String, String> parameterMap = authReq.getParameterMap();
        for (Entry<String, String> entry : parameterMap.entrySet()) {
          out.println(
              "	<input type=\"hidden\" name=\""
                  + entry.getKey()
                  + "\" value=\""
                  + entry.getValue()
                  + "\"/>");
        }

        out.println("        <button type=\"submit\">Continue...</button>");
        out.println("    </form>");
        out.println("</body>");
        out.println("</html>");

        out.flush();
      }
    } catch (OpenIDException e) {
      // present error to the user
      LOG.debug("OpenIDException", e);

      ServletOutputStream out = httpResp.getOutputStream();
      httpResp.setContentType("text/html; charset=\"UTF-8\"");
      httpResp.addHeader("pragma", "no-cache");
      httpResp.addHeader("Cache-Control", "no-cache");

      httpResp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

      out.print("<html><head>");
      out.print("<title>OpenIDServlet Error</title>");
      out.print("<link rel=\"stylesheet\" type=\"text/css\" href=\"error.css\"></link></head>");
      out.print("<body><div id=\"container\"><h1>Error found</h1>");

      out.print("<h2>Message:");
      out.print(e.getMessage());
      out.print("</h2>");

      Throwable t = e.getCause();
      if (t != null) {
        // t can be null
        out.print(HTTPUtils.printStackTraceHTML(t));
      }

      out.print("</div></body></html>");
    }

    return null;
  }
예제 #20
0
  /**
   * 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());
    }
  }