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:com.meltmedia.cadmium.servlets.jersey.StatusService.java

@GET
@Path("/health")
@Produces("text/plain")
public String health(@Context HttpServletRequest request) {
    StringBuilder builder = new StringBuilder();
    builder.append("Server: " + request.getServerName() + "\n");
    builder.append("Scheme: " + request.getScheme() + "\n");
    builder.append("Port: " + request.getServerPort() + "\n");
    builder.append("ContextPath:  " + request.getContextPath() + "\n");
    builder.append("ServletPath: " + request.getServletPath() + "\n");
    builder.append("Uri: " + request.getRequestURI() + "\n");
    builder.append("Query: " + request.getQueryString() + "\n");
    Enumeration<?> headerNames = request.getHeaderNames();
    builder.append("Headers:\n");
    while (headerNames.hasMoreElements()) {
        String name = (String) headerNames.nextElement();
        Enumeration<?> headers = request.getHeaders(name);
        builder.append("  '" + name + "':\n");
        while (headers.hasMoreElements()) {
            String headerValue = (String) headers.nextElement();
            builder.append("    -" + headerValue + "\n");
        }/*from   ww  w.  ja  va 2s  .  c  om*/
    }
    if (request.getCookies() != null) {
        builder.append("Cookies:\n");
        for (Cookie cookie : request.getCookies()) {
            builder.append("  '" + cookie.getName() + "':\n");
            builder.append("    value: " + cookie.getValue() + "\n");
            builder.append("    domain: " + cookie.getDomain() + "\n");
            builder.append("    path: " + cookie.getPath() + "\n");
            builder.append("    maxAge: " + cookie.getMaxAge() + "\n");
            builder.append("    version: " + cookie.getVersion() + "\n");
            builder.append("    comment: " + cookie.getComment() + "\n");
            builder.append("    secure: " + cookie.getSecure() + "\n");
        }
    }
    return builder.toString();
}

