/*
  * (non-Javadoc)
  *
  * @see org.mockito.ArgumentMatcher#matches(java.lang.Object)
  */
 @Override
 public boolean matches(final Object argument) {
   if (argument instanceof Cookie) {
     final Cookie givenCookie = (Cookie) argument;
     if (givenCookie.getSecure() == expectedCookie.getSecure()) {
       if (givenCookie.getMaxAge() == expectedCookie.getMaxAge()) {
         if (givenCookie.getName().equals(expectedCookie.getName())) {
           if (givenCookie.getPath() == expectedCookie.getPath()
               || givenCookie.getPath().equals(expectedCookie.getPath())) {
             if (givenCookie.getValue().equals(expectedCookie.getValue())) {
               if (givenCookie.getDomain() == expectedCookie.getDomain()
                   || givenCookie.getDomain().equals(expectedCookie.getDomain())) {
                 return true;
               }
             }
           }
         }
       }
     }
     Assert.fail(
         "Expected \n["
             + ToStringBuilder.reflectionToString(expectedCookie)
             + "]\n but got \n["
             + ToStringBuilder.reflectionToString(argument)
             + "]");
   }
   return false;
 }
  /**
   * Adds a cookie to the response.
   *
   * @param response The servlet response.
   * @param cookie The cookie to be sent.
   */
  private void addCookie(HttpServletResponse response, Cookie cookie) {
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug(
          "Adding cookie: "
              + cookie.getDomain()
              + cookie.getPath()
              + " "
              + cookie.getName()
              + "="
              + cookie.getValue());
    }
    // We don't use the container's response.addCookie, since the HttpOnly cookie flag was
    // introduced only recently
    // in the servlet specification, and we're still using the older 2.4 specification as a minimal
    // requirement for
    // compatibility with as many containers as possible. Instead, we write the cookie manually as a
    // HTTP header.
    StringBuilder cookieValue = new StringBuilder(150);
    cookieValue.append(cookie.getName() + "=");
    if (StringUtils.isNotEmpty(cookie.getValue())) {
      cookieValue.append("\"" + cookie.getValue() + "\"");
    }
    cookieValue.append("; Version=1");
    if (cookie.getMaxAge() >= 0) {
      cookieValue.append("; Max-Age=" + cookie.getMaxAge());
      // IE is such a pain, it doesn't understand the modern, safer Max-Age
      cookieValue.append("; Expires=");
      if (cookie.getMaxAge() == 0) {
        cookieValue.append(COOKIE_EXPIRE_NOW);
      } else {
        cookieValue.append(
            COOKIE_EXPIRE_FORMAT.format(
                new Date(System.currentTimeMillis() + cookie.getMaxAge() * 1000L)));
      }
    }
    if (StringUtils.isNotEmpty(cookie.getDomain())) {
      // IE needs toLowerCase for the domain name
      cookieValue.append("; Domain=" + cookie.getDomain().toLowerCase());
    }
    if (StringUtils.isNotEmpty(cookie.getPath())) {
      cookieValue.append("; Path=" + cookie.getPath());
    }
    // Protect cookies from being used from JavaScript, see http://www.owasp.org/index.php/HttpOnly
    cookieValue.append("; HttpOnly");

    // Session cookies should be discarded.
    // FIXME Safari 5 can't handle properly "Discard", as it really discards all the response header
    // data after the
    // first "Discard" encountered, so it will only see the first such cookie. Disabled for the
    // moment until Safari
    // gets fixed, or a better idea comes to mind.
    // Since we don't set a Max-Age, the rfc2109 behavior will kick in, and recognize this as a
    // session cookie.
    // if (cookie.getMaxAge() < 0) {
    // cookieValue.append("; Discard");
    // }
    response.addHeader("Set-Cookie", cookieValue.toString());
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;charset=UTF-8");

    Cookie[] cookies = request.getCookies();
    if (cookies != null && cookies.length > 0) {
      for (Cookie c : cookies) {
        System.out.println("cookie domain :" + c.getDomain());
        System.out.println("cookie path :" + c.getPath());
        System.out.println("cookie comment :" + c.getComment());

        System.out.println("cookie maxAge :" + c.getMaxAge());
        System.out.println("cookie version :" + c.getVersion());
        System.out.println("cookie name :" + c.getName());
        System.out.println("cookie value:" + c.getValue());
      }
    } else {
      System.err.println("不存在cookie");
    }

    // 创建cookie
    Cookie cookie = new Cookie("myCookie", "mycookieServlet");

    // 将cookie信息通知浏览器
    response.addCookie(cookie);
  }
