/**
   * Logs HTTP Request's in a log file suitable for replaying to eXist later Takes a
   * HttpServletRequest or a HttpServletRequestWrapper as an argument for logging.
   *
   * <p>Enabled by descriptor.xml <xquery-app request-replay-log="true">
   *
   * @param request The HttpServletRequest to log. For Simple HTTP POST Requests -
   *     EXistServlet/XQueryServlet - POST parameters (e.g. form data) will only be logged if a
   *     HttpServletRequestWrapper is used instead of HttpServletRequest! POST Uploaded files are
   *     not yet supported! For XML-RPC Requests - RpcServlet - HttpServletRequestWrapper must be
   *     used, otherwise the content of the Request will be lost! For Cocoon Requests -
   */
  public synchronized void doLogRequestInReplayLog(HttpServletRequest request) {
    // Only log if set by the user in descriptor.xml <xquery-app request-replay-log="true">
    if (bufWriteReplayLog == null) {
      return;
    }

    // Log the Request
    try {
      // Store the date and time
      bufWriteReplayLog.write("Date: ");
      SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
      bufWriteReplayLog.write(formatter.format(new Date()));

      bufWriteReplayLog.write(SYSTEM_LINE_SEPARATOR);

      // Store the request string excluding the first line
      String requestAsString = request.toString();
      bufWriteReplayLog.write(
          requestAsString.substring(requestAsString.indexOf(SYSTEM_LINE_SEPARATOR) + 1));

      // End of record indicator
      bufWriteReplayLog.write(SYSTEM_LINE_SEPARATOR);

      // flush the buffer to file
      bufWriteReplayLog.flush();
    } catch (IOException ioe) {
      LOG.warn("Could not write request replay log: " + ioe);
      return;
    }
  }
 public void doPost(HttpServletRequest request, HttpServletResponse response)
     throws IOException, ServletException {
   logger.debug(request.toString());
   try {
     serviceCallService = ServiceFactory.getSerViceCallService();
     serviceCallService.registerServiceCall(request);
     setSuccessMsg(request, RESULT_SC_ADDED);
   } catch (Exception e) {
     setErrorMsg(request, RESULT_UNKNOWN_ERROR);
   }
   doGet(request, response);
 }
  /**
   * Handle a request.
   *
   * @param target The target of the request - either a URI or a name.
   * @param baseRequest The original unwrapped request object.
   * @param request The request either as the {@link Request} object or a wrapper of that request.
   *     The HttpChannel.getCurrentHttpChannel method can be used access the Request object if
   *     required.
   * @param response The response as the Response object or a wrapper of that request. The
   *     HttpChannel.getCurrentHttpChannel() method can be used access the Response object if
   *     required.
   */
  @Override
  public void handle(
      String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    /* since we're not deciding what to do based on the `target`, we're going to do
     * the exact same thing for every page regardless of which path parameter they sent
     * in their HTTP request.
     */

    System.out.println("target: " + target);
    System.out.println("baseRequest:" + baseRequest.toString());
    System.out.println("request: " + request.toString());

    /* this sets the `Content-Type` HEADER in the HTTP response */
    response.setContentType("text/html; charset=utf-8");

    /* this sets the STATUS CODE in the HTTP response */
    response.setStatus(HttpServletResponse.SC_OK);

    /* this adds the text to the BODY of the HTTP response */
    response.getWriter().println("<h1>Hello World</h1>");

    /* I think this means that if we have this handler in a HandlerList, it will stop
     * passing the request to sequential handlers in that list because this one did
     * already handle it.
     */
    baseRequest.setHandled(true);

    /* The `Date` is automatically added as a header because the default `HttpConfiguration`
     * does that. And the default `Server` we created, creates a default `ServerConnector`
     * which creates a default `HttpConnectionFactory`, which creates a default
     * `HttpConfiguration`.
     */

    System.out.println("\nresponse:");
    System.out.println("==============");
    System.out.println(response.toString());
    System.out.println("==============\n");
  }
 @Override
 public String toString() {
   return request != null ? request.toString() : null;
 }
  /*
   * @see org.mortbay.jetty.Handler#handle(java.lang.String, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, int)
   */
  public void handle(
      String target, HttpServletRequest request, HttpServletResponse response, int dispatch)
      throws IOException, ServletException {
    Request base_request =
        (request instanceof Request)
            ? (Request) request
            : HttpConnection.getCurrentConnection().getRequest();

    if (!isStarted()) return;

    if (request.getParameter("continue") != null) {
      Continuation continuation = ContinuationSupport.getContinuation(request, null);
      continuation.suspend(Long.parseLong(request.getParameter("continue")));
    }

    base_request.setHandled(true);
    response.setHeader(HttpHeaders.CONTENT_TYPE, MimeTypes.TEXT_HTML);

    OutputStream out = response.getOutputStream();
    ByteArrayOutputStream buf = new ByteArrayOutputStream(2048);
    Writer writer = new OutputStreamWriter(buf, StringUtil.__ISO_8859_1);
    writer.write("<html><h1>" + label + "</h1>");
    writer.write("<pre>\npathInfo=" + request.getPathInfo() + "\n</pre>\n");
    writer.write("<pre>\ncontentType=" + request.getContentType() + "\n</pre>\n");
    writer.write("<pre>\nencoding=" + request.getCharacterEncoding() + "\n</pre>\n");
    writer.write("<h3>Header:</h3><pre>");
    writer.write(request.toString());
    writer.write("</pre>\n<h3>Parameters:</h3>\n<pre>");
    Enumeration names = request.getParameterNames();
    while (names.hasMoreElements()) {
      String name = names.nextElement().toString();
      String[] values = request.getParameterValues(name);
      if (values == null || values.length == 0) {
        writer.write(name);
        writer.write("=\n");
      } else if (values.length == 1) {
        writer.write(name);
        writer.write("=");
        writer.write(values[0]);
        writer.write("\n");
      } else {
        for (int i = 0; i < values.length; i++) {
          writer.write(name);
          writer.write("[" + i + "]=");
          writer.write(values[i]);
          writer.write("\n");
        }
      }
    }

    String cookie_name = request.getParameter("CookieName");
    if (cookie_name != null && cookie_name.trim().length() > 0) {
      String cookie_action = request.getParameter("Button");
      try {
        Cookie cookie = new Cookie(cookie_name.trim(), request.getParameter("CookieVal"));
        if ("Clear Cookie".equals(cookie_action)) cookie.setMaxAge(0);
        response.addCookie(cookie);
      } catch (IllegalArgumentException e) {
        writer.write("</pre>\n<h3>BAD Set-Cookie:</h3>\n<pre>");
        writer.write(e.toString());
      }
    }

    writer.write("</pre>\n<h3>Cookies:</h3>\n<pre>");
    Cookie[] cookies = request.getCookies();
    if (cookies != null && cookies.length > 0) {
      for (int c = 0; c < cookies.length; c++) {
        Cookie cookie = cookies[c];
        writer.write(cookie.getName());
        writer.write("=");
        writer.write(cookie.getValue());
        writer.write("\n");
      }
    }

    writer.write("</pre>\n<h3>Attributes:</h3>\n<pre>");
    Enumeration attributes = request.getAttributeNames();
    if (attributes != null && attributes.hasMoreElements()) {
      while (attributes.hasMoreElements()) {
        String attr = attributes.nextElement().toString();
        writer.write(attr);
        writer.write("=");
        writer.write(request.getAttribute(attr).toString());
        writer.write("\n");
      }
    }

    writer.write("</pre>\n<h3>Content:</h3>\n<pre>");
    byte[] content = new byte[4096];
    int len;
    try {
      InputStream in = request.getInputStream();
      while ((len = in.read(content)) >= 0) writer.write(new String(content, 0, len));
    } catch (IOException e) {
      writer.write(e.toString());
    }

    writer.write("</pre>");
    writer.write("</html>");

    // commit now
    writer.flush();
    response.setContentLength(buf.size() + 1000);
    buf.writeTo(out);

    buf.reset();
    writer.flush();
    for (int pad = 998 - buf.size(); pad-- > 0; ) writer.write(" ");
    writer.write("\015\012");
    writer.flush();
    buf.writeTo(out);

    response.setHeader("IgnoreMe", "ignored");
  }