From source file:com.versatus.jwebshield.filter.SecurityFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    // Assume its HTTP
    HttpServletRequest httpReq = (HttpServletRequest) request;

    String reqInfo = "J-WebShield Alert: CSRF attack detected! request URL="
            + httpReq.getRequestURL().toString() + "| from IP address=" + httpReq.getRemoteAddr();

    logger.debug("doFilter: IP address=" + httpReq.getRemoteAddr());
    logger.debug("doFilter: pathInfo=" + httpReq.getPathInfo());
    logger.debug("doFilter: queryString=" + httpReq.getQueryString());
    logger.debug("doFilter: requestURL=" + httpReq.getRequestURL().toString());
    logger.debug("doFilter: method=" + httpReq.getMethod());
    logger.debug("doFilter: Origin=" + httpReq.getHeader("Origin"));
    logger.info("doFilter: Referer=" + httpReq.getHeader("Referer"));
    logger.info("doFilter: " + csrfHeaderName + "=" + httpReq.getHeader(csrfHeaderName));

    UrlExclusionList exclList = (UrlExclusionList) request.getServletContext()
            .getAttribute(SecurityConstant.CSRF_CHECK_URL_EXCL_LIST_ATTR_NAME);
    HttpSession session = httpReq.getSession(false);
    if (session == null) {
        chain.doFilter(request, response);
        return;//  w  w  w.j  av a2 s  .  c om
    }

    logger.debug("doFilter: matching " + httpReq.getRequestURI() + " to exclusions list "
            + exclList.getExclusionMap());

    try {
        if (!exclList.isEmpty() && exclList.isMatch(httpReq.getRequestURI())) {
            chain.doFilter(request, response);
            return;
        }
    } catch (Exception e) {
        logger.error("doFilter", e);
    }
    // check CSRF cookie/header
    boolean csrfHeaderPassed = false;
    String rawCsrfHeaderVal = httpReq.getHeader(csrfHeaderName);
    if (useCsrfToken && StringUtils.isNotBlank(rawCsrfHeaderVal)) {
        String csrfHeader = StringUtils.strip(httpReq.getHeader(csrfHeaderName), "\"");
        logger.debug("doFilter: csrfHeader after decoding" + csrfHeader);
        Cookie[] cookies = httpReq.getCookies();
        for (Cookie c : cookies) {
            String name = c.getName();

            if (StringUtils.isNotBlank(csrfCookieName) && csrfCookieName.equals(name)) {

                logger.debug("doFilter: cookie domain=" + c.getDomain() + "|name=" + name + "|value="
                        + c.getValue() + "|path=" + c.getPath() + "|maxage=" + c.getMaxAge() + "|httpOnly="
                        + c.isHttpOnly());

                logger.debug("doFilter: string comp:" + StringUtils.difference(csrfHeader, c.getValue()));

                if (StringUtils.isNotBlank(csrfHeader) && csrfHeader.equals(c.getValue())) {

                    csrfHeaderPassed = true;
                    logger.info("Header " + csrfHeaderName + " value matches the cookie " + csrfCookieName);
                    break;
                } else {
                    logger.info(
                            "Header " + csrfHeaderName + " value does not match the cookie " + csrfCookieName);
                }
            }

        }
        // String csrfCookieVal = (String) session
        // .getAttribute(SecurityConstant.CSRFCOOKIE_VALUE_PARAM);
        // if (csrfCookieVal != null && csrfCookieVal.equals(csrfHeader)) {
        // // chain.doFilter(request, response);
        // // return;
        // csrfHeaderPassed = true;
        // } else {
        // // logger.info(reqInfo);
        // // sendSecurityReject(response);
        // }
    }

    if (useCsrfToken && csrfHeaderPassed) {
        chain.doFilter(request, response);
        return;
    }

    // Validate that the salt is in the cache
    Cache<SecurityInfo, SecurityInfo> csrfPreventionSaltCache = (Cache<SecurityInfo, SecurityInfo>) httpReq
            .getSession().getAttribute(SecurityConstant.SALT_CACHE_ATTR_NAME);

    if (csrfPreventionSaltCache != null) {
        // Get the salt sent with the request
        String saltName = (String) httpReq.getSession().getAttribute(SecurityConstant.SALT_PARAM_NAME);

        logger.debug("doFilter: csrf saltName=" + saltName);

        if (saltName != null) {

            String salt = httpReq.getParameter(saltName);

            logger.debug("doFilter: csrf salt=" + salt);

            if (salt != null) {

                SecurityInfo si = new SecurityInfo(saltName, salt);

                logger.debug("doFilter: csrf token=" + csrfPreventionSaltCache.getIfPresent(si));

                SecurityInfo cachedSi = csrfPreventionSaltCache.getIfPresent(si);
                if (cachedSi != null) {
                    // csrfPreventionSaltCache.invalidate(si);
                    if (SecurityTokenFilter.checkReferer) {
                        String refHeader = StringUtils.defaultString(httpReq.getHeader("Referer"));
                        logger.debug("doFilter: refHeader=" + refHeader);
                        if (StringUtils.isNotBlank(refHeader)) {
                            try {
                                URL refUrl = new URL(refHeader);
                                refHeader = refUrl.getHost();
                            } catch (MalformedURLException mex) {
                                logger.debug("doFilter: parsing referer header failed", mex);
                            }
                        }
                        if (!cachedSi.getRefererHost().isEmpty()
                                && !refHeader.equalsIgnoreCase(cachedSi.getRefererHost())) {
                            logger.info("Potential CSRF detected - Referer host does not match orignal! "
                                    + refHeader + " != " + cachedSi.getRefererHost());
                            sendSecurityReject(response);
                        }
                    }

                    chain.doFilter(request, response);
                } else {
                    logger.info(reqInfo);
                    sendSecurityReject(response);
                }
            } else if (httpMethodMatch(httpReq.getMethod())) {
                // let flow through
                chain.doFilter(request, response);
            } else {
                logger.info(reqInfo);
                sendSecurityReject(response);
            }
        }
    } else {
        chain.doFilter(request, response);
    }

}

