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.ireland.jnetty.http.HttpServletRequestImpl.java

/**
 * Extracte cookies.//from  w  w  w  .jav  a 2  s  .com
 */
protected void extracteCookie() {
    _cookiesExtracted = true;

    // Decode the cookie.
    String cookieString = headers.get(HttpHeaders.Names.COOKIE);
    if (cookieString != null) {
        Set<io.netty.handler.codec.http.Cookie> _cookies = CookieDecoder.decode(cookieString);

        this.cookies = new Cookie[_cookies.size()];

        int i = 0;

        // Convent netty's Cookie to Servlet's Cookie
        for (io.netty.handler.codec.http.Cookie c : _cookies) {
            Cookie cookie = new Cookie(c.getName(), c.getValue());

            cookie.setComment(c.getComment());

            if (c.getDomain() != null)
                cookie.setDomain(c.getDomain());

            cookie.setHttpOnly(c.isHttpOnly());
            cookie.setMaxAge((int) c.getMaxAge());
            cookie.setPath(c.getPath());
            cookie.setSecure(c.isSecure());
            cookie.setVersion(c.getVersion());

            this.cookies[i] = cookie;
            i++;
        }
    }
}

From source file:org.jasig.portal.portlet.container.services.SessionOnlyPortletCookieImpl.java

SessionOnlyPortletCookieImpl(Cookie cookie) {
    this.name = cookie.getName();
    this.value = cookie.getValue();
    this.comment = cookie.getComment();
    this.domain = cookie.getDomain();
    this.path = cookie.getPath();
    this.version = cookie.getVersion();
    this.secure = cookie.getSecure();

    setMaxAge(cookie.getMaxAge());
}

From source file:org.jasig.portal.portlet.container.services.SessionOnlyPortletCookieImpl.java

@Override
public void updateFromCookie(Cookie cookie) {
    this.setComment(cookie.getComment());
    this.setDomain(cookie.getDomain());
    this.setExpires(DateUtils.addSeconds(new Date(), cookie.getMaxAge()));
    this.setPath(cookie.getPath());
    this.setSecure(cookie.getSecure());
    this.setValue(cookie.getValue());
}

From source file:org.jsecurity.web.attr.CookieAttribute.java

public T onRetrieveValue(ServletRequest request, ServletResponse response) {
    T value = null;/*w  w  w .ja v  a  2 s .c o  m*/

    String stringValue;
    Cookie cookie = getCookie(toHttp(request), getName());
    if (cookie != null && cookie.getMaxAge() != 0) {
        stringValue = cookie.getValue();
        if (log.isInfoEnabled()) {
            log.info("Found string value [" + stringValue + "] from HttpServletRequest Cookie [" + getName()
                    + "]");
        }
        value = fromStringValue(stringValue);
    } else {
        if (log.isDebugEnabled()) {
            log.debug("No value found in request Cookies under cookie name [" + getName() + "]");
        }
    }

    return value;
}

From source file:org.nuxeo.ecm.platform.ui.web.auth.cleartrust.ClearTrustAuthenticator.java

protected void displayCookieInformation(Cookie[] cookies) {
    log.debug(">>>>>>>>>>>>> Here are the cookies: ");
    for (Cookie cookie : cookies) {
        log.debug("displayCookieInformation cookie name: [" + cookie.getName() + "] path: [" + cookie.getPath()
                + "] domain: " + cookie.getDomain() + " max age: " + cookie.getMaxAge() + " value: ["
                + cookie.getValue() + "]");
    }/*from   w ww .  j a v a 2 s  . c  o  m*/
}

From source file:org.opencms.flex.CmsFlexResponse.java

/**
 * Method overloaded from the standard HttpServletRequest API.<p>
 *
 * Cookies must be set directly as a header, otherwise they might not be set
 * in the super class.<p>// w  w w  .j a  va  2s.c  om
 *
 * @see javax.servlet.http.HttpServletResponseWrapper#addCookie(javax.servlet.http.Cookie)
 */