Example #4
0
  public void json(RequestInfoHttp reqInfo, String content, List<Cookie> cookies)
      throws IOException {

    if (cookies.size() > 0) {
      HttpServletResponse res = reqInfo.getRes();

      Cookie[] exists = reqInfo.getReq().getCookies();

      for (Cookie ck : cookies) {
        Cookie found = null;
        for (Cookie eck : exists) {
          if (eck.getName().equals(ck.getName())) {
            found = eck;
            break;
          }
        }
        if (found == null) {
          res.addCookie(ck);
        } else {
          found.setValue(ck.getValue());
          found.setMaxAge(ck.getMaxAge());
          found.setPath(ck.getPath());
          res.addCookie(found);
        }
      }
    }

    json(reqInfo, content);
  }
  @Test
  public void testTrackClusterNewUser() throws Exception {
    // activate
    String serverId = getServerId();
    Capture<String> serverIdCapture = new Capture<String>();
    Capture<ClusterServerImpl> clusterServerCapture = new Capture<ClusterServerImpl>();
    expect(serverTrackingCache.list()).andReturn(new ArrayList<Object>()).times(2);
    expect(serverTrackingCache.put(capture(serverIdCapture), capture(clusterServerCapture)))
        .andReturn(new Object());

    // trackClusterUser
    HttpServletRequest request = createMock(HttpServletRequest.class);
    HttpServletResponse response = createMock(HttpServletResponse.class);

    Cookie cookieA = new Cookie("something", "someValue");
    Cookie cookieB = new Cookie("somethingElse", "someOtherValue");

    Cookie[] cookies = new Cookie[] {cookieA, cookieB};

    expect(request.getCookies()).andReturn(cookies);
    expect(request.getRemoteUser()).andReturn("userid");

    expect(response.isCommitted()).andReturn(false);
    Capture<Cookie> captureCookie = new Capture<Cookie>();
    response.addCookie(capture(captureCookie));
    expectLastCall();

    response.addHeader("Cache-Control", "no-cache=\"set-cookie\" ");
    expectLastCall();
    response.addDateHeader("Expires", 0);
    expectLastCall();

    // deactivate
    serverTrackingCache.remove(serverId);

    replay();
    clusterTrackingServiceImpl.activate(componentContext);

    clusterTrackingServiceImpl.trackClusterUser(request, response);

    clusterTrackingServiceImpl.deactivate(componentContext);
    assertTrue(serverIdCapture.hasCaptured());
    assertEquals(serverId, serverIdCapture.getValue());
    assertTrue(clusterServerCapture.hasCaptured());
    ClusterServerImpl clusterServerImpl = clusterServerCapture.getValue();
    assertEquals(serverId, clusterServerImpl.getServerId());
    assertTrue(System.currentTimeMillis() >= clusterServerImpl.getLastModified());

    // check the cookie
    assertTrue(captureCookie.hasCaptured());
    Cookie cookie = captureCookie.getValue();
    assertEquals("SAKAI-TRACKING", cookie.getName());
    assertEquals("/", cookie.getPath());
    assertEquals(-1, cookie.getMaxAge());
    assertNotNull(cookie.getValue());
    assertTrue(cookie.getValue().startsWith(serverId));
    verify();
  }
  @Override
  public void addCookie(Cookie cookie) {

    StringBuffer cookieHeader = new StringBuffer();

    cookieHeader.append(cookie.getName());
    cookieHeader.append("=");
    cookieHeader.append(cookie.getValue());
    if (cookie.getPath() != null) {
      cookieHeader.append("; Path=");
      cookieHeader.append(cookie.getPath());
    }
    if (cookie.getDomain() != null) {
      cookieHeader.append("; Domain=");
      cookieHeader.append(cookie.getDomain());
    }
    if (cookie.getMaxAge() > 0) {
      cookieHeader.append("; Max-Age=");
      cookieHeader.append(cookie.getMaxAge());
      /** This breaks IE when date of server and browser do not match */
      cookieHeader.append("; Expires=");
      if (cookie.getMaxAge() == 0) {
        cookieHeader.append(DateUtils.formatDate(new Date(10000), DateUtils.PATTERN_RFC1036));
      } else {
        cookieHeader.append(
            DateUtils.formatDate(
                new Date(System.currentTimeMillis() + cookie.getMaxAge() * 1000L),
                DateUtils.PATTERN_RFC1036));
      }
    }

    if (cookie.getSecure()) {
      cookieHeader.append("; Secure");
    }

    /** Make sure we are not adding duplicate cookies */
    for (Entry<String, String> entry : response.getHeaders()) {
      if (entry.getKey().equals("Set-Cookie") && entry.getValue().equals(cookieHeader.toString())) {
        return;
      }
    }
    addHeader("Set-Cookie", cookieHeader.toString());
  }