From source file:com.xpn.xwiki.stats.impl.StatsUtil.java

/**
 * Create a new visit cookie and return it.
 * /*  ww w. j  av  a2 s  .com*/
 * @param context the XWiki context.
 * @return the newly created cookie.
 * @since 1.4M1
 */
protected static Cookie addCookie(XWikiContext context) {
    Cookie cookie = new Cookie(COOKPROP_VISITID, RandomStringUtils.randomAlphanumeric(32).toUpperCase());
    cookie.setPath("/");

    int time = (int) (getCookieExpirationDate().getTime() - (new Date()).getTime()) / 1000;
    cookie.setMaxAge(time);

    String cookieDomain = null;
    getCookieDomains(context);
    if (cookieDomains != null) {
        String servername = context.getRequest().getServerName();
        for (int i = 0; i < cookieDomains.length; i++) {
            if (servername.indexOf(cookieDomains[i]) != -1) {
                cookieDomain = cookieDomains[i];
                break;
            }
        }
    }

    if (cookieDomain != null) {
        cookie.setDomain(cookieDomain);
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Setting cookie " + cookie.getValue() + " for name " + cookie.getName() + " with domain "
                + cookie.getDomain() + " and path " + cookie.getPath() + " and maxage " + cookie.getMaxAge());
    }

    context.getResponse().addCookie(cookie);

    return cookie;
}

From source file:com.nesscomputing.httpclient.factory.httpclient4.ApacheHttpClient4Factory.java

private <T> void contributeCookies(final DefaultHttpClient httpClient,
        final HttpClientRequest<T> httpClientRequest) {
    final List<Cookie> cookies = httpClientRequest.getCookies();

    if (CollectionUtils.isNotEmpty(cookies)) {
        final CookieStore cookieStore = new BasicCookieStore();
        for (final Cookie cookie : cookies) {
            final BasicClientCookie httpCookie = new BasicClientCookie(cookie.getName(), cookie.getValue());

            final int maxAge = cookie.getMaxAge();

            if (maxAge > 0) {
                final Date expire = new Date(System.currentTimeMillis() + maxAge * 1000L);
                httpCookie.setExpiryDate(expire);
                httpCookie.setAttribute(ClientCookie.MAX_AGE_ATTR, Integer.toString(maxAge));
            }/*from w w w .ja  v  a2s  . co m*/

            httpCookie.setVersion(1);
            httpCookie.setPath(cookie.getPath());
            httpCookie.setDomain(cookie.getDomain());
            httpCookie.setSecure(cookie.getSecure());

            LOG.debug("Adding cookie to the request: '%s'", httpCookie);
            cookieStore.addCookie(httpCookie);
        }
        httpClient.setCookieStore(cookieStore);
    } else {
        LOG.debug("No cookies found.");
        httpClient.setCookieStore(null);
    }
}

From source file:com.hypersocket.netty.HttpResponseServletWrapper.java

@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());
    }/*  w  w  w  .j ava2 s.c  o m*/
    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());

}

From source file:org.craftercms.security.processors.impl.AddSecurityCookiesProcessorTest.java