@Override
public void addCookie(Cookie cookie) {

    if (cookie == null) {
        throw new CmsIllegalArgumentException(Messages.get().container(Messages.ERR_ADD_COOKIE_0));
    }

    StringBuffer header = new StringBuffer(128);

    // name and value
    header.append(cookie.getName());
    header.append('=');
    header.append(cookie.getValue());

    // add version 1 / RFC 2109 specific information
    if (cookie.getVersion() == 1) {
        header.append("; Version=1");

        // comment
        if (cookie.getComment() != null) {
            header.append("; Comment=");
            header.append(cookie.getComment());
        }
    }

    // domain
    if (cookie.getDomain() != null) {
        header.append("; Domain=");
        header.append(cookie.getDomain());
    }

    // max-age / expires
    if (cookie.getMaxAge() >= 0) {
        if (cookie.getVersion() == 0) {
            // old Netscape format
            header.append("; Expires=");
            long time;
            if (cookie.getMaxAge() == 0) {
                time = 10000L;
            } else {
                time = System.currentTimeMillis() + (cookie.getMaxAge() * 1000L);
            }
            header.append(CmsDateUtil.getOldCookieDate(time));
        } else {
            // new RFC 2109 format 
            header.append("; Max-Age=");
            header.append(cookie.getMaxAge());
        }
    }

    // path
    if (cookie.getPath() != null) {
        header.append("; Path=");
        header.append(cookie.getPath());
    }

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

    addHeader("Set-Cookie", header.toString());
}

From source file:org.opensubsystems.core.util.servlet.WebUtils.java

/**
 * Create debug string containing all parameter names and their values from
 * the request, all attributes, all cookies and other data characterizing the
 * request.//from   w w w .j a v  a  2 s . co m
 *
 * @param  hsrqRequest - the servlet request.
 * @return String - debug string containing all parameter names and their
 *                  values from the request
 */