Example #7
0
 public void setValue(Object key, Object value) {
   if (this.response == null) {
     throw new UnsupportedOperationException();
   }
   if (key == null) {
     throw new NullPointerException("Key can't be null.");
   }
   if (this.cookieMap == null) {
     this.initCookie();
   }
   String name = key.toString();
   Cookie cookie = null;
   if (value == null) {
     Cookie oldCookie = (Cookie) this.cookieMap.get(name);
     if (oldCookie != null) {
       cookie = new Cookie(this.encodeStr(name), "");
       cookie.setMaxAge(0);
       cookie.setDomain(oldCookie.getDomain());
       cookie.setPath(oldCookie.getPath());
     }
   } else if (value instanceof Cookie) {
     cookie = (Cookie) value;
     String cookieName = this.decodeStr(cookie.getName(), this.response.getCharacterEncoding());
     if (!(name.equals(cookieName))) {
       throw new IllegalArgumentException(
           "The cookie name not same, name:[" + name + "], cookie:[" + cookieName + "]");
     }
   } else {
     String str = value.toString();
     if (this.compressValue) {
       BooleanRef ziped = new BooleanRef();
       str = this.doDeflater(str, ziped);
       if (ziped.value) {
         str = COMPRESS_VALUE_PREFIX.concat(str);
       } else {
         str = this.encodeStr(str);
       }
     } else {
       str = this.encodeStr(str);
     }
     cookie = new Cookie(this.encodeStr(name), str);
     cookie.setPath(this.request.getContextPath().concat("/"));
   }
   if (cookie != null) {
     this.response.addCookie(cookie);
     if (cookie.getMaxAge() == 0) {
       this.cookieMap.remove(name);
     } else {
       this.cookieMap.put(name, cookie);
     }
   }
 }
Example #8
0
 /**
  * Generate httponly cookie from HS2 cookie
  *
  * @param cookie HS2 generated cookie
  * @return The httponly cookie
  */
 private static String getHttpOnlyCookieHeader(Cookie cookie) {
   NewCookie newCookie =
       new NewCookie(
           cookie.getName(),
           cookie.getValue(),
           cookie.getPath(),
           cookie.getDomain(),
           cookie.getVersion(),
           cookie.getComment(),
           cookie.getMaxAge(),
           cookie.getSecure());
   return newCookie + "; HttpOnly";
 }
  protected org.apache.commons.httpclient.Cookie toCommonsCookie(Cookie cookie) {

    org.apache.commons.httpclient.Cookie commonsCookie =
        new org.apache.commons.httpclient.Cookie(
            cookie.getDomain(),
            cookie.getName(),
            cookie.getValue(),
            cookie.getPath(),
            cookie.getMaxAge(),
            cookie.getSecure());

    commonsCookie.setVersion(cookie.getVersion());

    return commonsCookie;
  }
