/**
  * 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();
 }
  /**
   * Attempts to send an internal server error HTTP error, if possible. Otherwise simply pushes the
   * exception message to the output stream.
   *
   * @param message Message to be printed to the logger and to the output stream.
   * @param t Exception that caused the error.
   */
  protected void filterError(String message, Throwable t) {
    log.error("XSLT filter error: " + message, t);
    if (false == origResponse.isCommitted()) {
      // Reset the buffer and previous status code.
      origResponse.reset();
      origResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      origResponse.setContentType("text/html; charset=UTF-8");
    }

    // Response committed. Just push the error to the output stream.
    try {
      final OutputStream os = origResponse.getOutputStream();
      final PrintWriter osw = new PrintWriter(new OutputStreamWriter(os, "iso8859-1"));
      osw.write("<html><body><!-- " + XSLTFilterConstants.ERROR_TOKEN + " -->");
      osw.write("<h1 style=\"color: red; margin-top: 1em;\">");
      osw.write("Internal server exception");
      osw.write("</h1>");
      osw.write("<b>URI</b>: " + origRequest.getRequestURI() + "\n<br/><br/>");
      serializeException(osw, t);
      if (t instanceof ServletException && ((ServletException) t).getRootCause() != null) {
        osw.write("<br/><br/><h2>ServletException root cause:</h2>");
        serializeException(osw, ((ServletException) t).getRootCause());
      }
      osw.write("</body></html>");
      osw.flush();
    } catch (IOException e) {
      // Not much to do in such case (connection broken most likely).
      log.debug("Filter error could not be returned to client.");
    }
  }
Esempio n. 3
0
  @Override
  public void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws IOException, ServletException {
    String sid = req.getParameter("sid");
    String gameId = req.getParameter("game");
    String action = req.getParameter("action");

    HanabiUser user = s.getUserBySession(sid);
    HanabiGame game = s.getGame(gameId);

    try {

      String message;
      if (action.equals("play_card")) {
        int slot = Integer.parseInt(req.getParameter("handSlot"));
        HanabiGame.PlayCardResult rv = game.playCard(slot);
        message = "It was a " + rv.card + "; " + (rv.success ? "Success!" : "Oops!");
      } else if (action.equals("discard_card")) {
        int slot = Integer.parseInt(req.getParameter("handSlot"));
        HanabiGame.Card c = game.discardCard(slot);
        message = "It was a " + c;
      } else if (action.equals("give_hint")) {
        doGiveHint(game, req, resp);
        return;
      } else {
        message = "don't know how to " + action;
      }

      JsonGenerator out = new JsonFactory().createJsonGenerator(resp.getOutputStream());

      out.writeStartObject();
      out.writeStringField("message", message);
      out.writeEndObject();
      out.close();

    } catch (HanabiException e) {

      resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

      JsonGenerator out = new JsonFactory().createJsonGenerator(resp.getOutputStream());
      out.writeStartObject();
      out.writeStringField("status", "error");
      out.writeStringField("message", e.toString());
      out.writeEndObject();
      out.close();
    }
  }
Esempio n. 4
0
 public GZIPResponseStream(HttpServletResponse response) throws IOException {
   super();
   closed = false;
   this.response = response;
   this.output = response.getOutputStream();
   baos = new ByteArrayOutputStream();
   gzipstream = new GZIPOutputStream(baos);
 }
Esempio n. 5
0
 /**
  * Sets a status and sends an info message.
  *
  * @param code status code
  * @param message info message
  * @throws IOException I/O exception
  */
 public void status(final int code, final String message) throws IOException {
   log(true, code, message);
   if (session != null) session.close();
   res.resetBuffer();
   res.setStatus(code);
   if (code == SC_UNAUTHORIZED) res.setHeader(WWW_AUTHENTICATE, BASIC);
   if (message != null) res.getOutputStream().write(token(message));
 }
Esempio n. 6
0
  protected void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    try {
      DateFormat df = DateFormat.getDateTimeInstance();
      String titleStr = "C3P0 Status - " + df.format(new Date());

      DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = fact.newDocumentBuilder();
      Document doc = db.newDocument();

      Element htmlElem = doc.createElement("html");
      Element headElem = doc.createElement("head");

      Element titleElem = doc.createElement("title");
      titleElem.appendChild(doc.createTextNode(titleStr));

      Element bodyElem = doc.createElement("body");

      Element h1Elem = doc.createElement("h1");
      h1Elem.appendChild(doc.createTextNode(titleStr));

      Element h3Elem = doc.createElement("h3");
      h3Elem.appendChild(doc.createTextNode("PooledDataSources"));

      Element pdsDlElem = doc.createElement("dl");
      pdsDlElem.setAttribute("class", "PooledDataSources");
      for (Iterator ii = C3P0Registry.getPooledDataSources().iterator(); ii.hasNext(); ) {
        PooledDataSource pds = (PooledDataSource) ii.next();
        StatusReporter sr = findStatusReporter(pds, doc);
        pdsDlElem.appendChild(sr.reportDtElem());
        pdsDlElem.appendChild(sr.reportDdElem());
      }

      headElem.appendChild(titleElem);
      htmlElem.appendChild(headElem);

      bodyElem.appendChild(h1Elem);
      bodyElem.appendChild(h3Elem);
      bodyElem.appendChild(pdsDlElem);
      htmlElem.appendChild(bodyElem);

      res.setContentType("application/xhtml+xml");

      TransformerFactory tf = TransformerFactory.newInstance();
      Transformer transformer = tf.newTransformer();
      Source src = new DOMSource(doc);
      Result result = new StreamResult(res.getOutputStream());
      transformer.transform(src, result);
    } catch (IOException e) {
      throw e;
    } catch (Exception e) {
      throw new ServletException(e);
    }
  }
  /**
   * 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);
      }
    }
  }
  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");
      }
    }
  }
Esempio n. 9
0
  /**
   * Send given content string as the HTTP response.
   *
   * @param contents the string to return as the HTTP response.
   * @param res the HttpServletResponse
   * @throws IOException if an I/O error occurs while writing the response.
   */
  public static void returnString(String contents, HttpServletResponse res) throws IOException {

    try {
      ServletOutputStream out = res.getOutputStream();
      IO.copy(new ByteArrayInputStream(contents.getBytes()), out);
      log.info(
          UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_OK, contents.length()));
    } catch (IOException e) {
      log.error(" IOException sending string: ", e);
      log.info(UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_NOT_FOUND, 0));
      res.sendError(HttpServletResponse.SC_NOT_FOUND, "Problem sending string: " + e.getMessage());
    }
  }
