/**
  * Mark Request that processed at primary node with attribute primaryIndicatorName
  *
  * @param request
  * @throws IOException
  */
 protected void createPrimaryIndicator(Request request) throws IOException {
   String id = request.getRequestedSessionId();
   if ((id != null) && (id.length() > 0)) {
     Manager manager = request.getContext().getManager();
     Session session = manager.findSession(id);
     if (session instanceof ClusterSession) {
       ClusterSession cses = (ClusterSession) session;
       if (log.isDebugEnabled())
         log.debug(
             sm.getString(
                 "ReplicationValve.session.indicator",
                 request.getContext().getName(),
                 id,
                 primaryIndicatorName,
                 Boolean.valueOf(cses.isPrimarySession())));
       request.setAttribute(
           primaryIndicatorName, cses.isPrimarySession() ? Boolean.TRUE : Boolean.FALSE);
     } else {
       if (log.isDebugEnabled()) {
         if (session != null) {
           log.debug(
               sm.getString("ReplicationValve.session.found", request.getContext().getName(), id));
         } else {
           log.debug(
               sm.getString(
                   "ReplicationValve.session.invalid", request.getContext().getName(), id));
         }
       }
     }
   }
 }
  @Test
  public final void testRequestUrlIgnorePatternIsSkippedIfPrimaryMemcachedNodeIsDown()
      throws IOException, ServletException {
    when(_memcachedNodesManager.isNodeAvailable(PRIMARY_NODE_IDENTIFIER)).thenReturn(false);
    when(_request.getRequestedSessionId()).thenReturn(SESSION_ID);
    _sessionTrackerValve.invoke(_request, _response);

    verify(_request).setNote(RequestTrackingHostValve.REQUEST_PROCESS, Boolean.TRUE);
  }
  @Test
  public final void testRequestFinishedShouldBeInvokedForIgnoredResources()
      throws IOException, ServletException {
    when(_request.getRequestedSessionId()).thenReturn("foo");
    when(_request.getRequestURI()).thenReturn("/pixel.gif");

    _sessionTrackerValve.invoke(_request, _response);

    verify(_service).requestFinished(eq("foo"), anyString());
  }
  @Test
  public final void testBackupSessionNotInvokedWhenNoSessionIdPresent()
      throws IOException, ServletException {
    when(_request.getRequestedSessionId()).thenReturn(null);
    when(_response.getHeader(eq("Set-Cookie"))).thenReturn(null);

    _sessionTrackerValve.invoke(_request, _response);

    verify(_service, never()).backupSession(anyString(), anyBoolean(), anyString());
  }
  @Test
  public final void testBackupSessionInvokedWhenResponseCookiePresent()
      throws IOException, ServletException {
    when(_request.getRequestedSessionId()).thenReturn(null);
    final Cookie cookie = new Cookie(_sessionTrackerValve.getSessionCookieName(), "foo");
    setupGetResponseSetCookieHeadersExpectations(
        _response, new String[] {generateCookieString(cookie)});
    _sessionTrackerValve.invoke(_request, _response);

    verify(_service).backupSession(eq("foo"), eq(false), anyString());
  }
  @Test
  public final void testChangeSessionIdForRelocatedSession() throws IOException, ServletException {

    final String sessionId = "bar";
    final String newSessionId = "newId";

    when(_request.getNote(eq(RequestTrackingHostValve.SESSION_ID_CHANGED)))
        .thenReturn(Boolean.TRUE);
    when(_request.getRequestedSessionId()).thenReturn(sessionId);

    final Cookie cookie = new Cookie(_sessionTrackerValve.getSessionCookieName(), newSessionId);
    setupGetResponseSetCookieHeadersExpectations(
        _response, new String[] {generateCookieString(cookie)});

    _sessionTrackerValve.invoke(_request, _response);

    verify(_service).backupSession(eq(newSessionId), eq(true), anyString());
  }