Example #10
0
 @Override
 public Collection<Cookie> getRequestCookies() {
   final javax.servlet.http.Cookie[] cookies = this.request.getCookies();
   final Collection<Cookie> pac4jCookies = new LinkedHashSet<>(cookies.length);
   for (javax.servlet.http.Cookie c : this.request.getCookies()) {
     final Cookie cookie = new Cookie(c.getName(), c.getValue());
     cookie.setComment(c.getComment());
     cookie.setDomain(c.getDomain());
     cookie.setHttpOnly(c.isHttpOnly());
     cookie.setMaxAge(c.getMaxAge());
     cookie.setPath(c.getPath());
     cookie.setSecure(c.getSecure());
     pac4jCookies.add(cookie);
   }
   return pac4jCookies;
 }
 @Nonnull
 protected String generateCookieString(final Cookie cookie) {
   final StringBuffer sb = new StringBuffer();
   ServerCookie.appendCookieValue(
       sb,
       cookie.getVersion(),
       cookie.getName(),
       cookie.getValue(),
       cookie.getPath(),
       cookie.getDomain(),
       cookie.getComment(),
       cookie.getMaxAge(),
       cookie.getSecure(),
       true);
   final String setSessionCookieHeader = sb.toString();
   return setSessionCookieHeader;
 }
Example #12
0
  protected static Map<String, Http.Cookie> getCookies(HttpServletRequest httpServletRequest) {
    Map<String, Http.Cookie> cookies = new HashMap<String, Http.Cookie>(16);
    javax.servlet.http.Cookie[] cookiesViaServlet = httpServletRequest.getCookies();
    if (cookiesViaServlet != null) {
      for (javax.servlet.http.Cookie cookie : cookiesViaServlet) {
        Http.Cookie playCookie = new Http.Cookie();
        playCookie.name = cookie.getName();
        playCookie.path = cookie.getPath();
        playCookie.domain = cookie.getDomain();
        playCookie.secure = cookie.getSecure();
        playCookie.value = cookie.getValue();
        playCookie.maxAge = cookie.getMaxAge();
        cookies.put(playCookie.name, playCookie);
      }
    }

    return cookies;
  }
Example #13
0
  @Override
  public void addCookie(Cookie cookie) {
    String comment = cookie.getComment();
    boolean httpOnly = false;

    if (comment != null) {
      int i = comment.indexOf(HTTP_ONLY_COMMENT);
      if (i >= 0) {
        httpOnly = true;
        comment = comment.replace(HTTP_ONLY_COMMENT, "").trim();
        if (comment.length() == 0) comment = null;
      }
    }
    _fields.addSetCookie(
        cookie.getName(),
        cookie.getValue(),
        cookie.getDomain(),
        cookie.getPath(),
        cookie.getMaxAge(),
        comment,
        cookie.getSecure(),
        httpOnly || cookie.isHttpOnly(),
        cookie.getVersion());
  }
Example #14
0
 @Override
 public int getExpiry() {
   return cookie.getMaxAge();
 }