Esempio n. 10
0
  void doGiveHint(HanabiGame game, HttpServletRequest req, HttpServletResponse resp)
      throws IOException, ServletException, HanabiException {
    String target = req.getParameter("target");
    String hint = req.getParameter("hint");

    game.giveHint(target, hint);

    JsonGenerator out = new JsonFactory().createJsonGenerator(resp.getOutputStream());
    out.writeStartObject();
    out.writeStringField("message", "hint given; " + game.hintsLeft + " hints left");
    out.writeEndObject();
    out.close();
  }
Esempio n. 11
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();
  }
Esempio n. 12
0
  /**
   * Sets a status and sends an info message.
   *
   * @param code status code
   * @param message info message
   * @param error treat as error (use web server standard output)
   * @throws IOException I/O exception
   */
  public void status(final int code, final String message, final boolean error) throws IOException {
    try {
      log(message, code);
      res.resetBuffer();
      if (code == SC_UNAUTHORIZED) res.setHeader(WWW_AUTHENTICATE, BASIC);

      if (error && code >= SC_BAD_REQUEST) {
        res.sendError(code, message);
      } else {
        res.setStatus(code);
        if (message != null) res.getOutputStream().write(token(message));
      }
    } catch (final IllegalStateException ex) {
      log(Util.message(ex), SC_INTERNAL_SERVER_ERROR);
    }
  }
  /** {@inheritDoc} */
  @Override
  public void handle(String target, Request req, HttpServletRequest srvReq, HttpServletResponse res)
      throws IOException, ServletException {
    if (log.isDebugEnabled())
      log.debug("Handling request [target=" + target + ", req=" + req + ", srvReq=" + srvReq + ']');

    if (target.startsWith("/gridgain")) {
      processRequest(target, srvReq, res);

      req.setHandled(true);
    } else if (target.startsWith("/favicon.ico")) {
      if (favicon == null) {
        res.setStatus(HttpServletResponse.SC_NOT_FOUND);

        req.setHandled(true);

        return;
      }

      res.setStatus(HttpServletResponse.SC_OK);

      res.setContentType("image/x-icon");

      res.getOutputStream().write(favicon);
      res.getOutputStream().flush();

      req.setHandled(true);
    } else {
      if (dfltPage == null) {
        res.setStatus(HttpServletResponse.SC_NOT_FOUND);

        req.setHandled(true);

        return;
      }

      res.setStatus(HttpServletResponse.SC_OK);

      res.setContentType("text/html");

      res.getWriter().write(dfltPage);
      res.getWriter().flush();

      req.setHandled(true);
    }
  }
Esempio n. 14
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) {
     }
   }
 }
  /**
   * Return the byte output stream for this response. This is either the original stream or a
   * buffered stream.
   *
   * @exception IllegalStateException Thrown when character stream has been already initialized
   *     ({@link #getWriter()}).
   */
  public ServletOutputStream getOutputStream() throws IOException {
    if (writer != null) {
      throw new IllegalStateException(
          "Character stream has been already initialized. Use streams consequently.");
    }

    if (stream != null) {
      return stream;
    }

    if (passthrough) {
      stream = origResponse.getOutputStream();
    } else {
      stream = new DeferredOutputStream();
    }

    return stream;
  }
Esempio n. 16
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");
    }
  }
  /**
   * 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);
          }
        }
      }
    }
  }
  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);
    }
  }
Esempio n. 19
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) {
      }
    }
  }
Esempio n. 20
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());
    }
  }
  /** We override this method to detect XML data streams. */
  public void setContentType(String contentType) {
    // Check if XSLT processing has been suppressed for this request.
    final boolean processingSuppressed = processingSuppressed(origRequest);

    if (processingSuppressed) {
      // Processing is suppressed.
      log.debug("XSLT processing disabled for the request.");
    }

    if (!processingSuppressed
        && (contentType.startsWith("text/xml") || contentType.startsWith("application/xml"))) {
      /*
       * We have an XML data stream. Set the real response to proper content type.
       * TODO: Should we make the encoding a configurable setting?
       */
      origResponse.setContentType("text/html; charset=UTF-8");
    } else {
      /*
       * The input is something we won't process anyway, so simply passthrough all
       * data directly to the output stream.
       */
      if (!processingSuppressed) {
        log.info(
            "Content type is not text/xml or application/xml (" + contentType + "), passthrough.");
      }

      origResponse.setContentType(contentType);
      passthrough = true;

      // If the output stream is already initialized, passthrough everything.
      if (stream != null && stream instanceof DeferredOutputStream) {
        try {
          ((DeferredOutputStream) stream).passthrough(origResponse.getOutputStream());
        } catch (IOException e) {
          ((DeferredOutputStream) stream).setExceptionOnNext(e);
        }
      }
    }
  }
