Example usage for javax.servlet.http Cookie getMaxAge

List of usage examples for javax.servlet.http Cookie getMaxAge

Introduction

In this page you can find the example usage for javax.servlet.http Cookie getMaxAge.

Prototype

public int getMaxAge() 

Source Link

Document

Gets the maximum age in seconds of this Cookie.

Usage

From source file:org.projectforge.web.UserFilter.java

public void doFilter(final ServletRequest req, final ServletResponse resp, final FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    if (log.isDebugEnabled() == true) {
        log.debug("doFilter " + request.getRequestURI() + ": " + request.getSession().getId());
        final Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (final Cookie cookie : cookies) {
                log.debug("Cookie " + cookie.getName() + ", path=" + cookie.getPath() + ", value="
                        + cookie.getValue() + ", secure=" + cookie.getVersion() + ", maxAge="
                        + cookie.getMaxAge() + ", domain=" + cookie.getDomain());
            }//from  www .ja v a2 s .  co  m
        }
    }
    final HttpServletResponse response = (HttpServletResponse) resp;
    PFUserDO user = null;
    try {
        MDC.put("ip", request.getRemoteAddr());
        MDC.put("session", request.getSession().getId());
        if (ignoreFilterFor(request) == true) {
            // Ignore the filter for this request:
            if (log.isDebugEnabled() == true) {
                log.debug("Ignore: " + request.getRequestURI());
            }
            chain.doFilter(request, response);
        } else {
            // final boolean sessionTimeout = request.isRequestedSessionIdValid() == false;
            user = (PFUserDO) request.getSession().getAttribute(SESSION_KEY_USER);
            if (user != null) {
                if (log.isDebugEnabled() == true) {
                    log.debug("User found in session: " + request.getRequestURI());
                }
            } else if (updateRequiredFirst == false) {
                // Ignore stay-logged-in if redirect to update page is required.
                user = checkStayLoggedIn(request, response);
                if (user != null) {
                    if (log.isDebugEnabled() == true) {
                        log.debug("User's stay logged-in cookie found: " + request.getRequestURI());
                    }
                    user.setAttribute(USER_ATTR_STAY_LOGGED_IN, true); // Used by MenuMobilePage.
                    UserFilter.login(request, user);
                }
            }
            if (user != null) {
                MDC.put("user", user.getUsername());
                PFUserContext.setUser(user);
                request = decorateWithLocale(request, user);
                chain.doFilter(request, response);
            } else {
                if (((HttpServletRequest) req).getRequestURI().startsWith(WICKET_PAGES_PREFIX) == true) {
                    // Access-checking is done by Wicket, not by this filter:
                    request = decorateWithLocale(request, user);
                    chain.doFilter(request, response);
                } else {
                    response.getWriter().append("No access.");
                }
            }
        }
    } finally {
        PFUserContext.setUser(null);
        MDC.remove("ip");
        MDC.remove("session");
        if (user != null) {
            MDC.remove("user");
        }
        if (log.isDebugEnabled() == true) {
            log.debug("doFilter finished for " + request.getRequestURI() + ": " + request.getSession().getId());
        }
    }
}

From source file:org.sakaiproject.entitybroker.util.http.HttpRESTUtils.java

/**
 * Generates a reusable http client wrapper which can be given to {@link #fireRequest(HttpClientWrapper, String, Method, Map, Object, boolean)}
 * as an efficiency mechanism/*from w w w . j  a  v a2s. c  om*/
 * 
 * @param multiThreaded true if you want to allow the client to run in multiple threads
 * @param idleConnectionTimeout if this is 0 then it will use the defaults, otherwise connections will be timed out after this long (ms)
 * @param cookies to send along with every request from this client
 * @return the reusable http client wrapper
 */
public static HttpClientWrapper makeReusableHttpClient(boolean multiThreaded, int idleConnectionTimeout,
        Cookie[] cookies) {
    HttpClientWrapper wrapper;
    HttpClient client;
    MultiThreadedHttpConnectionManager connectionManager = null;
    if (multiThreaded) {
        connectionManager = new MultiThreadedHttpConnectionManager();
        client = new HttpClient(connectionManager);
    } else {
        client = new HttpClient();
    }
    if (idleConnectionTimeout <= 0) {
        idleConnectionTimeout = 5000;
    }
    client.getHttpConnectionManager().closeIdleConnections(idleConnectionTimeout);
    client.getHttpConnectionManager().getParams().setConnectionTimeout(idleConnectionTimeout);
    // create the initial state
    HttpState initialState = new HttpState();
    if (cookies != null && cookies.length > 0) {
        for (int i = 0; i < cookies.length; i++) {
            Cookie c = cookies[i];
            org.apache.commons.httpclient.Cookie mycookie = new org.apache.commons.httpclient.Cookie(
                    c.getDomain(), c.getName(), c.getValue(), c.getPath(), c.getMaxAge(), c.getSecure());
            initialState.addCookie(mycookie);
        }
        client.setState(initialState);
    }
    // set some defaults
    client.getParams().setParameter(HttpMethodParams.USER_AGENT,
            "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1");
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    client.getParams().setBooleanParameter(HttpMethodParams.SINGLE_COOKIE_HEADER, true);
    wrapper = new HttpClientWrapper(client, connectionManager, initialState);
    return wrapper;
}

