예제 #1
0
  /**
   * 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.");
    }
  }
예제 #2
0
  /**
   * Called by the server (via the <code>service</code> method) to allow a servlet to handle a TRACE
   * request.
   *
   * <p>A TRACE returns the headers sent with the TRACE request to the client, so that they can be
   * used in debugging. There's no need to override this method.
   *
   * @param req the {@link HttpServletRequest} object that contains the request the client made of
   *     the servlet
   * @param resp the {@link HttpServletResponse} object that contains the response the servlet
   *     returns to the client
   * @exception IOException if an input or output error occurs while the servlet is handling the
   *     TRACE request
   * @exception ServletException if the request for the TRACE cannot be handled
   */
  protected void doTrace(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    int responseLength;

    String CRLF = "\r\n";
    StringBuilder buffer =
        new StringBuilder("TRACE ")
            .append(req.getRequestURI())
            .append(" ")
            .append(req.getProtocol());

    Enumeration<String> reqHeaderEnum = req.getHeaderNames();

    while (reqHeaderEnum.hasMoreElements()) {
      String headerName = reqHeaderEnum.nextElement();
      buffer.append(CRLF).append(headerName).append(": ").append(req.getHeader(headerName));
    }

    buffer.append(CRLF);

    responseLength = buffer.length();

    resp.setContentType("message/http");
    resp.setContentLength(responseLength);
    ServletOutputStream out = resp.getOutputStream();
    out.print(buffer.toString());
    out.close();
    return;
  }
예제 #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();
    }
  }
예제 #4
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));
 }
예제 #5
0
 public GZIPResponseStream(HttpServletResponse response) throws IOException {
   super();
   closed = false;
   this.response = response;
   this.output = response.getOutputStream();
   baos = new ByteArrayOutputStream();
   gzipstream = new GZIPOutputStream(baos);
 }
예제 #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);
      }
    }
  }
예제 #8
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");
      }
    }
  }
예제 #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());
    }
  }
예제 #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();
  }
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    BarCodeBuilder b = new BarCodeBuilder();
    b.setSymbologyType(Symbology.Code128);
    b.setCodeText("12345678");
    BufferedImage image = b.getBarCodeImage();

    response.setContentType("image/png");
    OutputStream outputStream = response.getOutputStream();
    ImageIO.write(image, "png", outputStream);
    outputStream.close();
  }
예제 #12
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();
  }
 /**
  * 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();
 }
예제 #14
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);
    }
  }
예제 #15
0
  public void serializeHistoryCursor(
      Collection<TrackHistory> historyCursor, HttpServletResponse httpServletResponse) {
    try {
      final ServletOutputStream httpOutputStream = httpServletResponse.getOutputStream();
      final BufferedWriter outputStream =
          new BufferedWriter(new OutputStreamWriter(httpOutputStream));
      outputStream.write("{");
      outputStream.write("\"count\":");
      outputStream.write("" + historyCursor.size());

      if (historyCursor.size() > 0) {
        Gson gson = new Gson();

        outputStream.write(",");
        outputStream.write("\"tracks\":[");

        for (Iterator<TrackHistory> iterator = historyCursor.iterator(); iterator.hasNext(); ) {
          TrackHistory next = iterator.next();
          outputStream.write(gson.toJson(toWebTrack(next)));
          if (iterator.hasNext()) {
            outputStream.write(",");
          }
          outputStream.flush();
        }

        /*
                        while (historyCursor.hasNext())
                        {
                            outputStream.write(gson.toJson(toWebTrack(historyCursor.next())));
                            if (historyCursor.hasNext())
                            {
                                outputStream.write(",");
                            }
                            outputStream.flush();
                        }
        */
        outputStream.write("]");
      }
      outputStream.write("}");
      outputStream.flush();
      outputStream.close();
      httpOutputStream.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
