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.google.acre.script.AcreCookie.java

public AcreCookie(Cookie servlet_cookie) {
    name = servlet_cookie.getName();/*  w  w w  . j  av  a2 s .c o  m*/
    value = servlet_cookie.getValue();
    domain = servlet_cookie.getDomain();
    path = servlet_cookie.getPath();
    secure = servlet_cookie.getSecure();
    max_age = servlet_cookie.getMaxAge();
}

From source file:ed.net.CookieJar.java

/**
 * Checks if the cookie has expired/*from ww  w .ja v  a 2 s . com*/
 * @param cookie the cookie to check
 * @return true, if the cookie has an expiration date that has been reached
 */
private boolean isExpired(Cookie cookie) {
    if (cookie.getMaxAge() < 0)
        return false;

    if (cookie.getMaxAge() == 0)
        return true;

    Date createDate = _creationDates.get(cookie.getName());
    Date expirationDate = new Date(createDate.getTime() + (cookie.getMaxAge() * 1000));

    return expirationDate.getTime() <= System.currentTimeMillis();
}

From source file:net.fenyo.mail4hotspot.web.BrowserServlet.java

@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException {
    // debug informations
    log.debug("doGet");
    log.debug("context path: " + request.getContextPath());
    log.debug("character encoding: " + request.getCharacterEncoding());
    log.debug("content length: " + request.getContentLength());
    log.debug("content type: " + request.getContentType());
    log.debug("local addr: " + request.getLocalAddr());
    log.debug("local name: " + request.getLocalName());
    log.debug("local port: " + request.getLocalPort());
    log.debug("method: " + request.getMethod());
    log.debug("path info: " + request.getPathInfo());
    log.debug("path translated: " + request.getPathTranslated());
    log.debug("protocol: " + request.getProtocol());
    log.debug("query string: " + request.getQueryString());
    log.debug("requested session id: " + request.getRequestedSessionId());
    log.debug("Host header: " + request.getServerName());
    log.debug("servlet path: " + request.getServletPath());
    log.debug("request URI: " + request.getRequestURI());
    @SuppressWarnings("unchecked")
    final Enumeration<String> header_names = request.getHeaderNames();
    while (header_names.hasMoreElements()) {
        final String header_name = header_names.nextElement();
        log.debug("header name: " + header_name);
        @SuppressWarnings("unchecked")
        final Enumeration<String> header_values = request.getHeaders(header_name);
        while (header_values.hasMoreElements())
            log.debug("  " + header_name + " => " + header_values.nextElement());
    }//from w w  w .  ja v a  2  s.  com
    if (request.getCookies() != null)
        for (Cookie cookie : request.getCookies()) {
            log.debug("cookie:");
            log.debug("cookie comment: " + cookie.getComment());
            log.debug("cookie domain: " + cookie.getDomain());
            log.debug("cookie max age: " + cookie.getMaxAge());
            log.debug("cookie name: " + cookie.getName());
            log.debug("cookie path: " + cookie.getPath());
            log.debug("cookie value: " + cookie.getValue());
            log.debug("cookie version: " + cookie.getVersion());
            log.debug("cookie secure: " + cookie.getSecure());
        }
    @SuppressWarnings("unchecked")
    final Enumeration<String> parameter_names = request.getParameterNames();
    while (parameter_names.hasMoreElements()) {
        final String parameter_name = parameter_names.nextElement();
        log.debug("parameter name: " + parameter_name);
        final String[] parameter_values = request.getParameterValues(parameter_name);
        for (final String parameter_value : parameter_values)
            log.debug("  " + parameter_name + " => " + parameter_value);
    }

    // parse request

    String target_scheme = null;
    String target_host;
    int target_port;

    // request.getPathInfo() is url decoded
    final String[] path_info_parts = request.getPathInfo().split("/");
    if (path_info_parts.length >= 2)
        target_scheme = path_info_parts[1];
    if (path_info_parts.length >= 3) {
        target_host = path_info_parts[2];
        try {
            if (path_info_parts.length >= 4)
                target_port = new Integer(path_info_parts[3]);
            else
                target_port = 80;
        } catch (final NumberFormatException ex) {
            log.warn(ex);
            target_port = 80;
        }
    } else {
        target_scheme = "http";
        target_host = "www.google.com";
        target_port = 80;
    }

    log.debug("remote URL: " + target_scheme + "://" + target_host + ":" + target_port);

    // create forwarding request

    final URL target_url = new URL(target_scheme + "://" + target_host + ":" + target_port);
    final HttpURLConnection target_connection = (HttpURLConnection) target_url.openConnection();

    // be transparent for accept-language headers
    @SuppressWarnings("unchecked")
    final Enumeration<String> accepted_languages = request.getHeaders("accept-language");
    while (accepted_languages.hasMoreElements())
        target_connection.setRequestProperty("Accept-Language", accepted_languages.nextElement());

    // be transparent for accepted headers
    @SuppressWarnings("unchecked")
    final Enumeration<String> accepted_content = request.getHeaders("accept");
    while (accepted_content.hasMoreElements())
        target_connection.setRequestProperty("Accept", accepted_content.nextElement());

}