public static String debug(HttpServletRequest hsrqRequest) {
    Enumeration enumNames;
    Enumeration enumValues;
    Iterator iterValues;
    String strName;
    String[] arValues;
    Cookie[] arCookies;
    int iIndex;
    Map<String, String[]> mpParamMap;
    StringBuilder sbfReturn = new StringBuilder();

    sbfReturn.append("HttpServletRequest=[");
    sbfReturn.append("\nRemoteAddress=");
    sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getRemoteAddr()));
    sbfReturn.append(";");
    sbfReturn.append("\nRemotePort=");
    sbfReturn.append(hsrqRequest.getRemotePort());
    sbfReturn.append(";");
    sbfReturn.append("\nRemoteHost=");
    sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getRemoteHost()));
    sbfReturn.append(";");
    sbfReturn.append("\nRemoteUser=");
    sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getRemoteUser()));
    sbfReturn.append(";");
    sbfReturn.append("\nFullURL=");
    sbfReturn.append(getFullRequestURL(hsrqRequest));
    sbfReturn.append(";");
    sbfReturn.append("\nContextPath=");
    sbfReturn.append(hsrqRequest.getContextPath());
    sbfReturn.append(";");
    sbfReturn.append("\nServletPath=");
    sbfReturn.append(hsrqRequest.getServletPath());
    sbfReturn.append(";");
    sbfReturn.append("\nPathInfo =");
    sbfReturn.append(hsrqRequest.getPathInfo());
    sbfReturn.append(";");
    sbfReturn.append("\nRequestURI=");
    sbfReturn.append(hsrqRequest.getRequestURI());
    sbfReturn.append(";");
    sbfReturn.append("\nRequestURL=");
    sbfReturn.append(hsrqRequest.getRequestURL());
    sbfReturn.append(";");
    sbfReturn.append("\nMethod=");
    sbfReturn.append(hsrqRequest.getMethod());
    sbfReturn.append(";");
    sbfReturn.append("\nAuthenticationType=");
    sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getAuthType()));
    sbfReturn.append(";");
    sbfReturn.append("\nCharacterEncoding=");
    sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getCharacterEncoding()));
    sbfReturn.append(";");
    sbfReturn.append("\nContentType=");
    sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getContentType()));
    sbfReturn.append(";");
    sbfReturn.append("\nMultiPart=");
    sbfReturn.append(ServletFileUpload.isMultipartContent(hsrqRequest));
    sbfReturn.append(";");

    // Parameters ////////////////////////////////////////////////////////////

    try {
        Map.Entry<String, String[]> entry;

        // Use getParameterMap rather than request.getParameterNames since it 
        // correctly handles multipart requests
        mpParamMap = WebParamUtils.getParameterMap("WebUtils: ", hsrqRequest);
        for (iterValues = mpParamMap.entrySet().iterator(); iterValues.hasNext();) {
            entry = (Map.Entry<String, String[]>) iterValues.next();
            strName = entry.getKey();
            arValues = entry.getValue();
            sbfReturn.append("\nParam=");
            sbfReturn.append(strName);
            sbfReturn.append(" values=");
            for (iIndex = 0; iIndex < arValues.length; iIndex++) {
                sbfReturn.append(arValues[iIndex]);
                if (iIndex < (arValues.length - 1)) {
                    sbfReturn.append(";");
                }
            }
            if (iterValues.hasNext()) {
                sbfReturn.append(";");
            }
        }
    } catch (OSSInvalidDataException ex) {
        sbfReturn.append("<Cannot access parameter map of the request>");
        s_logger.log(Level.SEVERE, "Cannot access parameter map of the request", ex);
    }

    // Uploaded files ////////////////////////////////////////////////////////

    if (ServletFileUpload.isMultipartContent(hsrqRequest)) {
        try {
            FileItem item;
            Map<String, FileItem> mpFiles;
            TwoElementStruct<Map<String, Object>, Map<String, FileItem>> params;

            params = WebParamUtils.getMultipartParameters("WebUtils: ", hsrqRequest);
            mpFiles = params.getSecond();

            for (iterValues = mpFiles.values().iterator(); iterValues.hasNext();) {
                item = (FileItem) iterValues.next();
                sbfReturn.append("\nUpload=");
                sbfReturn.append(item.getName());
                sbfReturn.append(" field=");
                sbfReturn.append(item.getFieldName());
                sbfReturn.append(" contentType=");
                sbfReturn.append(item.getContentType());
                sbfReturn.append(" isInMemory=");
                sbfReturn.append(item.isInMemory());
                sbfReturn.append(" sizeInBytes=");
                sbfReturn.append(item.getSize());
                if (iterValues.hasNext()) {
                    sbfReturn.append(";");
                }
            }
        } catch (OSSInvalidDataException ex) {
            sbfReturn.append("<Cannot access list of multipart parameters>");
            s_logger.log(Level.SEVERE, "Cannot access list of multipart parameters", ex);
        }
    }

    // Headers ///////////////////////////////////////////////////////////////

    for (enumNames = hsrqRequest.getHeaderNames(); enumNames.hasMoreElements();) {
        strName = (String) enumNames.nextElement();
        sbfReturn.append("\nHeader=");
        sbfReturn.append(strName);
        sbfReturn.append(" values=");
        for (enumValues = hsrqRequest.getHeaders(strName); enumValues.hasMoreElements();) {
            sbfReturn.append(enumValues.nextElement());
            if (enumValues.hasMoreElements()) {
                sbfReturn.append(";");
            }
        }
        if (enumNames.hasMoreElements()) {
            sbfReturn.append(";");
        }
    }

    // Cookies ///////////////////////////////////////////////////////////////

    arCookies = hsrqRequest.getCookies();
    if (arCookies != null) {
        Cookie cookie;

        for (iIndex = 0; iIndex < arCookies.length; iIndex++) {
            cookie = arCookies[iIndex];
            sbfReturn.append("\nCookie=");
            sbfReturn.append(cookie.getName());
            sbfReturn.append(" path=");
            sbfReturn.append(cookie.getPath());
            sbfReturn.append(" path=");
            sbfReturn.append(cookie.getDomain());
            sbfReturn.append(" maxage=");
            sbfReturn.append(cookie.getMaxAge());
            sbfReturn.append(" version=");
            sbfReturn.append(cookie.getVersion());
            sbfReturn.append(" secure=");
            sbfReturn.append(cookie.getSecure());
            sbfReturn.append(" value=");
            sbfReturn.append(cookie.getValue());
            sbfReturn.append(" comment=");
            sbfReturn.append(StringUtils.valueIfNotNull(cookie.getComment()));
            if (iIndex < (arCookies.length - 1)) {
                sbfReturn.append(";");
            }
        }
    }
    if (enumNames.hasMoreElements()) {
        sbfReturn.append(";");
    }

    // Attributes ////////////////////////////////////////////////////////////

    for (enumNames = hsrqRequest.getAttributeNames(); enumNames.hasMoreElements();) {
        strName = (String) enumNames.nextElement();
        sbfReturn.append("\nAttribute=");
        sbfReturn.append(strName);
        sbfReturn.append(" value=");
        sbfReturn.append(hsrqRequest.getAttribute(strName));
        if (enumNames.hasMoreElements()) {
            sbfReturn.append(";");
        }
    }

    // Content ///////////////////////////////////////////////////////////////

    sbfReturn.append("\nContent=");
    try {
        sbfReturn.append(StringUtils.convertStreamToString(hsrqRequest.getInputStream(), true));
    } catch (IOException ex) {
        sbfReturn.append("<Cannot access input stream of the request>");
        s_logger.log(Level.SEVERE, "Cannot access input stream of the request", ex);
    }
    sbfReturn.append(";");

    return sbfReturn.toString();
}