@Test
public void testAddCookiesLoggedOut() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    RequestContext context = new RequestContext(request, response);
    RequestSecurityProcessor flushResponseProcessor = new RequestSecurityProcessor() {

        @Override//  w  w  w .j  av  a  2 s .c o  m
        public void processRequest(RequestContext context, RequestSecurityProcessorChain processorChain)
                throws Exception {
            context.getResponse().getOutputStream().flush();
        }

    };

    Cookie ticketCookie = new Cookie(SecurityUtils.TICKET_COOKIE_NAME, new ObjectId().toString());
    Cookie profileLastModifiedCookie = new Cookie(SecurityUtils.PROFILE_LAST_MODIFIED_COOKIE_NAME,
            String.valueOf(System.currentTimeMillis()));

    request.setCookies(ticketCookie, profileLastModifiedCookie);

    RequestSecurityProcessorChain chain = new RequestSecurityProcessorChainImpl(
            Arrays.asList(processor, flushResponseProcessor).iterator());

    processor.processRequest(context, chain);

    ticketCookie = response.getCookie(SecurityUtils.TICKET_COOKIE_NAME);

    assertNotNull(ticketCookie);
    assertEquals(null, ticketCookie.getValue());
    assertEquals(0, ticketCookie.getMaxAge());

    profileLastModifiedCookie = response.getCookie(SecurityUtils.PROFILE_LAST_MODIFIED_COOKIE_NAME);

    assertNotNull(profileLastModifiedCookie);
    assertEquals(null, profileLastModifiedCookie.getValue());
    assertEquals(0, profileLastModifiedCookie.getMaxAge());
}

From source file:fedroot.dacs.http.DacsCookie.java

/** 
 * Creates a new instance of DacsCookie from a javax.servlet.http.net.Cookie
 *//*  w ww  .  j a va2s.  c o  m*/
public DacsCookie(String domain, javax.servlet.http.Cookie cookie) throws DacsRuntimeException {
    //        super(federationDomain, jcookie.getName(),jcookie.getValue(),"/", jcookie.getMaxAge(),jcookie.getSecure());
    super(cookie.getName(), cookie.getValue());

    if (!isDacsCookie(cookie)) {
        throw new DacsRuntimeException("invalid DACS cookie: " + cookie.getName());
    }

    // the domain of a DACS federation never refers to a single host
    // if there is no leading dot we add one to the domain,
    // so a cookie with domain "foo.com" becomes a DACS
    // cookie with domain ".foo.com" causing user agents to send the cookie
    // to hosts foo.com, bar.foo.com, baz.foo.com etc

    setVersion(1);
    if (domain.startsWith(".")) {
        setDomain(domain);
    } else {
        setDomain("." + domain);
    }
    setPath("/");

    if (cookie.getMaxAge() == -1) {
    } else {
        Date expires = new Date();
        expires.setTime(expires.getTime() + cookie.getMaxAge());
        setExpiryDate(expires);
    }

    setSecure(cookie.getSecure());
}

From source file:com.liferay.portal.util.HttpImpl.java

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());/*from   w w  w. j  a  v  a  2  s.  c o m*/

    commonsCookie.setVersion(cookie.getVersion());

    return commonsCookie;
}

From source file:CookieServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {

    Cookie cookie = null;
    Cookie[] cookies = request.getCookies();
    boolean newCookie = false;

    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equals("mycookie")) {
                cookie = cookies[i];/* w  w w  .  j a v a  2 s  .  co m*/
            }
        }
    }
    if (cookie == null) {
        newCookie = true;
        int maxAge;
        try {
            maxAge = new Integer(getServletContext().getInitParameter("cookie-age")).intValue();
        } catch (Exception e) {
            maxAge = -1;
        }

        cookie = new Cookie("mycookie", "" + getNextCookieValue());
        cookie.setPath(request.getContextPath());
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();

    out.println("<html>");
    out.println("<head>");
    out.println("<title>Cookie info</title>");
    out.println("</head>");
    out.println("<body>");

    out.println("<h2> Information about the cookie named \"mycookie\"</h2>");

    out.println("Cookie value: " + cookie.getValue() + "<br>");
    if (newCookie) {
        out.println("Cookie Max-Age: " + cookie.getMaxAge() + "<br>");
        out.println("Cookie Path: " + cookie.getPath() + "<br>");
    }

    out.println("</body>");
    out.println("</html>");

    out.close();
}