From source file:com.anjz.util.CookieUtils.java

private static void getCookieHeaderValue(final Cookie cookie, final StringBuffer buf, final boolean httpOnly) {
    final int version = cookie.getVersion();

    // this part is the same for all cookies

    String name = cookie.getName(); // Avoid NPE on malformed cookies
    if (name == null) {
        name = "";
    }/*from   w  w w.  ja  v a2  s .  com*/
    String value = cookie.getValue();
    if (value == null) {
        value = "";
    }

    buf.append(name);
    buf.append("=");

    maybeQuote(version, buf, value);

    // add version 1 specific information
    if (version == 1) {
        // Version=1 ... required
        buf.append("; Version=1");

        // Comment=comment
        if (cookie.getComment() != null) {
            buf.append("; Comment=");
            maybeQuote(version, buf, cookie.getComment());
        }
    }

    // add domain information, if present

    if (cookie.getDomain() != null) {
        buf.append("; Domain=");
        maybeQuote(version, buf, cookie.getDomain());
    }

    // Max-Age=secs/Discard ... or use old "Expires" format
    if (cookie.getMaxAge() >= 0) {
        if (version == 0) {
            buf.append("; Expires=");
            SimpleDateFormat dateFormat = new SimpleDateFormat(OLD_COOKIE_PATTERN, LOCALE_US);
            dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); //GMT?
            if (cookie.getMaxAge() == 0) {
                dateFormat.format(new Date(10000), buf, new FieldPosition(0));
            } else {
                dateFormat.format(new Date(System.currentTimeMillis() + cookie.getMaxAge() * 1000L), buf,
                        new FieldPosition(0));
            }
        } else {
            buf.append("; Max-Age=");
            buf.append(cookie.getMaxAge());
        }
    } else if (version == 1) {
        buf.append("; Discard");
    }

    // Path=path
    if (cookie.getPath() != null) {
        buf.append("; Path=");
        maybeQuote(version, buf, cookie.getPath());
    }

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

    // HttpOnly
    if (httpOnly) {
        buf.append("; HttpOnly");
    }
}

From source file:ed.net.CookieJar.java

public List<Cookie> clean(boolean removeNonpersistent) {
    List<Cookie> deadCookies = new ArrayList<Cookie>();

    for (Cookie c : _cookies.values()) {
        if (isExpired(c))
            deadCookies.add(c);/*from   w w  w.j  a  va 2  s.co m*/

        if (removeNonpersistent && c.getMaxAge() < 0)
            deadCookies.add(c);
    }
    for (Cookie deadCookie : deadCookies)
        _cookies.remove(deadCookie.getName());

    return deadCookies;
}