From source file:org.owasp.esapi.reference.DefaultHTTPUtilities.java

/**
* {@inheritDoc}//www.j  ava 2  s  .  c o m
 * This implementation uses a custom "set-cookie" header rather than Java's
 * cookie interface which doesn't allow the use of HttpOnly. Configure the
 * HttpOnly and Secure settings in ESAPI.properties.
*/
public void addCookie(HttpServletResponse response, Cookie cookie) {
    String name = cookie.getName();
    String value = cookie.getValue();
    int maxAge = cookie.getMaxAge();
    String domain = cookie.getDomain();
    String path = cookie.getPath();
    boolean secure = cookie.getSecure();

    // validate the name and value
    ValidationErrorList errors = new ValidationErrorList();
    String cookieName = ESAPI.validator().getValidInput("cookie name", name, "HTTPCookieName", 50, false,
            errors);
    String cookieValue = ESAPI.validator().getValidInput("cookie value", value, "HTTPCookieValue", 5000, false,
            errors);

    // if there are no errors, then set the cookie either with a header or normally
    if (errors.size() == 0) {
        if (ESAPI.securityConfiguration().getForceHttpOnlyCookies()) {
            String header = createCookieHeader(cookieName, cookieValue, maxAge, domain, path, secure);
            addHeader(response, "Set-Cookie", header);
        } else {
            // Issue 23 - If the ESAPI Configuration is set to force secure cookies, force the secure flag on the cookie before setting it
            cookie.setSecure(secure || ESAPI.securityConfiguration().getForceSecureCookies());
            response.addCookie(cookie);
        }
        return;
    }
    logger.warning(Logger.SECURITY_FAILURE,
            "Attempt to add unsafe data to cookie (skip mode). Skipping cookie and continuing.");
}

From source file:org.piraso.web.base.WebEntryUtils.java

public static CookieEntry toEntry(Cookie cookie) {
    CookieEntry entry = new CookieEntry();

    entry.setName(cookie.getName());/*from ww w.j  av a2  s . c o m*/
    entry.setValue(cookie.getValue());
    entry.setComment(cookie.getComment());
    entry.setDomain(cookie.getDomain());
    entry.setMaxAge(cookie.getMaxAge());
    entry.setPath(cookie.getPath());
    entry.setSecure(cookie.getSecure());
    entry.setVersion(cookie.getVersion());

    return entry;
}

From source file:org.projectforge.business.user.filter.UserFilter.java

@Override
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());
            }/* w ww . j  av a  2  s.c om*/
        }
    }
    final HttpServletResponse response = (HttpServletResponse) resp;
    UserContext userContext = null;
    try {
        MDC.put("ip", (Object) request.getRemoteAddr());
        MDC.put("session", (Object) 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;
            userContext = (UserContext) request.getSession().getAttribute(SESSION_KEY_USER);
            if (userContext != null) {
                if (updateRequiredFirst == false) {
                    // Get the fresh user from the user cache (not in maintenance mode because user group cache is perhaps not initialized correctly
                    // if updates of e. g. the user table are necessary.
                    userContext.refreshUser();
                }
                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.
                userContext = checkStayLoggedIn(request, response);
                if (userContext != null) {
                    if (log.isDebugEnabled() == true) {
                        log.debug("User's stay logged-in cookie found: " + request.getRequestURI());
                    }
                    userContext.setStayLoggedIn(true); // Used by MenuMobilePage.
                    UserFilter.login(request, userContext);
                }
            }
            final PFUserDO user = userContext != null ? userContext.getUser() : null;
            if (user != null) {
                MDC.put("user", (Object) user.getUsername());
                ThreadLocalUserContext.setUserContext(userContext);
                request = decorateWithLocale(request);
                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);
                    chain.doFilter(request, response);
                } else {
                    response.getWriter().append("No access.");
                }
            }
        }
    } finally {
        ThreadLocalUserContext.clear();
        MDC.remove("ip");
        MDC.remove("session");
        final PFUserDO user = userContext != null ? userContext.getUser() : null;
        if (user != null) {
            MDC.remove("user");
        }
        if (log.isDebugEnabled() == true) {
            StringBuffer sb = new StringBuffer();
            sb.append("doFilter finished for ");
            sb.append(request.getRequestURI());
            if (request.getSession(false) != null) {
                sb.append(request.getSession(false).getId());
            } else {
                sb.append("No active session available.");
            }
            log.debug(sb.toString());
        }
    }
}