Пример #7
0
  /**
   * Log the interesting request parameters, invoke the next Valve in the sequence, and log the
   * interesting response parameters.
   *
   * @param request The servlet request to be processed
   * @param response The servlet response to be created
   * @exception IOException if an input/output error occurs
   * @exception ServletException if a servlet error occurs
   */
  public void invoke(Request request, Response response) throws IOException, ServletException {

    Log log = container.getLogger();

    // Log pre-service information
    log.info("REQUEST URI       =" + request.getRequestURI());
    log.info("          authType=" + request.getAuthType());
    log.info(" characterEncoding=" + request.getCharacterEncoding());
    log.info("     contentLength=" + request.getContentLength());
    log.info("       contentType=" + request.getContentType());
    log.info("       contextPath=" + request.getContextPath());
    Cookie cookies[] = request.getCookies();
    if (cookies != null) {
      for (int i = 0; i < cookies.length; i++)
        log.info("            cookie=" + cookies[i].getName() + "=" + cookies[i].getValue());
    }
    Enumeration hnames = request.getHeaderNames();
    while (hnames.hasMoreElements()) {
      String hname = (String) hnames.nextElement();
      Enumeration hvalues = request.getHeaders(hname);
      while (hvalues.hasMoreElements()) {
        String hvalue = (String) hvalues.nextElement();
        log.info("            header=" + hname + "=" + hvalue);
      }
    }
    log.info("            locale=" + request.getLocale());
    log.info("            method=" + request.getMethod());
    Enumeration pnames = request.getParameterNames();
    while (pnames.hasMoreElements()) {
      String pname = (String) pnames.nextElement();
      String pvalues[] = request.getParameterValues(pname);
      StringBuffer result = new StringBuffer(pname);
      result.append('=');
      for (int i = 0; i < pvalues.length; i++) {
        if (i > 0) result.append(", ");
        result.append(pvalues[i]);
      }
      log.info("         parameter=" + result.toString());
    }
    log.info("          pathInfo=" + request.getPathInfo());
    log.info("          protocol=" + request.getProtocol());
    log.info("       queryString=" + request.getQueryString());
    log.info("        remoteAddr=" + request.getRemoteAddr());
    log.info("        remoteHost=" + request.getRemoteHost());
    log.info("        remoteUser="******"requestedSessionId=" + request.getRequestedSessionId());
    log.info("            scheme=" + request.getScheme());
    log.info("        serverName=" + request.getServerName());
    log.info("        serverPort=" + request.getServerPort());
    log.info("       servletPath=" + request.getServletPath());
    log.info("          isSecure=" + request.isSecure());
    log.info("---------------------------------------------------------------");

    // Perform the request
    getNext().invoke(request, response);

    // Log post-service information
    log.info("---------------------------------------------------------------");
    log.info("          authType=" + request.getAuthType());
    log.info("     contentLength=" + response.getContentLength());
    log.info("       contentType=" + response.getContentType());
    Cookie rcookies[] = response.getCookies();
    for (int i = 0; i < rcookies.length; i++) {
      log.info(
          "            cookie="
              + rcookies[i].getName()
              + "="
              + rcookies[i].getValue()
              + "; domain="
              + rcookies[i].getDomain()
              + "; path="
              + rcookies[i].getPath());
    }
    String rhnames[] = response.getHeaderNames();
    for (int i = 0; i < rhnames.length; i++) {
      String rhvalues[] = response.getHeaderValues(rhnames[i]);
      for (int j = 0; j < rhvalues.length; j++)
        log.info("            header=" + rhnames[i] + "=" + rhvalues[j]);
    }
    log.info("           message=" + response.getMessage());
    log.info("        remoteUser="******"            status=" + response.getStatus());
    log.info("===============================================================");
  }
  /**
   * Enforce any user data constraint required by the security constraint guarding this request URI.
   * Return <code>true</code> if this constraint was not violated and processing should continue, or
   * <code>false</code> if we have created a response already.
   *
   * @param request Request we are processing
   * @param response Response we are creating
   * @param constraints Security constraint being checked
   * @exception IOException if an input/output error occurs
   */
  @Override
  public boolean hasUserDataPermission(
      Request request, Response response, SecurityConstraint[] constraints) throws IOException {

    // Is there a relevant user data constraint?
    if (constraints == null || constraints.length == 0) {
      if (log.isDebugEnabled()) log.debug("  No applicable security constraint defined");
      return (true);
    }
    for (int i = 0; i < constraints.length; i++) {
      SecurityConstraint constraint = constraints[i];
      String userConstraint = constraint.getUserConstraint();
      if (userConstraint == null) {
        if (log.isDebugEnabled()) log.debug("  No applicable user data constraint defined");
        return (true);
      }
      if (userConstraint.equals(Constants.NONE_TRANSPORT)) {
        if (log.isDebugEnabled()) log.debug("  User data constraint has no restrictions");
        return (true);
      }
    }
    // Validate the request against the user data constraint
    if (request.getRequest().isSecure()) {
      if (log.isDebugEnabled()) log.debug("  User data constraint already satisfied");
      return (true);
    }
    // Initialize variables we need to determine the appropriate action
    int redirectPort = request.getConnector().getRedirectPort();

    // Is redirecting disabled?
    if (redirectPort <= 0) {
      if (log.isDebugEnabled()) log.debug("  SSL redirect is disabled");
      response.sendError(HttpServletResponse.SC_FORBIDDEN, request.getRequestURI());
      return (false);
    }

    // Redirect to the corresponding SSL port
    StringBuilder file = new StringBuilder();
    String protocol = "https";
    String host = request.getServerName();
    // Protocol
    file.append(protocol).append("://").append(host);
    // Host with port
    if (redirectPort != 443) {
      file.append(":").append(redirectPort);
    }
    // URI
    file.append(request.getRequestURI());
    String requestedSessionId = request.getRequestedSessionId();
    if ((requestedSessionId != null) && request.isRequestedSessionIdFromURL()) {
      file.append(";");
      file.append(SessionConfig.getSessionUriParamName(request.getContext()));
      file.append("=");
      file.append(requestedSessionId);
    }
    String queryString = request.getQueryString();
    if (queryString != null) {
      file.append('?');
      file.append(queryString);
    }
    if (log.isDebugEnabled()) log.debug("  Redirecting to " + file.toString());
    response.sendRedirect(file.toString());
    return (false);
  }