From source file:com.pureinfo.tgirls.servlet.TestServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    System.out.println("=================parameter from request====================");
    Enumeration ereq = request.getParameterNames();
    while (ereq.hasMoreElements()) {
        String name = (String) ereq.nextElement();
        System.out.println(name + "[" + request.getParameter(name) + "]");
    }//from   w ww.j av  a  2s .c o  m
    System.out.println("=================end====================");

    String userTabaoId = request.getParameter("id");

    if (StringUtils.isEmpty(userTabaoId)) {
        userTabaoId = "1";
    }
    try {
        IUserMgr mgr = (IUserMgr) ArkContentHelper.getContentMgrOf(User.class);
        User _loginUser = mgr.getUserByTaobaoId(userTabaoId);

        addCookie(_loginUser, request, response);

        Cookie[] cookies = request.getCookies();

        if (cookies == null) {
            System.out.println("=====cookie is null=======");
        } else {
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                System.out.println("cookie[" + i + "]:[" + cookie.getName() + ":" + cookie.getValue() + "("
                        + cookie.getMaxAge() + ")]");
            }

        }

        //request.getSession().setAttribute(ArkHelper.ATTR_LOGIN_USER, _loginUser);

        System.out.println("loginuser:" + _loginUser);

        response.sendRedirect(request.getContextPath());
        return;
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace(System.err);
    }

}

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

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

    HttpServletRequest httpReq = (HttpServletRequest) request;
    HttpServletResponse httpRes = (HttpServletResponse) response;
    UrlExclusionList exclList = (UrlExclusionList) request.getServletContext()
            .getAttribute(SecurityConstant.CSRF_CHECK_URL_EXCL_LIST_ATTR_NAME);

    logger.debug("doFilter: request from IP address=" + httpReq.getRemoteAddr());

    if (httpReq.getSession(false) == null) {
        chain.doFilter(request, response);
        return;//from ww  w. j ava2 s.  c  o m
    }

    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 the user session for the salt cache, if none is present we
    // create one
    Cache<SecurityInfo, SecurityInfo> csrfPreventionSaltCache = (Cache<SecurityInfo, SecurityInfo>) httpReq
            .getSession().getAttribute(SecurityConstant.SALT_CACHE_ATTR_NAME);

    if (csrfPreventionSaltCache == null) {
        if (tokenTimeout == -1) {
            csrfPreventionSaltCache = CacheBuilder.newBuilder().maximumSize(1000).build();
        } else {
            csrfPreventionSaltCache = CacheBuilder.newBuilder().maximumSize(1000)
                    .expireAfterAccess(tokenTimeout, TimeUnit.SECONDS).build();
        }

        httpReq.getSession().setAttribute(SecurityConstant.SALT_CACHE_ATTR_NAME, csrfPreventionSaltCache);

        String nameSalt = RandomStringUtils.random(10, 0, 0, true, true, null, new SecureRandom());
        httpReq.getSession().setAttribute(SecurityConstant.SALT_PARAM_NAME, nameSalt);
    }

    // Generate the salt and store it in the users cache
    String salt = RandomStringUtils.random(20, 0, 0, true, true, null, new SecureRandom());

    String saltNameAttr = (String) httpReq.getSession().getAttribute(SecurityConstant.SALT_PARAM_NAME);
    SecurityInfo si = new SecurityInfo(saltNameAttr, salt);

    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);
            }
        }

        si.setRefererHost(refHeader);
    }

    logger.debug("doFilter: si=" + si.toString());

    csrfPreventionSaltCache.put(si, si);

    // Add the salt to the current request so it can be used
    // by the page rendered in this request
    httpReq.setAttribute(SecurityConstant.SALT_ATTR_NAME, si);

    // set CSRF cookie
    HttpSession session = httpReq.getSession(false);
    if (session != null && StringUtils.isNotBlank(csrfCookieName)) {

        if (logger.isDebugEnabled()) {
            Cookie[] cookies = httpReq.getCookies();
            // boolean cookiePresent = false;
            for (Cookie c : cookies) {
                String name = c.getName();
                logger.debug("doFilter: cookie domain=" + c.getDomain() + "|name=" + name + "|value="
                        + c.getValue() + "|path=" + c.getPath() + "|maxage=" + c.getMaxAge() + "|httpOnly="
                        + c.isHttpOnly());
                // if (csrfCookieName.equals(name)) {
                // cookiePresent = true;
                // break;
                // }
            }
        }
        // if (!cookiePresent) {
        byte[] hashSalt = new byte[32];
        SecureRandom sr = new SecureRandom();
        sr.nextBytes(hashSalt);

        String csrfHash = RandomStringUtils.random(64, 0, 0, true, true, null, sr);

        Cookie c = new Cookie(csrfCookieName, csrfHash);
        c.setMaxAge(1800);
        c.setSecure(false);
        c.setPath(httpReq.getContextPath());
        c.setHttpOnly(false);
        httpRes.addCookie(c);
        // session.setAttribute(SecurityConstant.CSRFCOOKIE_VALUE_PARAM,
        // hashStr);
        // }
    }

    chain.doFilter(request, response);
}

From source file:com.acc.storefront.security.cookie.EnhancedCookieGenerator.java