예제 #16
0
  /** {@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);
    }
  }
예제 #17
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) {
     }
   }
 }
예제 #18
0
  /**
   * 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;
  }
예제 #19
0
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    resp.setContentType("text/html");

    String username = req.getUserPrincipal().getName();

    String token = ChannelServiceFactory.getChannelService().createChannel(username);
    String tokenized =
        CharStreams.toString(
                new InputStreamReader(getServletContext().getResourceAsStream(PATH), ENCODING))
            .replace("TOKEN", token);

    DatastoreService store = DatastoreServiceFactory.getDatastoreService();
    Entity player = ensurePlayerExists(username, store);
    Entity map = ensureMapExists(player, store);

    OutputStream out = resp.getOutputStream();
    out.write(ENCODING.encode(tokenized).array());
    out.flush();
  }
예제 #20
0
파일: down.java 프로젝트: RainerJava/erp-6
  public void download(HttpServletResponse response, String filename) throws IOException {
    StringTokenizer tokenTO = new StringTokenizer(filename, "\\");
    int j = 0;
    String[] filepath1 = new String[10];
    while (tokenTO.hasMoreTokens()) {
      filepath1[j] = tokenTO.nextToken();
      j++;
    }
    String filepath = "";
    for (int m = 0; m < j - 1; m++) {
      filepath = filepath + filepath1[m] + "\\";
    }
    filepath = filepath + filepath1[j - 1];
    File down_file = new java.io.File(filepath);
    long l = down_file.length(); // 文件长度
    InputStream in = new FileInputStream(down_file);

    if (in != null) {
      try {
        String fs = down_file.getName();
        response.reset();
        response.setContentType(null); //
        String s = "attachment; filename=" + fs; //
        response.setHeader("Content-Disposition", s); // 以上输出文件元信息

        OutputStream output = null;
        FileInputStream fis = null;

        output = response.getOutputStream();
        fis = new FileInputStream(filepath);
        response.setContentLength((int) l);
        byte[] b = new byte[2048];
        int i = 0;
        while ((i = fis.read(b)) > 0) {
          output.write(b, 0, i);
        }
        output.flush();
        in.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
예제 #21
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");
    }
  }
예제 #22
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);
          }
        }
      }
    }
  }
예제 #23
0
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    String diagramUXF = req.getParameter("diagramUXF");

    // Get an output stream suitable for writing binary
    // data to the client.
    ServletOutputStream respOutputStream = resp.getOutputStream();

    // Umlet should behave as if running from command line, e.g.
    // as if being called by
    // "-action=convert -format=svg -filename=inputfile.uxf"
    Program.RUNTIME_TYPE = RuntimeType.BATCH;

    // OutputHandler performs conversion from UXF to SVG and
    // requires DiagramHandler object for representing a UXF
    // document, which requires that the UXF is accessible
    // through a File interface.
    //
    // Create a temporary file and write UXF to it.

    // Take hash of UXF for good enough uniqueness.
    String tempSuffix = new Integer(diagramUXF.hashCode()).toString();
    File temp = File.createTempFile(tempSuffix, ".tmp");
    FileWriter tempWriter = new FileWriter(temp);
    tempWriter.write(diagramUXF);
    tempWriter.close();

    DiagramHandler diagramHandler = new DiagramHandler(temp);

    // Convert to SVG and write out binary data to client.
    try {
      OutputHandler.createToStream("svg", respOutputStream, diagramHandler);
    } catch (Exception e) {
      throw new ServletException(e);
    }

    // Flush to commit the response.
    respOutputStream.flush();
  }
  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);
    }
  }
예제 #25
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) {
      }
    }
  }
예제 #26
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());
    }
  }
예제 #27
0
  /** 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);
        }
      }
    }
  }
예제 #28
0
  private void callMethodForParam(HttpServletRequest req, HttpServletResponse resp)
      throws Exception {
    String pinfo = req.getPathInfo();
    int pos = pinfo.indexOf('.');
    String cname = pinfo.substring(1, pos).replace('/', '.');
    String mname = pinfo.substring(pos + 1);

    int argc = 0;
    while (req.getParameter("a" + argc) != null) argc++;

    Class clazz = Class.forName(cname);
    Method method = null;
    Method[] methods = clazz.getMethods();
    for (int i = 0; i < methods.length; i++) {
      if (methods[i].getParameterTypes().length == argc && mname.equals(methods[i].getName())) {
        method = methods[i];
      }
    }
    if (method == null) {
      throw new RuntimeException("Not found method " + mname + "(" + argc + "args)");
    }

    Object[] args = new Object[argc];
    Class[] types = method.getParameterTypes();
    if (types != null) {
      for (int i = 0; i < types.length; i++) {
        args[i] = toArg(types[i], req.getParameter("a" + i));
      }
    }

    Object result = method.invoke(null, args);

    resp.setContentType(MIME_JSON);
    OutputStream out = resp.getOutputStream();
    out.write("{\"result\":".getBytes("UTF-8"));
    new JSONSerializer().serialize(result, out);
    out.write("}".getBytes("UTF-8"));
    out.flush();
  }
예제 #29
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();
        }
    }
  }
예제 #30
0
파일: kbSRU.java 프로젝트: STITCHplus/kbSRU
  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();
  }