Esempio n. 22
0
  public void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws IOException, ServletException {
    boolean isMultipart = FileUpload.isMultipartContent(req);
    Hashtable dv = new Hashtable();
    String user = null;
    String password = null;
    String sql = null;
    String dfo = null;
    String enc = null;
    if (isMultipart) {

      ServletFileUpload upload = new ServletFileUpload();

      upload.setSizeMax(mU);
      try {
        FileItemIterator iter = upload.getItemIterator(req);
        // List<FileItem> items = upload.parseRequest(req);

        while (iter.hasNext()) {
          FileItemStream item = iter.next();
          // for (int ct = 0;ct < items.size();ct++){

          //         FileItem item = (FileItem)items.get(ct);

          String name = item.getName();
          // (name + " jiql UREEAD 1aay " + item.isFormField() + ":" + name.equals("directValues"));

          InputStream stream = item.openStream();
          // InputStream stream = item.getInputStream();

          //// (name + " jiql UREEAD 1 " + stream.available());
          // byte[] b = StreamUtil.readBytes(stream);

          if (name.equals("directValues")) {
            // (stream.available() + " jiql UREEAD " );

            // ByteArrayInputStream bout = new ByteArrayInputStream(b);
            ObjectInputStream dout = new ObjectInputStream(stream);

            // ObjectInputStream dout = new ObjectInputStream(bout);
            dv = (Hashtable) dout.readObject();
          }
        }

      } catch (Exception e) {
        tools.util.LogMgr.err("JS.readDV " + e.toString());
        e.printStackTrace();
      }
      // ("$$$ DV " + dv);
      Hashtable pars = (Hashtable) dv.get("parameters");
      if (pars != null) {
        Enumeration en = pars.keys();
        while (en.hasMoreElements()) {
          String n = en.nextElement().toString();
          // ("PARSMS " + n);
          if (n.equals("query")) sql = pars.get(n).toString();
          else if (n.equals("password")) password = pars.get(n).toString();
          else if (n.equals("user")) user = pars.get(n).toString();
          else if (n.equals("date.format")) dfo = pars.get(n).toString();
          else if (n.equals("encoding")) enc = pars.get(n).toString();
        }
      }
    }

    if (user == null) user = req.getParameter("user");
    if (password == null) password = req.getParameter("password");
    if (!StringUtil.isRealString(user) || !StringUtil.isRealString(password)) {
      resp.sendError(403, "Invalid User or Password");
      return;
    }

    if (!StringUtil.isRealString(theUser) || !StringUtil.isRealString(thePassword)) {
      resp.sendError(403, "Invalid User OR Password");
      return;
    }

    Connection Conn = null;
    Hashtable h = new Hashtable();
    h.put("remote", "true");
    try {
      //	NameValuePairs p = new NameValuePairs(ps);
      if (!user.equals(theUser) || !password.equals(thePassword)) {
        resp.sendError(403, "Invalid User OR Invalid Password");
        return;
      }
      // throw new ServletException("Invalid User OR Password");
      if (sql == null) sql = req.getParameter("query");
      // ( "THE SQL " + sql);
      NameValuePairs nvp = new NameValuePairs();
      if (dfo == null) dfo = req.getParameter("date.format");
      if (dfo != null) nvp.put("date.format", dfo);

      if (enc == null) enc = req.getParameter("encoding");
      if (enc != null) nvp.put("encoding", enc);

      Conn = get(nvp);

      org.jiql.jdbc.Statement Stmt = (org.jiql.jdbc.Statement) Conn.createStatement();
      Stmt.setDirectValues(dv);

      Stmt.execute(sql);
      org.jiql.jdbc.ResultSet res = (org.jiql.jdbc.ResultSet) Stmt.getResultSet();

      if (res != null) {

        if (res.getResults() != null) h.put("results", res.getResults());
        if (res.getSQLParser() != null) h.put("sqlparser", res.getSQLParser());
      } else h.put("sqlparser", Stmt.getSQLParser());

      // h.put("remote","true");
      resp.setContentType("binary/object");
      // if (enc != null)
      //	resp.setCharacterEncoding(enc);
      OutputStream fos = resp.getOutputStream();
      ObjectOutputStream oos = new ObjectOutputStream(fos);
      oos.writeObject(h);
      // resp.getWriter(). ("result" + h);

    } catch (Exception ex) {
      org.jiql.util.JGUtil.olog(ex);
      ex.printStackTrace();
      tools.util.LogMgr.err("JIQLServlet " + ex.toString());
      JGException je = null;
      if (ex instanceof JGException) je = (JGException) ex;
      else je = new JGException(ex.toString());

      h.put("error", je);

      resp.setContentType("binary/object");
      OutputStream fos = resp.getOutputStream();
      ObjectOutputStream oos = new ObjectOutputStream(fos);
      oos.writeObject(h);

      // throw new ServletException(ex.toString());
    } finally {
      if (Conn != null)
        try {

          Conn.close();
        } catch (Exception ex) {
          ex.printStackTrace();
        }
    }
  }