@Override
public void addCookie(final HttpServletResponse response, final String cookieValue) {
    super.addCookie(new HttpServletResponseWrapper(response) {
        @Override//from w  ww  .java  2  s. c  o m
        public void addCookie(final Cookie cookie) {
            setEnhancedCookiePath(cookie);

            if (isHttpOnly()) {
                // Custom code to write the cookie including the httpOnly flag
                final StringBuffer headerBuffer = new StringBuffer(100);
                ServerCookie.appendCookieValue(headerBuffer, cookie.getVersion(), cookie.getName(),
                        cookie.getValue(), cookie.getPath(), cookie.getDomain(), cookie.getComment(),
                        cookie.getMaxAge(), cookie.getSecure(), true);
                response.addHeader(HEADER_COOKIE, headerBuffer.toString());
            } else {
                // Write the cookie as normal
                super.addCookie(cookie);
            }
        }
    }, cookieValue);
}

From source file:org.iwethey.forums.web.HeaderInterceptor.java

/**
 * Load the request attributes with the User object (if authenticated)
 * and start time for the page for audit purposes.
 * <p>//  w  ww. j a v  a 2 s.  c  om
 * @param request The servlet request object.
 * @param response The servlet response object.
 * @param handler The request handler processing this request.
 */
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    Date now = new Date();
    request.setAttribute("now", now);

    long start = now.getTime();
    request.setAttribute("start", new Long(start));

    Integer id = (Integer) WebUtils.getSessionAttribute(request, USER_ID_ATTRIBUTE);

    User user = null;

    if (id == null) {
        user = (User) WebUtils.getSessionAttribute(request, USER_ATTRIBUTE);

        if (user == null) {
            user = new User("Anonymous");
            WebUtils.setSessionAttribute(request, USER_ATTRIBUTE, user);
        }
    } else {
        user = mUserManager.getUserById(id.intValue());
        user.setLastPresent(new Date());
        mUserManager.saveUserAttributes(user);
    }

    request.setAttribute("username", user.getNickname());
    request.setAttribute(USER_ATTRIBUTE, user);

    System.out.println("Local Address  = [" + request.getLocalAddr() + "]");
    System.out.println("Local Name     = [" + request.getLocalName() + "]");
    System.out.println("Remote Address = [" + request.getRemoteAddr() + "]");
    System.out.println("Remote Host    = [" + request.getRemoteHost() + "]");
    System.out.println("Remote Port    = [" + request.getRemotePort() + "]");
    System.out.println("Remote User    = [" + request.getRemoteUser() + "]");
    System.out.println("Context Path   = [" + request.getContextPath() + "]");
    System.out.println("====================");

    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            Cookie cookie = cookies[i];

            System.out.println("Cookie Domain = [" + cookie.getDomain() + "]");
            System.out.println("Cookie Name   = [" + cookie.getName() + "]");
            System.out.println("Cookie Value  = [" + cookie.getValue() + "]");
            System.out.println("Cookie Expire = [" + cookie.getMaxAge() + "]");
            System.out.println("====================");

            if ("iwt_cookie".equals(cookie.getName())) {
                cookie.setMaxAge(1000 * 60 * 60 * 24 * 30 * 6);
                response.addCookie(cookie);
            }
        }
    } else {
        System.out.println("No cookies were found in the request");
    }

    Cookie newCookie = new Cookie("iwt_cookie", "harrr2!");
    newCookie.setPath(request.getContextPath());
    newCookie.setDomain(request.getLocalName());
    newCookie.setMaxAge(1000 * 60 * 60 * 24 * 30 * 6);
    response.addCookie(newCookie);

    request.setAttribute(HEADER_IMAGE_ATTRIBUTE, "/images/iwethey-lrpd-small.png");

    return true;
}

From source file:ed.net.CookieJar.java

/**
 * Validates & adds cookies to this object
 * //from   ww  w.j a  va  2 s  . c  o  m
 * @param source the origin server of the cookie
 * @param cookie the being added 
 */
public void addCookie(URL source, Cookie cookie) {
    try {
        validate(source, cookie);
    } catch (MalformedCookieException e) {
        //TODO: invalid cookies
        return;
    } catch (IllegalArgumentException e) {
        //TODO: invalid cookies
        return;
    }

    if (cookie.getMaxAge() == 0) {
        remove(cookie.getName());
        return;
    } else {
        _cookies.put(cookie.getName(), cookie);
        _creationDates.put(cookie.getName(), new Date());
    }
}