From source file:org.sakaiproject.util.RequestFilter.java

protected void addCookie(HttpServletResponse res, Cookie cookie) {

    if (!m_cookieHttpOnly) {
        // Use the standard servlet mechanism for setting the cookie
        res.addCookie(cookie);//from  w w w.  ja v  a 2 s. c  o  m
    } else {
        // Set the cookie manually

        StringBuffer sb = new StringBuffer();

        ServerCookie.appendCookieValue(sb, cookie.getVersion(), cookie.getName(), cookie.getValue(),
                cookie.getPath(), cookie.getDomain(), cookie.getComment(), cookie.getMaxAge(),
                cookie.getSecure(), m_cookieHttpOnly);

        res.addHeader("Set-Cookie", sb.toString());
    }
    return;
}

From source file:org.sonar.server.authentication.CsrfVerifierTest.java

@Test
public void verify_state() throws Exception {
    String state = "state";
    when(request.getCookies()).thenReturn(new Cookie[] { new Cookie("OAUTHSTATE", sha256Hex(state)) });
    when(request.getParameter("state")).thenReturn(state);

    underTest.verifyState(request, response);

    verify(response).addCookie(cookieArgumentCaptor.capture());
    Cookie updatedCookie = cookieArgumentCaptor.getValue();
    assertThat(updatedCookie.getName()).isEqualTo("OAUTHSTATE");
    assertThat(updatedCookie.getValue()).isNull();
    assertThat(updatedCookie.getPath()).isEqualTo("/");
    assertThat(updatedCookie.getMaxAge()).isEqualTo(0);
}

From source file:org.sonar.server.authentication.CsrfVerifierTest.java

private void verifyCookie(Cookie cookie, boolean isSecured) {
    assertThat(cookie.getName()).isEqualTo("OAUTHSTATE");
    assertThat(cookie.getValue()).isNotEmpty();
    assertThat(cookie.getPath()).isEqualTo("/");
    assertThat(cookie.isHttpOnly()).isTrue();
    assertThat(cookie.getMaxAge()).isEqualTo(-1);
    assertThat(cookie.getSecure()).isEqualTo(isSecured);
}

From source file:org.sonar.server.authentication.OAuthCsrfVerifierTest.java

@Test
public void verify_state() throws Exception {
    String state = "state";
    when(request.getCookies()).thenReturn(new Cookie[] { new Cookie("OAUTHSTATE", sha256Hex(state)) });
    when(request.getParameter("state")).thenReturn(state);

    underTest.verifyState(request, response, identityProvider);

    verify(response).addCookie(cookieArgumentCaptor.capture());
    Cookie updatedCookie = cookieArgumentCaptor.getValue();
    assertThat(updatedCookie.getName()).isEqualTo("OAUTHSTATE");
    assertThat(updatedCookie.getValue()).isNull();
    assertThat(updatedCookie.getPath()).isEqualTo("/");
    assertThat(updatedCookie.getMaxAge()).isEqualTo(0);
}

From source file:org.sonar.server.authentication.OAuthCsrfVerifierTest.java

private void verifyCookie(Cookie cookie) {
    assertThat(cookie.getName()).isEqualTo("OAUTHSTATE");
    assertThat(cookie.getValue()).isNotEmpty();
    assertThat(cookie.getPath()).isEqualTo("/");
    assertThat(cookie.isHttpOnly()).isTrue();
    assertThat(cookie.getMaxAge()).isEqualTo(-1);
    assertThat(cookie.getSecure()).isFalse();
}

From source file:org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServicesTests.java

@Test
public void autoLoginReturnsNullForExpiredCookieAndClearsCookie() throws Exception {
    Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, generateCorrectCookieContentForToken(
            System.currentTimeMillis() - 1000000, "someone", "password", "key"));
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setCookies(cookie);/*from  w  w w.j a v  a  2s .  c  o  m*/

    MockHttpServletResponse response = new MockHttpServletResponse();

    assertThat(services.autoLogin(request, response)).isNull();
    Cookie returnedCookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
    assertThat(returnedCookie).isNotNull();
    assertThat(returnedCookie.getMaxAge()).isZero();
}

From source file:org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServicesTests.java

@Test
public void autoLoginReturnsNullAndClearsCookieIfMissingThreeTokensInCookieValue() throws Exception {
    Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
            new String(Base64.encodeBase64("x".getBytes())));
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setCookies(cookie);//  ww  w  . java2s  .c o m

    MockHttpServletResponse response = new MockHttpServletResponse();
    assertThat(services.autoLogin(request, response)).isNull();

    Cookie returnedCookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
    assertThat(returnedCookie).isNotNull();
    assertThat(returnedCookie.getMaxAge()).isZero();
}

From source file:org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServicesTests.java

@Test
public void autoLoginClearsNonBase64EncodedCookie() throws Exception {
    Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, "NOT_BASE_64_ENCODED");
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setCookies(cookie);/*from ww  w  .j  a va2 s.  c  om*/

    MockHttpServletResponse response = new MockHttpServletResponse();
    assertThat(services.autoLogin(request, response)).isNull();

    Cookie returnedCookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
    assertThat(returnedCookie).isNotNull();
    assertThat(returnedCookie.getMaxAge()).isZero();
}