Exemple #6
0
  @Override
  public void execute(ITransaction transaction, HttpServletRequest req, HttpServletResponse resp)
      throws IOException, LockFailedException {
    LOG.trace("-- " + this.getClass().getName());

    if (!readOnly) {
      String path = getRelativePath(req);
      String parentPath = getParentPath(path);

      userAgent = req.getHeader("User-Agent");

      if (isOSXFinder() && req.getContentLength() == 0) {
        // OS X Finder sends 2 PUTs; first has 0 content, second has content.
        // This is the first one, so we'll ignore it ...
        LOG.trace("-- First of multiple OS-X Finder PUT calls at {0}", path);
      }

      Hashtable<String, Integer> errorList = new Hashtable<String, Integer>();

      if (isOSXFinder()) {
        // OS X Finder sends 2 PUTs; first has 0 content, second has content.
        // This is the second one that was preceded by a LOCK, so don't need to check the locks ...
      } else {
        if (!isUnlocked(transaction, req, resourceLocks, parentPath)) {
          LOG.trace("-- Locked parent at {0}", path);
          resp.setStatus(WebdavStatus.SC_LOCKED);
          return; // parent is locked
        }

        if (!isUnlocked(transaction, req, resourceLocks, path)) {
          LOG.trace("-- Locked resource at {0}", path);
          resp.setStatus(WebdavStatus.SC_LOCKED);
          return; // resource is locked
        }
      }

      String tempLockOwner = "doPut" + System.currentTimeMillis() + req.toString();
      if (resourceLocks.lock(transaction, path, tempLockOwner, false, 0, TEMP_TIMEOUT, TEMPORARY)) {
        StoredObject parentSo, so = null;
        try {
          parentSo = store.getStoredObject(transaction, parentPath);
          if (parentPath != null && parentSo != null && parentSo.isResource()) {
            resp.sendError(WebdavStatus.SC_FORBIDDEN);
            return;

          } else if (parentPath != null && parentSo == null && lazyFolderCreationOnPut) {
            store.createFolder(transaction, parentPath);

          } else if (parentPath != null && parentSo == null && !lazyFolderCreationOnPut) {
            errorList.put(parentPath, WebdavStatus.SC_NOT_FOUND);
            sendReport(req, resp, errorList);
            return;
          }

          LOG.trace("-- Looking for the stored object at {0}", path);
          so = store.getStoredObject(transaction, path);

          if (so == null) {
            LOG.trace("-- Creating resource in the store at {0}", path);
            store.createResource(transaction, path);
            // resp.setStatus(WebdavStatus.SC_CREATED);
          } else {
            // This has already been created, just update the data
            LOG.trace("-- There is already a resource at {0}", path);
            if (so.isNullResource()) {

              LockedObject nullResourceLo = resourceLocks.getLockedObjectByPath(transaction, path);
              if (nullResourceLo == null) {
                LOG.trace("-- Unable to obtain resource lock object at {0}", path);
                resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
                return;
              }
              LOG.trace("-- Found resource lock object at {0}", path);
              String nullResourceLockToken = nullResourceLo.getID();
              String[] lockTokens = getLockIdFromIfHeader(req);
              String lockToken = null;
              if (lockTokens != null) {
                lockToken = lockTokens[0];
              } else {
                LOG.trace("-- No lock tokens found in resource lock object at {0}", path);
                resp.sendError(WebdavStatus.SC_BAD_REQUEST);
                return;
              }
              if (lockToken.equals(nullResourceLockToken)) {
                so.setNullResource(false);
                so.setFolder(false);

                String[] nullResourceLockOwners = nullResourceLo.getOwner();
                String owner = null;
                if (nullResourceLockOwners != null) {
                  owner = nullResourceLockOwners[0];
                }

                if (!resourceLocks.unlock(transaction, lockToken, owner)) {
                  resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
                }
              } else {
                errorList.put(path, WebdavStatus.SC_LOCKED);
                sendReport(req, resp, errorList);
              }
            } else {
              LOG.trace("-- Found a lock for the (existing) resource at {0}", path);
            }
          }
          // User-Agent workarounds
          doUserAgentWorkaround(resp);

          // setting resourceContent
          LOG.trace("-- Setting resource content at {0}", path);
          long resourceLength =
              store.setResourceContent(transaction, path, req.getInputStream(), null, null);

          so = store.getStoredObject(transaction, path);
          if (so == null) {
            resp.setStatus(WebdavStatus.SC_NOT_FOUND);
          } else if (resourceLength != -1) {
            so.setResourceLength(resourceLength);
          }
          // Now lets report back what was actually saved

        } catch (AccessDeniedException e) {
          LOG.trace(e, "Access denied when working with {0}", path);
          resp.sendError(WebdavStatus.SC_FORBIDDEN);
        } catch (WebdavException e) {
          LOG.trace(e, "WebDAV exception when working with {0}", path);
          resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
        } finally {
          resourceLocks.unlockTemporaryLockedObjects(transaction, path, tempLockOwner);
        }
      } else {
        LOG.trace("Lock was not acquired when working with {0}", path);
        resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
      }
    } else {
      LOG.trace("Readonly={0}", readOnly);
      resp.sendError(WebdavStatus.SC_FORBIDDEN);
    }
  }
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   System.out.println(request.toString());
   doPost(request, response);
 }