Esempio n. 23
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType(XML_RESPONSE_HEADER); // Talkback happens in XML form.
    response.setCharacterEncoding("UTF-8"); // Unicode++
    request.setCharacterEncoding("UTF-8");

    PrintWriter out = null; // The talkback buffer.

    // handle startrecord
    Integer startRecord = 0;

    if (!(request.getParameter("startRecord") == null)) {
      try {
        startRecord = Integer.parseInt(request.getParameter("startRecord")) - 1;
      } catch (NumberFormatException e) {
        startRecord = 0;
      }
    }

    // maximumrecords
    Integer maximumRecords = Integer.parseInt(this.config.getProperty("default_maximumRecords"));
    if (!(request.getParameter("maximumRecords") == null)) {
      maximumRecords = Integer.parseInt(request.getParameter("maximumRecords"));
    }

    // operation
    String operation = request.getParameter("operation");

    // x_collection
    String x_collection = request.getParameter("x-collection");
    if (x_collection == null) x_collection = this.config.getProperty("default_x_collection");
    if (x_collection == null) operation = null;

    // sortkeys
    String sortKeys = request.getParameter("sortKeys");

    // sortorder
    String sortOrder = request.getParameter("sortOrder");

    // recordschema
    String recordSchema = request.getParameter("recordSchema");
    if (recordSchema == null) recordSchema = "dc";

    if (recordSchema.equalsIgnoreCase("dcx")) {
      recordSchema = "dcx";
    }

    if (recordSchema.equalsIgnoreCase("solr")) {
      recordSchema = "solr";
    }

    // query request
    String query = request.getParameter("query");
    String q = request.getParameter("q");

    // who is requestor ?
    String remote_ip = request.getHeader("X-FORWARDED-FOR");

    if (remote_ip == null) {
      remote_ip = request.getRemoteAddr().trim();
    } else {
      remote_ip = request.getHeader("X-FORWARDED-FOR");
    }

    // handle debug
    Boolean debug = Boolean.parseBoolean(request.getParameter("debug"));
    if (!debug) {
      out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF8"), true);
    }

    // handle query
    if ((query == null) && (q != null)) {
      query = q;
    } else {
      if ((query != null) && (q == null)) {
        q = query;
      } else {
        operation = null;
      }
    }

    // handle operation
    if (operation == null) {
      if (query != null) {
        operation = "searchRetrieve";
      } else {
        operation = "explain";
      }
    }

    //  searchRetrieve
    if (operation.equalsIgnoreCase("searchRetrieve")) {
      if (query == null) {
        operation = "explain";
        log.debug(operation + ":" + query);
      }
    }

    // start talking back.
    String[] sq = {""};
    String solrquery = "";

    // facet

    String facet = null;
    List<FacetField> fct = null;

    if (request.getParameter("facet") != null) {
      facet = request.getParameter("facet");
      log.debug("facet : " + facet);
    }

    if (operation == null) {
      operation = "searchretrieve";
    } else { // explain response
      if (operation.equalsIgnoreCase("explain")) {
        log.debug("operation = explain");
        out.write("<srw:explainResponse xmlns:srw=\"http://www.loc.gov/zing/srw/\">");
        out.write("</srw:explainResponse>");
      } else { // DEBUG routine
        operation = "searchretrieve";

        String triplequery = null;

        if (query.matches(".*?\\[.+?\\].*?")) { // New symantic syntax
          triplequery = symantic_query(query);
          query = query.split("\\[")[0] + " " + triplequery;
          log.fatal(triplequery);

          solrquery = CQLtoLucene.translate(query, log, config);
        } else {
          solrquery = CQLtoLucene.translate(query, log, config);
        }
        log.debug(solrquery);

        if (debug == true) {
          response.setContentType(HTML_RESPONSE_HEADER);
          out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF8"), true);
          out.write("<html><body>\n\n");
          out.write("'" + remote_ip + "'<br>\n");
          out.write("<form action='http://www.kbresearch.nl/kbSRU'>");
          out.write("<input type=text name=q value='" + query + "' size=120>");
          out.write("<input type=hidden name=debug value=True>");
          out.write("<input type=submit>");
          out.write("<table border=1><tr><td>");
          out.write("q</td><td>" + query + "</td></tr><tr>");
          out.write("<td>query out</td><td>" + URLDecoder.decode(solrquery) + "</td></tr>");
          out.write(
              "<tr><td>SOLR_URL</td><td> <a href='"
                  + this.config.getProperty(
                      "collection." + x_collection.toLowerCase() + ".solr_baseurl")
                  + "/?q="
                  + solrquery
                  + "'>"
                  + this.config.getProperty(
                      "collection." + x_collection.toLowerCase() + ".solr_baseurl")
                  + "/select/?q="
                  + solrquery
                  + "</a><br>"
                  + this.config.getProperty("solr_url")
                  + solrquery
                  + "</td></tr>");
          out.write(
              "<b>SOLR_QUERY</b> : <BR> <iframe width=900 height=400 src='"
                  + this.config.getProperty(
                      "collection." + x_collection.toLowerCase() + ".solr_baseurl")
                  + "/../?q="
                  + solrquery
                  + "'></iframe><BR>");
          out.write(
              "<b>SRU_QUERY</b> : <BR> <a href="
                  + this.config.getProperty("baseurl")
                  + "?q="
                  + query
                  + "'>"
                  + this.config.getProperty("baseurl")
                  + "?q="
                  + query
                  + "</a><br><iframe width=901 height=400 src='http://www.kbresearch.nl/kbSRU/?q="
                  + query
                  + "'></iframe><BR>");
          out.write(
              "<br><b>JSRU_QUERY</b> : <BR><a href='http://jsru.kb.nl/sru/?query="
                  + query
                  + "&x-collection="
                  + x_collection
                  + "'>http://jsru.kb.nl/sru/?query="
                  + query
                  + "&x-collection=GGC</a><br><iframe width=900 height=400 src='http://jsru.kb.nl/sru/?query="
                  + query
                  + "&x-collection=GGC'></iframe>");

        } else { // XML SearchRetrieve response
          String url =
              this.config.getProperty("collection." + x_collection.toLowerCase() + ".solr_baseurl");
          String buffer = "";
          CommonsHttpSolrServer server = null;
          server = new CommonsHttpSolrServer(url);
          log.fatal("URSING " + url);
          server.setParser(new XMLResponseParser());
          int numfound = 0;
          try {
            SolrQuery do_query = new SolrQuery();
            do_query.setQuery(solrquery);
            do_query.setRows(maximumRecords);
            do_query.setStart(startRecord);

            if ((sortKeys != null) && (sortKeys.length() > 1)) {
              if (sortOrder != null) {
                if (sortOrder.equals("asc")) {
                  do_query.setSortField(sortKeys, SolrQuery.ORDER.asc);
                }
                if (sortOrder.equals("desc")) {
                  do_query.setSortField(sortKeys, SolrQuery.ORDER.desc);
                }
              } else {
                for (String str : sortKeys.trim().split(",")) {
                  str = str.trim();
                  if (str.length() > 1) {
                    if (str.equals("date")) {
                      do_query.setSortField("date_date", SolrQuery.ORDER.desc);
                      log.debug("SORTORDERDEBUG | DATE! " + str + " | ");
                      break;
                    } else {
                      do_query.setSortField(str + "_str", SolrQuery.ORDER.asc);
                      log.debug("SORTORDERDEBUG | " + str + " | ");
                      break;
                    }
                  }
                }
              }
            }

            if (facet != null) {
              if (facet.indexOf(",") > 1) {
                for (String str : facet.split(",")) {
                  if (str.indexOf("date") > 1) {
                    do_query.addFacetField(str);
                  } else {
                    do_query.addFacetField(str);
                  }
                  // do_query.setParam("facet.method", "enum");
                }
                // q.setFacetSort(false);
              } else {
                do_query.addFacetField(facet);
              }
              do_query.setFacet(true);
              do_query.setFacetMinCount(1);
              do_query.setFacetLimit(-1);
            }

            log.fatal(solrquery);

            QueryResponse rsp = null;
            boolean do_err = false;
            boolean do_sugg = false;
            SolrDocumentList sdl = null;
            String diag = "";
            StringBuffer suggest = new StringBuffer("");

            String content = "1";

            SolrQuery spellq = do_query;
            try {
              rsp = server.query(do_query);
            } catch (SolrServerException e) {
              String header = this.SRW_HEADER.replaceAll("\\$numberOfRecords", "0");
              out.write(header);
              diag = this.SRW_DIAG.replaceAll("\\$error", e.getMessage());
              do_err = true;
              rsp = null;
            }

            log.fatal("query done..");
            if (!(do_err)) { // XML dc response

              SolrDocumentList docs = rsp.getResults();
              numfound = (int) docs.getNumFound();
              int count = startRecord;
              String header =
                  this.SRW_HEADER.replaceAll("\\$numberOfRecords", Integer.toString(numfound));
              out.write(header);
              out.write("<srw:records>");

              Iterator<SolrDocument> iter = rsp.getResults().iterator();

              while (iter.hasNext()) {
                count += 1;
                if (recordSchema.equalsIgnoreCase("dc")) {
                  SolrDocument resultDoc = iter.next();
                  content = (String) resultDoc.getFieldValue("id");
                  out.write("<srw:record>");
                  out.write("<srw:recordPacking>xml</srw:recordPacking>");
                  out.write("<srw:recordSchema>info:srw/schema/1/dc-v1.1</srw:recordSchema>");
                  out.write(
                      "<srw:recordData xmlns:srw_dc=\"info:srw/schema/1/dc-v1.1\" xmlns:mods=\"http://www.loc.gov/mods\" xmlns:dcterms=\"http://purl.org/dc/terms/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:dcx=\"http://krait.kb.nl/coop/tel/handbook/telterms.html\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:marcrel=\"http://www.loc.gov/loc.terms/relators/OTH\" xmlns:facets=\"info:srw/extension/4/facets\" >");
                  StringBuffer result = new StringBuffer("");

                  construct_lucene_dc(result, resultDoc);

                  out.write(result.toString());
                  out.write("</srw:recordData>");
                  out.write(
                      "<srw:recordPosition>" + Integer.toString(count) + "</srw:recordPosition>");
                  out.write("</srw:record>");
                }

                if (recordSchema.equalsIgnoreCase("solr")) {
                  SolrDocument resultDoc = iter.next();
                  content = (String) resultDoc.getFieldValue("id");
                  out.write("<srw:record>");
                  out.write("<srw:recordPacking>xml</srw:recordPacking>");
                  out.write("<srw:recordSchema>info:srw/schema/1/solr</srw:recordSchema>");
                  out.write("<srw:recordData xmlns:expand=\"http://www.kbresearch.nl/expand\">");
                  StringBuffer result = new StringBuffer("");
                  construct_lucene_solr(result, resultDoc);
                  out.write(result.toString());

                  out.write("</srw:recordData>");
                  out.write(
                      "<srw:recordPosition>" + Integer.toString(count) + "</srw:recordPosition>");
                  out.write("</srw:record>");
                }

                if (recordSchema.equalsIgnoreCase("dcx")) { // XML dcx response
                  out.write("<srw:record>");
                  out.write("<srw:recordPacking>xml</srw:recordPacking>");
                  out.write("<srw:recordSchema>info:srw/schema/1/dc-v1.1</srw:recordSchema>");
                  out.write(
                      "<srw:recordData><srw_dc:dc xmlns:srw_dc=\"info:srw/schema/1/dc-v1.1\" xmlns:mods=\"http://www.loc.gov/mods\" xmlns:dcterms=\"http://purl.org/dc/terms/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:dcx=\"http://krait.kb.nl/coop/tel/handbook/telterms.html\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:marcrel=\"http://www.loc.gov/marc.relators/\" xmlns:expand=\"http://www.kbresearch.nl/expand\" xmlns:skos=\"http://www.w3.org/2004/02/skos/core#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" >");
                  SolrDocument resultDoc = iter.next();
                  content = (String) resultDoc.getFieldValue("id");

                  String dcx_data =
                      helpers.getOAIdcx(
                          "http://services.kb.nl/mdo/oai?verb=GetRecord&identifier=" + content,
                          log);
                  if (x_collection.equalsIgnoreCase("ggc-thes")) {
                    dcx_data =
                        helpers.getOAIdcx(
                            "http://serviceso.kb.nl/mdo/oai?verb=GetRecord&identifier=" + content,
                            log);
                  }

                  if (!(dcx_data.length() == 0)) {
                    out.write(dcx_data);
                  } else {
                    // Should not do this!!

                    out.write("<srw:record>");
                    out.write("<srw:recordPacking>xml</srw:recordPacking>");
                    out.write("<srw:recordSchema>info:srw/schema/1/dc-v1.1</srw:recordSchema>");
                    out.write(
                        "<srw:recordData xmlns:srw_dc=\"info:srw/schema/1/dc-v1.1\" xmlns:mods=\"http://www.loc.gov/mods\" xmlns:dcterms=\"http://purl.org/dc/terms/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:dcx=\"http://krait.kb.nl/coop/tel/handbook/telterms.html\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:marcrel=\"http://www.loc.gov/loc.terms/relators/OTH\" >");
                    StringBuffer result = new StringBuffer("");

                    construct_lucene_dc(result, resultDoc);

                    out.write(result.toString());
                    out.write("</srw:recordData>");
                    out.write(
                        "<srw:recordPosition>" + Integer.toString(count) + "</srw:recordPosition>");
                    out.write("</srw:record>");
                  }

                  out.write("</srw_dc:dc>");

                  StringBuffer expand_data;
                  boolean expand = false;

                  if (content.startsWith("GGC-THES:AC:")) {
                    String tmp_content = "";
                    tmp_content = content.replaceFirst("GGC-THES:AC:", "");
                    log.fatal("calling get");
                    expand_data =
                        new StringBuffer(
                            helpers.getExpand(
                                "http://www.kbresearch.nl/general/lod_new/get/"
                                    + tmp_content
                                    + "?format=rdf",
                                log));
                    log.fatal("get finini");

                    if (expand_data.toString().length() > 4) {

                      out.write(
                          "<srw_dc:expand xmlns:srw_dc=\"info:srw/schema/1/dc-v1.1\" xmlns:expand=\"http://www.kbresearch.nl/expand\" xmlns:skos=\"http://www.w3.org/2004/02/skos/core#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" >");
                      out.write(expand_data.toString());
                      expand = true;
                    }
                  } else {
                    expand_data =
                        new StringBuffer(
                            helpers.getExpand(
                                "http://www.kbresearch.nl/ANP.cgi?q=" + content, log));
                    if (expand_data.toString().length() > 0) {
                      if (!expand) {
                        out.write(
                            "<srw_dc:expand xmlns:srw_dc=\"info:srw/schema/1/dc-v1.1\" xmlns:expand=\"http://www.kbresearch.nl/expand\" xmlns:skos=\"http://www.w3.org/2004/02/skos/core#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" >");
                        expand = true;
                      }
                      out.write(expand_data.toString());
                    }
                  }
                  if (expand) {
                    out.write("</srw_dc:expand>");
                  }

                  out.write("</srw:recordData>");
                  out.write(
                      "<srw:recordPosition>" + Integer.toString(count) + "</srw:recordPosition>");
                  out.write("</srw:record>");
                }
              }
            }

            if ((do_err) || (numfound == 0)) {
              log.fatal("I haz suggestions");

              try {
                spellq.setParam("spellcheck", true);
                spellq.setQueryType("/spell");
                server = new CommonsHttpSolrServer(url);
                rsp = server.query(spellq);
                sdl = rsp.getResults();
                SpellCheckResponse spell;
                spell = rsp.getSpellCheckResponse();
                List<SpellCheckResponse.Suggestion> suggestions = spell.getSuggestions();
                if (suggestions.isEmpty() == false) {
                  suggest.append("<srw:extraResponseData>");
                  suggest.append("<suggestions>");

                  for (SpellCheckResponse.Suggestion sugg : suggestions) {
                    suggest.append("<suggestionfor>" + sugg.getToken() + "</suggestionfor>");
                    for (String item : sugg.getSuggestions()) {
                      suggest.append("<suggestion>" + item + "</suggestion>");
                    }
                    suggest.append("</suggestions>");
                    suggest.append("</srw:extraResponseData>");
                  }
                  do_sugg = true;
                }
              } catch (Exception e) {
                rsp = null;
                // log.fatal(e.toString());
              }
              ;
            }
            ;

            if (!do_err) {
              if (facet != null) {

                try {
                  fct = rsp.getFacetFields();
                  out.write("<srw:facets>");

                  for (String str : facet.split(",")) {
                    out.write("<srw:facet>");
                    out.write("<srw:facetType>");
                    out.write(str);
                    out.write("</srw:facetType>");

                    for (FacetField f : fct) {
                      log.debug(f.getName());
                      // if (f.getName().equals(str+"_str") || (f.getName().equals(str+"_date")) ) {
                      List<FacetField.Count> facetEnties = f.getValues();
                      for (FacetField.Count fcount : facetEnties) {
                        out.write("<srw:facetValue>");
                        out.write("<srw:valueString>");
                        out.write(helpers.xmlEncode(fcount.getName()));
                        out.write("</srw:valueString>");
                        out.write("<srw:count>");
                        out.write(Double.toString(fcount.getCount()));
                        out.write("</srw:count>");
                        out.write("</srw:facetValue>");
                        //   }
                      }
                    }
                    out.write("</srw:facet>");
                  }
                  out.write("</srw:facets>");
                  startRecord += 1;
                } catch (Exception e) {
                }

                // log.fatal(e.toString()); }
              }
            } else {
              out.write(diag);
            }
            out.write("</srw:records>"); // SearchRetrieve response footer
            String footer = this.SRW_FOOTER.replaceAll("\\$query", helpers.xmlEncode(query));
            footer = footer.replaceAll("\\$startRecord", (startRecord).toString());
            footer = footer.replaceAll("\\$maximumRecords", maximumRecords.toString());
            footer = footer.replaceAll("\\$recordSchema", recordSchema);
            if (do_sugg) {
              out.write(suggest.toString());
            }
            out.write(footer);
          } catch (MalformedURLException e) {
            out.write(e.getMessage());
          } catch (IOException e) {
            out.write("TO ERR is Human");
          }
        }
      }
    }
    out.close();
  }
  public void doProcess(HttpServletRequest req, HttpServletResponse res, boolean isPost) {
    StringBuffer bodyContent = null;
    OutputStream out = null;
    PrintWriter writer = null;
    String serviceKey = null;

    try {
      BufferedReader in = req.getReader();
      String line = null;
      while ((line = in.readLine()) != null) {
        if (bodyContent == null) bodyContent = new StringBuffer();
        bodyContent.append(line);
      }
    } catch (Exception e) {
    }
    try {
      if (requireSession) {
        // check to see if there was a session created for this request
        // if not assume it was from another domain and blow up
        // Wrap this to prevent Portlet exeptions
        HttpSession session = req.getSession(false);
        if (session == null) {
          res.setStatus(HttpServletResponse.SC_FORBIDDEN);
          return;
        }
      }
      serviceKey = req.getParameter("id");
      // only to preven regressions - Remove before 1.0
      if (serviceKey == null) serviceKey = req.getParameter("key");
      // check if the services have been loaded or if they need to be reloaded
      if (services == null || configUpdated()) {
        getServices(res);
      }
      String urlString = null;
      String xslURLString = null;
      String userName = null;
      String password = null;
      String format = "json";
      String callback = req.getParameter("callback");
      String urlParams = req.getParameter("urlparams");
      String countString = req.getParameter("count");
      // encode the url to prevent spaces from being passed along
      if (urlParams != null) {
        urlParams = urlParams.replace(' ', '+');
      }

      try {
        if (services.has(serviceKey)) {
          JSONObject service = services.getJSONObject(serviceKey);
          // default to the service default if no url parameters are specified
          if (urlParams == null && service.has("defaultURLParams")) {
            urlParams = service.getString("defaultURLParams");
          }
          String serviceURL = service.getString("url");
          // build the URL
          if (urlParams != null && serviceURL.indexOf("?") == -1) {
            serviceURL += "?";
          } else if (urlParams != null) {
            serviceURL += "&";
          }
          String apikey = "";
          if (service.has("username")) userName = service.getString("username");
          if (service.has("password")) password = service.getString("password");
          if (service.has("apikey")) apikey = service.getString("apikey");
          urlString = serviceURL + apikey;
          if (urlParams != null) urlString += "&" + urlParams;
          if (service.has("xslStyleSheet")) {
            xslURLString = service.getString("xslStyleSheet");
          }
        }
        // code for passing the url directly through instead of using configuration file
        else if (req.getParameter("url") != null) {
          String serviceURL = req.getParameter("url");
          // build the URL
          if (urlParams != null && serviceURL.indexOf("?") == -1) {
            serviceURL += "?";
          } else if (urlParams != null) {
            serviceURL += "&";
          }
          urlString = serviceURL;
          if (urlParams != null) urlString += urlParams;
        } else {
          writer = res.getWriter();
          if (serviceKey == null)
            writer.write("XmlHttpProxyServlet Error: id parameter specifying serivce required.");
          else
            writer.write(
                "XmlHttpProxyServlet Error : service for id '" + serviceKey + "' not  found.");
          writer.flush();
          return;
        }
      } catch (Exception ex) {
        getLogger().severe("XmlHttpProxyServlet Error loading service: " + ex);
      }

      Map paramsMap = new HashMap();
      paramsMap.put("format", format);
      // do not allow for xdomain unless the context level setting is enabled.
      if (callback != null && allowXDomain) {
        paramsMap.put("callback", callback);
      }
      if (countString != null) {
        paramsMap.put("count", countString);
      }

      InputStream xslInputStream = null;

      if (urlString == null) {
        writer = res.getWriter();
        writer.write(
            "XmlHttpProxyServlet parameters:  id[Required] urlparams[Optional] format[Optional] callback[Optional]");
        writer.flush();
        return;
      }
      // default to JSON
      res.setContentType(responseContentType);
      out = res.getOutputStream();
      // get the stream for the xsl stylesheet
      if (xslURLString != null) {
        // check the web root for the resource
        URL xslURL = null;
        xslURL = ctx.getResource(resourcesDir + "xsl/" + xslURLString);
        // if not in the web root check the classpath
        if (xslURL == null) {
          xslURL =
              XmlHttpProxyServlet.class.getResource(classpathResourcesDir + "xsl/" + xslURLString);
        }
        if (xslURL != null) {
          xslInputStream = xslURL.openStream();
        } else {
          String message =
              "Could not locate the XSL stylesheet provided for service id "
                  + serviceKey
                  + ". Please check the XMLHttpProxy configuration.";
          getLogger().severe(message);
          try {
            out.write(message.getBytes());
            out.flush();
            return;
          } catch (java.io.IOException iox) {
          }
        }
      }
      if (!isPost) {
        xhp.doGet(urlString, out, xslInputStream, paramsMap, userName, password);
      } else {
        if (bodyContent == null)
          getLogger()
              .info(
                  "XmlHttpProxyServlet attempting to post to url "
                      + urlString
                      + " with no body content");
        xhp.doPost(
            urlString,
            out,
            xslInputStream,
            paramsMap,
            bodyContent.toString(),
            req.getContentType(),
            userName,
            password);
      }
    } catch (Exception iox) {
      iox.printStackTrace();
      getLogger().severe("XmlHttpProxyServlet: caught " + iox);
      try {
        writer = res.getWriter();
        writer.write(iox.toString());
        writer.flush();
      } catch (java.io.IOException ix) {
        ix.printStackTrace();
      }
      return;
    } finally {
      try {
        if (out != null) out.close();
        if (writer != null) writer.close();
      } catch (java.io.IOException iox) {
      }
    }
  }
  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    // create the workbook, its worksheet, and its title row
    Workbook workbook = new HSSFWorkbook();
    Sheet sheet = workbook.createSheet("User table");
    Row row = sheet.createRow(0);
    row.createCell(0).setCellValue("The User table");

    // create the header row
    row = sheet.createRow(2);
    row.createCell(0).setCellValue("UserID");
    row.createCell(1).setCellValue("LastName");
    row.createCell(2).setCellValue("FirstName");
    row.createCell(3).setCellValue("Email");

    try {
      // read database rows
      ConnectionPool pool = ConnectionPool.getInstance();
      Connection connection = pool.getConnection();
      Statement statement = connection.createStatement();
      String query = "SELECT * FROM User ORDER BY UserID";
      ResultSet results = statement.executeQuery(query);

      // create spreadsheet rows
      int i = 3;
      while (results.next()) {
        row = sheet.createRow(i);
        row.createCell(0).setCellValue(results.getInt("UserID"));
        row.createCell(1).setCellValue(results.getString("LastName"));
        row.createCell(2).setCellValue(results.getString("FirstName"));
        row.createCell(3).setCellValue(results.getString("Email"));
        i++;
      }
      results.close();
      statement.close();
      connection.close();
    } catch (SQLException e) {
      this.log(e.toString());
    }

    // set response object headers
    response.setHeader("content-disposition", "attachment; filename=users.xls");
    response.setHeader("cache-control", "no-cache");

    // get the output stream
    String encodingString = request.getHeader("accept-encoding");
    OutputStream out;
    if (encodingString != null && encodingString.contains("gzip")) {
      out = new GZIPOutputStream(response.getOutputStream());
      response.setHeader("content-encoding", "gzip");
      // System.out.println("User table encoded with gzip");
    } else {
      out = response.getOutputStream();
      // System.out.println("User table not encoded with gzip");
    }

    // send the workbook to the browser
    workbook.write(out);
    out.close();
  }
Esempio n. 26
0
  public void _jspService(HttpServletRequest request, HttpServletResponse response)
      throws java.io.IOException, ServletException {

    PageContext pageContext = null;
    HttpSession session = null;
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;
    PageContext _jspx_page_context = null;

    try {
      response.setContentType("image/jpeg");
      pageContext =
          _jspxFactory.getPageContext(
              this, request, response, "/myhtml/errorpage/erroe.jsp", true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write("\r\n");
      out.write("\r\n");
      out.write('\r');
      out.write('\n');

      // 设置页面不缓存
      response.setHeader("Pragma", "No-cache");
      response.setHeader("Cache-Control", "no-cache");
      response.setDateHeader("Expires", 0);

      //   在内存中创建图象
      int width = 60, height = 20;
      BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

      //   获取图形上下文
      Graphics g = image.getGraphics();

      // 生成随机类
      Random random = new Random();

      //   设定背景色
      g.setColor(getRandColor(200, 250));
      g.fillRect(0, 0, width, height);

      // 设定字体
      g.setFont(new Font("Times   New   Roman", Font.PLAIN, 18));

      // 画边框
      // g.setColor(new   Color());
      // g.drawRect(0,0,width-1,height-1);

      //   随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
      g.setColor(getRandColor(160, 200));
      for (int i = 0; i < 155; i++) {
        int x = random.nextInt(width);
        int y = random.nextInt(height);
        int xl = random.nextInt(12);
        int yl = random.nextInt(12);
        g.drawLine(x, y, x + xl, y + yl);
      }

      //   取随机产生的认证码(4位数字)
      String sRand = "";
      for (int i = 0; i < 4; i++) {
        String rand = String.valueOf(random.nextInt(10));
        sRand += rand;
        //   将认证码显示到图象中
        g.setColor(
            new Color(
                20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
        // 调用函数出来的颜色相同,可能是å›
        // ä¸ºç§å­å¤ªæŽ¥è¿‘,所以只能直接生成
        g.drawString(rand, 13 * i + 6, 16);
      }

      //   将认证码存入SESSION
      session.setAttribute("rand", sRand);

      //   图象生效
      g.dispose();

      //   输出图象到页面
      ImageIO.write(image, "JPEG", response.getOutputStream());
      out.clear();
      out = pageContext.pushBody();

    } catch (Throwable t) {
      if (!(t instanceof SkipPageException)) {
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          try {
            out.clearBuffer();
          } catch (java.io.IOException e) {
          }
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
        else log(t.getMessage(), t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
  /**
   * 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);
      }
    }
  }
Esempio n. 28
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());
    }
  }
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    try {
      Locales.setCurrent(request);
      if (Users.getCurrent() == null) { // for a bug in websphere portal 5.1 with Domino LDAP
        Users.setCurrent((String) request.getSession().getAttribute("xava.user"));
      }
      request.getParameter("application"); // for a bug in websphere 5.1
      request.getParameter("module"); // for a bug in websphere 5.1
      Tab tab = (Tab) request.getSession().getAttribute("xava_reportTab");
      int[] selectedRowsNumber =
          (int[]) request.getSession().getAttribute("xava_selectedRowsReportTab");
      Map[] selectedKeys = (Map[]) request.getSession().getAttribute("xava_selectedKeysReportTab");
      int[] selectedRows = getSelectedRows(selectedRowsNumber, selectedKeys, tab);
      request.getSession().removeAttribute("xava_selectedRowsReportTab");
      Integer columnCountLimit =
          (Integer) request.getSession().getAttribute("xava_columnCountLimitReportTab");
      request.getSession().removeAttribute("xava_columnCountLimitReportTab");

      setDefaultSchema(request);
      String user = (String) request.getSession().getAttribute("xava_user");
      request.getSession().removeAttribute("xava_user");
      Users.setCurrent(user);
      String uri = request.getRequestURI();
      if (uri.endsWith(".pdf")) {
        InputStream is;
        JRDataSource ds;
        Map parameters = new HashMap();
        synchronized (tab) {
          tab.setRequest(request);
          parameters.put("Title", tab.getTitle());
          parameters.put("Organization", getOrganization());
          parameters.put("Date", getCurrentDate());
          for (String totalProperty : tab.getTotalPropertiesNames()) {
            parameters.put(totalProperty + "__TOTAL__", getTotal(request, tab, totalProperty));
          }
          TableModel tableModel = getTableModel(request, tab, selectedRows, false, true, null);
          tableModel.getValueAt(0, 0);
          if (tableModel.getRowCount() == 0) {
            generateNoRowsPage(response);
            return;
          }
          is = getReport(request, response, tab, tableModel, columnCountLimit);
          ds = new JRTableModelDataSource(tableModel);
        }
        JasperPrint jprint = JasperFillManager.fillReport(is, parameters, ds);
        response.setContentType("application/pdf");
        response.setHeader(
            "Content-Disposition", "inline; filename=\"" + getFileName(tab) + ".pdf\"");
        JasperExportManager.exportReportToPdfStream(jprint, response.getOutputStream());
      } else if (uri.endsWith(".csv")) {
        String csvEncoding = XavaPreferences.getInstance().getCSVEncoding();
        if (!Is.emptyString(csvEncoding)) {
          response.setCharacterEncoding(csvEncoding);
        }
        response.setContentType("text/x-csv");
        response.setHeader(
            "Content-Disposition", "inline; filename=\"" + getFileName(tab) + ".csv\"");
        synchronized (tab) {
          tab.setRequest(request);
          response
              .getWriter()
              .print(
                  TableModels.toCSV(
                      getTableModel(request, tab, selectedRows, true, false, columnCountLimit)));
        }
      } else {
        throw new ServletException(
            XavaResources.getString("report_type_not_supported", "", ".pdf .csv"));
      }
    } catch (Exception ex) {
      log.error(ex.getMessage(), ex);
      throw new ServletException(XavaResources.getString("report_error"));
    } finally {
      request.getSession().removeAttribute("xava_reportTab");
    }
  }
Esempio n. 30
0
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException {

    String retval = "<html> <H4>";

    try {
      // Create a message factory.
      MessageFactory mf = MessageFactory.newInstance();

      // Create a message from the message factory.
      SOAPMessage msg = mf.createMessage();

      // Message creation takes care of creating the SOAPPart - a
      // required part of the message as per the SOAP 1.1
      // specification.
      SOAPPart sp = msg.getSOAPPart();

      // Retrieve the envelope from the soap part to start building
      // the soap message.
      SOAPEnvelope envelope = sp.getEnvelope();

      // Create a soap header from the envelope.
      SOAPHeader hdr = envelope.getHeader();

      // Create a soap body from the envelope.
      SOAPBody bdy = envelope.getBody();

      // Add a soap body element to the soap body
      SOAPBodyElement gltp =
          bdy.addBodyElement(
              envelope.createName("GetLastTradePrice", "ztrade", "http://wombat.ztrade.com"));

      gltp.addChildElement(envelope.createName("symbol", "ztrade", "http://wombat.ztrade.com"))
          .addTextNode("SUNW");

      StringBuffer urlSB = new StringBuffer();
      urlSB.append(req.getScheme()).append("://").append(req.getServerName());
      urlSB.append(":").append(req.getServerPort()).append(req.getContextPath());
      String reqBase = urlSB.toString();

      if (data == null) {
        data = reqBase + "/index.html";
      }

      // Want to set an attachment from the following url.
      // Get context
      URL url = new URL(data);

      AttachmentPart ap = msg.createAttachmentPart(new DataHandler(url));

      ap.setContentType("text/html");

      // Add the attachment part to the message.
      msg.addAttachmentPart(ap);

      // Create an endpoint for the recipient of the message.
      if (to == null) {
        to = reqBase + "/receiver";
      }

      URL urlEndpoint = new URL(to);

      System.err.println("Sending message to URL: " + urlEndpoint);
      System.err.println("Sent message is logged in \"sent.msg\"");

      retval += " Sent message (check \"sent.msg\") and ";

      FileOutputStream sentFile = new FileOutputStream("sent.msg");
      msg.writeTo(sentFile);
      sentFile.close();

      // Send the message to the provider using the connection.
      SOAPMessage reply = con.call(msg, urlEndpoint);

      if (reply != null) {
        FileOutputStream replyFile = new FileOutputStream("reply.msg");
        reply.writeTo(replyFile);
        replyFile.close();
        System.err.println("Reply logged in \"reply.msg\"");
        retval += " received reply (check \"reply.msg\").</H4> </html>";

      } else {
        System.err.println("No reply");
        retval += " no reply was received. </H4> </html>";
      }

    } catch (Throwable e) {
      e.printStackTrace();
      logger.severe("Error in constructing or sending message " + e.getMessage());
      retval += " There was an error " + "in constructing or sending message. </H4> </html>";
    }

    try {
      OutputStream os = resp.getOutputStream();
      os.write(retval.getBytes());
      os.flush();
      os.close();
    } catch (IOException e) {
      e.printStackTrace();
      logger.severe("Error in outputting servlet response " + e.getMessage());
    }
  }