Example #15
0
  @Override
  public void onTrigger(final ProcessContext context, final ProcessSession session)
      throws ProcessException {
    try {
      if (!initialized.get()) {
        initializeServer(context);
      }
    } catch (Exception e) {
      context.yield();
      throw new ProcessException("Failed to initialize the server", e);
    }

    final HttpRequestContainer container = containerQueue.poll();
    if (container == null) {
      return;
    }

    final long start = System.nanoTime();
    final HttpServletRequest request = container.getRequest();
    FlowFile flowFile = session.create();
    try {
      flowFile = session.importFrom(request.getInputStream(), flowFile);
    } catch (final IOException e) {
      getLogger()
          .error(
              "Failed to receive content from HTTP Request from {} due to {}",
              new Object[] {request.getRemoteAddr(), e});
      session.remove(flowFile);
      return;
    }

    final String charset =
        request.getCharacterEncoding() == null
            ? context.getProperty(URL_CHARACTER_SET).getValue()
            : request.getCharacterEncoding();

    final String contextIdentifier = UUID.randomUUID().toString();
    final Map<String, String> attributes = new HashMap<>();
    try {
      putAttribute(attributes, HTTPUtils.HTTP_CONTEXT_ID, contextIdentifier);
      putAttribute(attributes, "mime.type", request.getContentType());
      putAttribute(attributes, "http.servlet.path", request.getServletPath());
      putAttribute(attributes, "http.context.path", request.getContextPath());
      putAttribute(attributes, "http.method", request.getMethod());
      putAttribute(attributes, "http.local.addr", request.getLocalAddr());
      putAttribute(attributes, HTTPUtils.HTTP_LOCAL_NAME, request.getLocalName());
      if (request.getQueryString() != null) {
        putAttribute(
            attributes, "http.query.string", URLDecoder.decode(request.getQueryString(), charset));
      }
      putAttribute(attributes, HTTPUtils.HTTP_REMOTE_HOST, request.getRemoteHost());
      putAttribute(attributes, "http.remote.addr", request.getRemoteAddr());
      putAttribute(attributes, "http.remote.user", request.getRemoteUser());
      putAttribute(attributes, HTTPUtils.HTTP_REQUEST_URI, request.getRequestURI());
      putAttribute(attributes, "http.request.url", request.getRequestURL().toString());
      putAttribute(attributes, "http.auth.type", request.getAuthType());

      putAttribute(attributes, "http.requested.session.id", request.getRequestedSessionId());
      if (request.getDispatcherType() != null) {
        putAttribute(attributes, "http.dispatcher.type", request.getDispatcherType().name());
      }
      putAttribute(attributes, "http.character.encoding", request.getCharacterEncoding());
      putAttribute(attributes, "http.locale", request.getLocale());
      putAttribute(attributes, "http.server.name", request.getServerName());
      putAttribute(attributes, HTTPUtils.HTTP_PORT, request.getServerPort());

      final Enumeration<String> paramEnumeration = request.getParameterNames();
      while (paramEnumeration.hasMoreElements()) {
        final String paramName = paramEnumeration.nextElement();
        final String value = request.getParameter(paramName);
        attributes.put("http.param." + paramName, value);
      }

      final Cookie[] cookies = request.getCookies();
      if (cookies != null) {
        for (final Cookie cookie : cookies) {
          final String name = cookie.getName();
          final String cookiePrefix = "http.cookie." + name + ".";
          attributes.put(cookiePrefix + "value", cookie.getValue());
          attributes.put(cookiePrefix + "domain", cookie.getDomain());
          attributes.put(cookiePrefix + "path", cookie.getPath());
          attributes.put(cookiePrefix + "max.age", String.valueOf(cookie.getMaxAge()));
          attributes.put(cookiePrefix + "version", String.valueOf(cookie.getVersion()));
          attributes.put(cookiePrefix + "secure", String.valueOf(cookie.getSecure()));
        }
      }

      final String queryString = request.getQueryString();
      if (queryString != null) {
        final String[] params = URL_QUERY_PARAM_DELIMITER.split(queryString);
        for (final String keyValueString : params) {
          final int indexOf = keyValueString.indexOf("=");
          if (indexOf < 0) {
            // no =, then it's just a key with no value
            attributes.put("http.query.param." + URLDecoder.decode(keyValueString, charset), "");
          } else {
            final String key = keyValueString.substring(0, indexOf);
            final String value;

            if (indexOf == keyValueString.length() - 1) {
              value = "";
            } else {
              value = keyValueString.substring(indexOf + 1);
            }

            attributes.put(
                "http.query.param." + URLDecoder.decode(key, charset),
                URLDecoder.decode(value, charset));
          }
        }
      }
    } catch (final UnsupportedEncodingException uee) {
      throw new ProcessException(
          "Invalid character encoding", uee); // won't happen because charset has been validated
    }

    final Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
      final String headerName = headerNames.nextElement();
      final String headerValue = request.getHeader(headerName);
      putAttribute(attributes, "http.headers." + headerName, headerValue);
    }

    final Principal principal = request.getUserPrincipal();
    if (principal != null) {
      putAttribute(attributes, "http.principal.name", principal.getName());
    }

    final X509Certificate certs[] =
        (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate");
    final String subjectDn;
    if (certs != null && certs.length > 0) {
      final X509Certificate cert = certs[0];
      subjectDn = cert.getSubjectDN().getName();
      final String issuerDn = cert.getIssuerDN().getName();

      putAttribute(attributes, HTTPUtils.HTTP_SSL_CERT, subjectDn);
      putAttribute(attributes, "http.issuer.dn", issuerDn);
    } else {
      subjectDn = null;
    }

    flowFile = session.putAllAttributes(flowFile, attributes);

    final HttpContextMap contextMap =
        context.getProperty(HTTP_CONTEXT_MAP).asControllerService(HttpContextMap.class);
    final boolean registered =
        contextMap.register(
            contextIdentifier, request, container.getResponse(), container.getContext());

    if (!registered) {
      getLogger()
          .warn(
              "Received request from {} but could not process it because too many requests are already outstanding; responding with SERVICE_UNAVAILABLE",
              new Object[] {request.getRemoteAddr()});

      try {
        container.getResponse().setStatus(Status.SERVICE_UNAVAILABLE.getStatusCode());
        container.getResponse().flushBuffer();
        container.getContext().complete();
      } catch (final Exception e) {
        getLogger()
            .warn(
                "Failed to respond with SERVICE_UNAVAILABLE message to {} due to {}",
                new Object[] {request.getRemoteAddr(), e});
      }

      session.remove(flowFile);
      return;
    }

    final long receiveMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
    session
        .getProvenanceReporter()
        .receive(
            flowFile,
            HTTPUtils.getURI(attributes),
            "Received from "
                + request.getRemoteAddr()
                + (subjectDn == null ? "" : " with DN=" + subjectDn),
            receiveMillis);
    session.transfer(flowFile, REL_SUCCESS);
    getLogger()
        .info(
            "Transferring {} to 'success'; received from {}",
            new Object[] {flowFile, request.getRemoteAddr()});
  }
  @Override
  public void doFilter(
      ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
      throws IOException, ServletException {
    logger.info("============== Request received ==============");

    HttpServletRequestCachedBodyWrapper request =
        new HttpServletRequestCachedBodyWrapper((HttpServletRequest) servletRequest);

    StringBuilder sb = new StringBuilder("Logging most of the request information:\n\n");

    sb.append(String.format("%-23s", "getProtocol()"))
        .append(" => ")
        .append(request.getProtocol())
        .append("\n");
    sb.append(String.format("%-23s", "getMethod()"))
        .append(" => ")
        .append(request.getMethod())
        .append("\n");
    sb.append(String.format("%-23s", "getRequestURL()"))
        .append(" => ")
        .append(request.getRequestURL())
        .append("\n");
    sb.append(String.format("%-23s", "getRequestURI()"))
        .append(" => ")
        .append(request.getRequestURI())
        .append("\n");
    sb.append(String.format("%-23s", "getQueryString()"))
        .append(" => ")
        .append(request.getQueryString())
        .append("\n");
    sb.append(String.format("%-23s", "getContextPath()"))
        .append(" => ")
        .append(request.getContextPath())
        .append("\n");
    sb.append(String.format("%-23s", "getContentType()"))
        .append(" => ")
        .append(request.getContentType())
        .append("\n");
    sb.append(String.format("%-23s", "getCharacterEncoding()"))
        .append(" => ")
        .append(request.getCharacterEncoding())
        .append("\n");
    sb.append(String.format("%-23s", "getContentLengthLong()"))
        .append(" => ")
        .append(request.getContentLengthLong())
        .append("\n");
    sb.append(String.format("%-23s", "getRemoteAddr()"))
        .append(" => ")
        .append(request.getRemoteAddr())
        .append("\n");
    sb.append(String.format("%-23s", "getRemoteHost()"))
        .append(" => ")
        .append(request.getRemoteHost())
        .append("\n");
    sb.append(String.format("%-23s", "getAuthType()"))
        .append(" => ")
        .append(request.getAuthType())
        .append("\n");

    sb.append("\n\n");

    sb.append("#Query Parameters:\n\n");

    int longestQueryParamLength = getLengthOfLongestValue(request.getParameterNames());

    if (request.getParameterMap() == null || request.getParameterMap().isEmpty()) {
      sb.append("(no parameters)\n");
    } else {
      for (Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
        sb.append(String.format("%-" + longestQueryParamLength + "s", entry.getKey()));
        sb.append(" => ");
        String comma = "";
        for (String value : entry.getValue()) {
          sb.append(value);
          sb.append(comma);
          comma = ", ";
        }
        sb.append("\n");
      }
    }

    sb.append("\n\n");

    sb.append("#Headers:\n\n");

    int longestHeaderNameLength = getLengthOfLongestValue(request.getHeaderNames());

    Enumeration<String> headerNames = request.getHeaderNames();

    if (headerNames != null) {
      if (!headerNames.hasMoreElements()) {
        sb.append("(no headers)\n");
      } else {
        while (headerNames.hasMoreElements()) {
          String headerName = headerNames.nextElement();
          sb.append(String.format("%-" + longestHeaderNameLength + "s", headerName));
          sb.append(" =>  ");
          sb.append(request.getHeader(headerName));
          sb.append("\n");
        }
      }
    }

    sb.append("\n\n");

    sb.append("#Cookies:\n\n");

    if (request.getCookies() != null && request.getCookies().length > 0) {
      for (Cookie cookie : request.getCookies()) {
        sb.append(String.format("%-23s", "getName()"))
            .append(" => ")
            .append(cookie.getName())
            .append("\n");
        sb.append(String.format("%-23s", "getValue()"))
            .append(" => ")
            .append(cookie.getValue())
            .append("\n");
        sb.append(String.format("%-23s", "getMaxAge()"))
            .append(" => ")
            .append(cookie.getMaxAge())
            .append("\n");
        sb.append(String.format("%-23s", "getDomain()"))
            .append(" => ")
            .append(cookie.getDomain())
            .append("\n");
        sb.append(String.format("%-23s", "getPath()"))
            .append(" => ")
            .append(cookie.getPath())
            .append("\n");
        sb.append(String.format("%-23s", "getSecure()"))
            .append(" => ")
            .append(cookie.getSecure())
            .append("\n");
        sb.append(String.format("%-23s", "getVersion()"))
            .append(" => ")
            .append(cookie.getVersion())
            .append("\n");
        sb.append(String.format("%-23s", "getComment()"))
            .append(" => ")
            .append(cookie.getComment())
            .append("\n");
        sb.append("\n");
      }
    } else {
      sb.append("(no cookies)\n");
    }

    sb.append("\n\n");

    sb.append("#Body:\n\n");

    if (StringUtils.isEmpty(request.getBody())) {
      sb.append("(body is empty)");
    } else {
      sb.append(request.getBody());
    }

    sb.append("\n");

    logger.info(sb.toString());

    if (request.getRequestURI().startsWith("/status")) {
      String statusCode = request.getRequestURI().replace("/status", "");
      try {
        ((HttpServletResponse) servletResponse).setStatus(Integer.parseInt(statusCode));
        logger.info("Response status code: " + statusCode);
      } catch (NumberFormatException e) {
        throw new RuntimeException("status code must be an Integer. Example: /status200");
      }

    } else if (request.getRequestURI().startsWith("/file")) {
      filterChain.doFilter(servletRequest, servletResponse);

    } else if (request.getRequestURI().startsWith("/pubsubhubbub")) {
      filterChain.doFilter(servletRequest, servletResponse);

    } else {
      logger.info("Response status code: 200");
    }

    // DONE, we just wanted to print the values, it should not reach any controllers
    // filterChain.doFilter(servletRequest, servletResponse);
  }
 /**
  * Returns the maximum age of the cookie, specified in seconds, By default, <code>-1</code>
  * indicating the cookie will persist until browser shutdown.
  *
  * @return an integer specifying the maximum age of the cookie in seconds; if negative, means the
  *     cookie persists until browser shutdown
  * @see #setMaxAge
  */
 @Override
 public int getMaxAge() {
   return wrappedCookie.getMaxAge();
 }
Example #18
0
  public static Request parseRequest(HttpServletRequest httpServletRequest) throws Exception {
    Request request = new Http.Request();
    Request.current.set(request);
    URI uri = new URI(httpServletRequest.getRequestURI());
    request.method = httpServletRequest.getMethod().intern();
    request.path = uri.getPath();
    request.querystring =
        httpServletRequest.getQueryString() == null ? "" : httpServletRequest.getQueryString();
    Logger.trace("httpServletRequest.getContextPath(): " + httpServletRequest.getContextPath());
    Logger.trace("request.path: " + request.path + ", request.querystring: " + request.querystring);

    Router.routeOnlyStatic(request);

    if (httpServletRequest.getHeader("Content-Type") != null) {
      request.contentType =
          httpServletRequest.getHeader("Content-Type").split(";")[0].trim().toLowerCase().intern();
    } else {
      request.contentType = "text/html".intern();
    }

    if (httpServletRequest.getHeader("X-HTTP-Method-Override") != null) {
      request.method = httpServletRequest.getHeader("X-HTTP-Method-Override").intern();
    }

    request.body = httpServletRequest.getInputStream();
    request.secure = httpServletRequest.isSecure();

    request.url =
        uri.toString()
            + (httpServletRequest.getQueryString() == null
                ? ""
                : "?" + httpServletRequest.getQueryString());
    request.host = httpServletRequest.getHeader("host");
    if (request.host.contains(":")) {
      request.port = Integer.parseInt(request.host.split(":")[1]);
      request.domain = request.host.split(":")[0];
    } else {
      request.port = 80;
      request.domain = request.host;
    }

    request.remoteAddress = httpServletRequest.getRemoteAddr();

    if (Play.configuration.containsKey("XForwardedSupport")
        && httpServletRequest.getHeader("X-Forwarded-For") != null) {
      if (!Arrays.asList(
              Play.configuration.getProperty("XForwardedSupport", "127.0.0.1").split(","))
          .contains(request.remoteAddress)) {
        throw new RuntimeException("This proxy request is not authorized");
      } else {
        request.secure =
            ("https".equals(Play.configuration.get("XForwardedProto"))
                || "https".equals(httpServletRequest.getHeader("X-Forwarded-Proto"))
                || "on".equals(httpServletRequest.getHeader("X-Forwarded-Ssl")));
        if (Play.configuration.containsKey("XForwardedHost")) {
          request.host = (String) Play.configuration.get("XForwardedHost");
        } else if (httpServletRequest.getHeader("X-Forwarded-Host") != null) {
          request.host = httpServletRequest.getHeader("X-Forwarded-Host");
        }
        if (httpServletRequest.getHeader("X-Forwarded-For") != null) {
          request.remoteAddress = httpServletRequest.getHeader("X-Forwarded-For");
        }
      }
    }

    Enumeration headersNames = httpServletRequest.getHeaderNames();
    while (headersNames.hasMoreElements()) {
      Http.Header hd = new Http.Header();
      hd.name = (String) headersNames.nextElement();
      hd.values = new ArrayList<String>();
      Enumeration enumValues = httpServletRequest.getHeaders(hd.name);
      while (enumValues.hasMoreElements()) {
        String value = (String) enumValues.nextElement();
        hd.values.add(value);
      }
      request.headers.put(hd.name.toLowerCase(), hd);
    }

    request.resolveFormat();

    javax.servlet.http.Cookie[] cookies = httpServletRequest.getCookies();
    if (cookies != null) {
      for (javax.servlet.http.Cookie cookie : cookies) {
        Http.Cookie playCookie = new Http.Cookie();
        playCookie.name = cookie.getName();
        playCookie.path = cookie.getPath();
        playCookie.domain = cookie.getDomain();
        playCookie.secure = cookie.getSecure();
        playCookie.value = cookie.getValue();
        playCookie.maxAge = cookie.getMaxAge();
        request.cookies.put(playCookie.name, playCookie);
      }
    }

    request._init();

    return request;
  }