Example usage for javax.servlet.http Cookie setMaxAge

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

Introduction

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

Prototype

public void setMaxAge(int expiry) 

Source Link

Document

Sets the maximum age in seconds for this Cookie.

Usage

From source file:com.qut.middleware.spep.filter.SPEPFilter.java

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
        throws IOException, ServletException {
    if (!(servletRequest instanceof HttpServletRequest)) {
        throw new ServletException(Messages.getString("SPEPFilter.0")); //$NON-NLS-1$
    }/*from  w  w  w  . j  a v a  2 s  .  com*/
    if (!(servletResponse instanceof HttpServletResponse)) {
        throw new ServletException(Messages.getString("SPEPFilter.1")); //$NON-NLS-1$
    }

    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    String resource, decodedResource, requested, redirectURL;
    URL serviceHost;

    ServletContext spepContext = this.filterConfig.getServletContext().getContext(this.spepContextName);

    // Get servlet context.
    if (spepContext == null) {
        throw new ServletException(Messages.getString("SPEPFilter.2") + " " + this.spepContextName); //$NON-NLS-1$ //$NON-NLS-2$
    }

    // Establish SPEPProxy object.
    SPEPProxy spep;
    try {
        spep = Initializer.init(spepContext);
    } catch (Exception e) {
        this.logger.error(
                "Unable to process request to acces resource, SPEP is not responding, check cross context configuration is enabled \n"
                        + e.getLocalizedMessage());
        throw new ServletException(Messages.getString("SPEPFilter.3"), e); //$NON-NLS-1$
    }

    // Ensure SPEP startup.
    if (!spep.isStarted()) {
        // Don't allow anything to occur if SPEP hasn't started correctly.
        this.logger.error("Unable to process request to acces resource, SPEP is not initialized correcty ");
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        throw new ServletException(Messages.getString("SPEPFilter.4")); //$NON-NLS-1$
    }

    // Get SPEP cookie.
    Cookie spepCookie = null;
    Cookie globalESOECookie = null;
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(spep.getTokenName())) {
                spepCookie = cookie;
                this.logger.debug("Located spep cookie with value of " + spepCookie.getValue());
            }
            if (cookie.getName().equals(spep.getEsoeGlobalTokenName())) {
                globalESOECookie = cookie;
                this.logger
                        .debug("Located globalESOECookie cookie with value of " + globalESOECookie.getValue());
            }
        }
    }

    // value for re-determining session status after Authz request
    boolean validSession = false;

    // Check SPEP session is valid.
    if (spepCookie != null) {
        String sessionID = spepCookie.getValue();

        this.logger.info("Attempting to retrieve data for session with ID of " + sessionID);
        PrincipalSession PrincipalSession = spep.verifySession(sessionID);

        if (PrincipalSession != null) {
            this.logger.info("Located session with ID of " + sessionID);

            if (request.getSession().getAttribute(ATTRIBUTES) == null) {
                // over write with new data if it exists
                WORMHashMap<String, List<Object>> attributeMap = new WORMHashMap<String, List<Object>>();
                attributeMap.putAll(PrincipalSession.getAttributes());
                attributeMap.close();

                request.getSession().setAttribute(ATTRIBUTES, attributeMap);
                request.getSession().setAttribute(SPEP_SESSIONID, sessionID);
            }

            /*
             * This section of code is critical, we must pass the PEP an exact representation of what the user is
             * attempting to access additionally the PEP expects that the string is not in encoded form as it will
             * do exact matching, so we decode before passing our request to it.
             */
            resource = request.getRequestURI();
            if (request.getQueryString() != null)
                resource = resource + "?" + request.getQueryString(); //$NON-NLS-1$

            decodedResource = decode(resource);

            SPEPProxy.decision authzDecision = spep.makeAuthzDecision(sessionID, decodedResource);

            // the authz processor may destroy the session if the PDP determines that the client
            // session is no longer valid, so we have to check it again
            if ((PrincipalSession = spep.verifySession(sessionID)) != null)
                validSession = true;

            if (validSession) {
                if (authzDecision == SPEPProxy.decision.permit) {
                    this.logger.info("PDP advised for session ID of " + sessionID + " that access to resource "
                            + decodedResource + " was permissable");
                    chain.doFilter(request, response);
                    return;
                } else if (authzDecision == SPEPProxy.decision.deny) {
                    this.logger.info("PDP advised for session ID of " + sessionID + " that access to resource "
                            + decodedResource + " was denied, forcing response of"
                            + HttpServletResponse.SC_FORBIDDEN);
                    response.setStatus(javax.servlet.http.HttpServletResponse.SC_FORBIDDEN);
                    response.sendError(HttpServletResponse.SC_FORBIDDEN);
                    return;
                } else if (authzDecision == SPEPProxy.decision.error) {
                    this.logger.info("PDP advised for session ID of " + sessionID + " that access to resource "
                            + decodedResource + " was in error, forcing response of"
                            + HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    throw new ServletException(Messages.getString("SPEPFilter.6")); //$NON-NLS-1$
                } else {
                    this.logger.info("PDP advised for session ID of " + sessionID + " that access to resource "
                            + decodedResource + " was undetermined, forcing response of"
                            + HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    throw new ServletException(Messages.getString("SPEPFilter.7")); //$NON-NLS-1$
                }
            }
        }

        /* Clear the local session object the supplied request is invalid */
        this.logger.debug("Invalidating session for ID of " + sessionID);
        request.getSession().invalidate();
    }

    /*
     * If we get to this stage, the user has not got a session established with this SPEP. We proceed to clear the
     * cookies configured by the SPEP to be cleared upon logout, since this is potentially the first time they have
     * come back to the SPEP since logging out.
     */
    List<Cookie> clearCookies = new Vector<Cookie>();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (spep.getLogoutClearCookies() != null) {
                for (Cookie clearCookie : spep.getLogoutClearCookies()) {
                    if (cookie.getName().equalsIgnoreCase(clearCookie.getName())) {
                        Cookie clearCookieCloneInsecure = (Cookie) clearCookie.clone();
                        clearCookieCloneInsecure.setMaxAge(0);
                        clearCookieCloneInsecure.setSecure(false);

                        clearCookies.add(clearCookieCloneInsecure);

                        // Don't need to process the inner loop again for this cookie.
                        break;
                    }
                }
            }
        }
    }

    /* Add the cookies to be cleared into the response object. */
    for (Cookie c : clearCookies)
        response.addCookie(c);

    /*
     * Remove any principal object details which may be in the session, this state can occur if the user has removed
     * their spepSession cookie but retained their jsessionid cookie
     */
    request.getSession().removeAttribute(ATTRIBUTES);

    /*
     * At this stage a determination needs to be made about allowing the request to pass SPEP without being hindered
     * due to lazy session initialization being configured if it isn't or we won't allow the request to pass for the
     * logical reasons below they will be forced to authenticate.
     */
    if (spep.isLazyInit()) {
        this.logger.info(
                "Lazy init is enabled on this SPEP instance, determining if request should be interrogated by SPEP");

        /*
         * We are being lazy in starting sessions, determine if user has already authenticated with an IDP (the
         * ESOE), if so we enforce a session (value is not important just that the cookie exists), if not figure out
         * if user is accessing something that has been configured to force a session to be established before it is
         * accessible
         */
        if (globalESOECookie == null) {
            this.logger.debug("globalESOECookie was not set for this request");

            boolean matchedLazyInitResource = false;
            resource = request.getRequestURI();
            if (request.getQueryString() != null)
                resource = resource + "?" + request.getQueryString(); //$NON-NLS-1$

            decodedResource = decode(resource);

            for (String lazyInitResource : spep.getLazyInitResources()) {
                if (decodedResource.matches(lazyInitResource)) {
                    matchedLazyInitResource = true;
                    this.logger.info("Lazy session init attempt matched initialization query of "
                            + lazyInitResource + " from request of " + decodedResource);
                } else
                    this.logger.debug("Lazy session init attempt failed to match initialization query of "
                            + lazyInitResource + " from request of " + decodedResource);
            }

            // If we still have no reason to engage spep functionality for this request let the request pass
            if (matchedLazyInitResource) {
                if (spep.getLazyInitDefaultAction().equals(SPEPProxy.defaultAction.deny)) {
                    this.logger.info("No reason to invoke SPEP for access to resource " + decodedResource
                            + " could be determined due to lazyInit, forwarding request to application");
                    chain.doFilter(request, response);
                    return;
                }
            } else {
                if (spep.getLazyInitDefaultAction().equals(SPEPProxy.defaultAction.permit)) {
                    this.logger.info("No reason to invoke SPEP for access to resource " + decodedResource
                            + " could be determined due to lazyInit, forwarding request to application");
                    chain.doFilter(request, response);
                    return;
                }
            }
        }
    }

    /*
     * All attempts to provide resource access have failed, invoke SPEP to provide secure session establishment
     * Current request is B64 encoded and appended to request for SPEP to redirect users back to content dynamically
     */
    this.logger.debug("Failed all avenues to provide access to content");
    if (request.getQueryString() != null)
        requested = request.getRequestURI() + "?" + request.getQueryString();
    else
        requested = request.getRequestURI();

    /*
     * Determine if the request was directed to the service URL, if so redirect to that point. If not redirect to
     * the local node.
     */
    serviceHost = new URL(spep.getServiceHost());

    String ssoRedirect = spep.getSsoRedirect();
    String timestampParameter;
    if (ssoRedirect.indexOf('?') > -1) {
        timestampParameter = "&ts=" + System.currentTimeMillis();
    } else {
        timestampParameter = "?ts=" + System.currentTimeMillis();
    }

    if (request.getServerName().equals(serviceHost.getHost())) {
        /* Ensures that SSL offloading in Layer 7 environments is correctly handled */
        requested = spep.getServiceHost() + requested;
        String base64RequestURI = new String(Base64.encodeBase64(requested.getBytes()));
        redirectURL = MessageFormat.format(spep.getServiceHost() + spep.getSsoRedirect(),
                new Object[] { base64RequestURI + timestampParameter });
    } else {
        String base64RequestURI = new String(Base64.encodeBase64(requested.getBytes()));
        redirectURL = MessageFormat.format(spep.getSsoRedirect(),
                new Object[] { base64RequestURI + timestampParameter });
    }

    this.logger.debug("Redirecting to " + redirectURL + " to establish secure session");
    response.sendRedirect(redirectURL);
}

From source file:com.xpn.xwiki.user.impl.xwiki.MyPersistentLoginManager.java

/**
 * Remove a cookie.//from w w w  . java2 s  .c o m
 * 
 * @param request The servlet request.
 * @param response The servlet response.
 * @param cookieName The name of the cookie that must be removed.
 */
private void removeCookie(HttpServletRequest request, HttpServletResponse response, String cookieName) {
    Cookie cookie = getCookie(request.getCookies(), cookieName);
    if (cookie != null) {
        cookie.setMaxAge(0);
        cookie.setPath(this.cookiePath);
        addCookie(response, cookie);
        String cookieDomain = getCookieDomain(request);
        if (cookieDomain != null) {
            cookie.setDomain(cookieDomain);
            addCookie(response, cookie);
        }
    }
}

From source file:org.alfresco.web.app.servlet.AuthenticationHelper.java

/**
 * Setup the Alfresco auth cookie value.
 * //from  ww  w . ja v a2 s.c  om
 * @param httpRequest
 * @param httpResponse
 * @param username
 */
public static void setUsernameCookie(HttpServletRequest httpRequest, HttpServletResponse httpResponse,
        String username) {
    if (logger.isDebugEnabled())
        logger.debug("Setting up the Alfresco auth cookie for " + username);
    Cookie authCookie = getAuthCookie(httpRequest);
    // Let's Base 64 encode the username so it is a legal cookie value
    String encodedUsername;
    try {
        encodedUsername = Base64.encodeBytes(username.getBytes("UTF-8"));
        if (logger.isDebugEnabled())
            logger.debug("Base 64 encode the username: " + encodedUsername);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
    if (authCookie == null) {
        if (logger.isDebugEnabled())
            logger.debug("No Alfresco auth cookie wa found, creating new one.");
        authCookie = new Cookie(COOKIE_ALFUSER, encodedUsername);
    } else {
        if (logger.isDebugEnabled())
            logger.debug("Updating the previous Alfresco auth cookie value.");
        authCookie.setValue(encodedUsername);
    }
    authCookie.setPath(httpRequest.getContextPath());
    // TODO: make this configurable - currently 7 days (value in seconds)
    authCookie.setMaxAge(60 * 60 * 24 * 7);
    httpResponse.addCookie(authCookie);
}

From source file:com.liferay.portal.action.LoginAction.java

public static void setLoginCookies(HttpServletRequest req, HttpServletResponse res, HttpSession ses,
        long userId, boolean rememberMe) throws PortalException, SystemException, EncryptorException {
    if (GetterUtil.getBoolean(PropsUtil.get(PropsUtil.SESSION_ENABLE_PHISHING_PROTECTION))) {

        // Invalidate the previous session to prevent phishing

        LastPath lastPath = (LastPath) ses.getAttribute(WebKeys.LAST_PATH);

        // GNOMON Gi9: KEEP ANY USER_CARRY ATTRIBUTES (for example shopping cart)
        HashMap userCarryAttributes = getUserCarryAttributes(ses);

        try {//from  w w w.  j  ava  2  s  .  c  om
            ses.invalidate();
        } catch (Exception e) {
            _log.info("Session has already invalidated");
        }

        ses = req.getSession(true);

        addSessionAttributes(ses, userCarryAttributes);

        if (lastPath != null) {
            ses.setAttribute(WebKeys.LAST_PATH, lastPath);
        }
    }

    // Set cookies

    String domain = PropsUtil.get(PropsUtil.SESSION_COOKIE_DOMAIN);

    User user = UserLocalServiceUtil.getUserById(userId);
    Company company = CompanyLocalServiceUtil.getCompanyById(user.getCompanyId());
    String userIdString = String.valueOf(userId);

    ses.setAttribute("j_username", userIdString);
    ses.setAttribute("j_password", user.getPassword());
    ses.setAttribute("j_remoteuser", userIdString);

    ses.setAttribute(WebKeys.USER_PASSWORD, user.getPassword());

    Cookie idCookie = new Cookie(CookieKeys.ID, UserLocalServiceUtil.encryptUserId(userIdString));

    if (Validator.isNotNull(domain)) {
        idCookie.setDomain(domain);
    }

    idCookie.setPath(StringPool.SLASH);

    Cookie passwordCookie = new Cookie(CookieKeys.PASSWORD,
            Encryptor.encrypt(company.getKeyObj(), user.getPassword()));

    if (Validator.isNotNull(domain)) {
        passwordCookie.setDomain(domain);
    }

    passwordCookie.setPath(StringPool.SLASH);

    int loginMaxAge = GetterUtil.getInteger(PropsUtil.get(PropsUtil.COMPANY_SECURITY_AUTO_LOGIN_MAX_AGE),
            CookieKeys.MAX_AGE);

    if (GetterUtil.getBoolean(PropsUtil.get(PropsUtil.SESSION_DISABLED))) {

        rememberMe = true;
    }

    if (rememberMe) {
        idCookie.setMaxAge(loginMaxAge);
        passwordCookie.setMaxAge(loginMaxAge);
    } else {
        idCookie.setMaxAge(0);
        passwordCookie.setMaxAge(0);
    }

    Cookie loginCookie = new Cookie(CookieKeys.LOGIN, user.getLogin());

    if (Validator.isNotNull(domain)) {
        loginCookie.setDomain(domain);
    }

    loginCookie.setPath(StringPool.SLASH);
    loginCookie.setMaxAge(loginMaxAge);

    Cookie screenNameCookie = new Cookie(CookieKeys.SCREEN_NAME,
            Encryptor.encrypt(company.getKeyObj(), user.getScreenName()));

    if (Validator.isNotNull(domain)) {
        screenNameCookie.setDomain(domain);
    }

    screenNameCookie.setPath(StringPool.SLASH);
    screenNameCookie.setMaxAge(loginMaxAge);

    CookieKeys.addCookie(res, idCookie);
    CookieKeys.addCookie(res, passwordCookie);
    CookieKeys.addCookie(res, loginCookie);
    CookieKeys.addCookie(res, screenNameCookie);

    //add entry to user tracking if needed
    boolean trackUser = GetterUtil.getBoolean(PropsUtil.get(user.getCompanyId(), "gn.user.tracking.enabled"),
            false);
    if (trackUser) {
        GnUserTracking track = new GnUserTracking();
        track.setCompanyId(user.getCompanyId());
        track.setUserId(user.getUserId());
        track.setLoginDate(new Date());
        String fromIp = req.getHeader("X-Forwarded-For");
        if (Validator.isNull(fromIp))
            fromIp = req.getRemoteAddr() + (Validator.isNotNull(req.getRemoteHost())
                    && !req.getRemoteAddr().equals(req.getRemoteHost()) ? "( " + req.getRemoteHost() + " )"
                            : "");

        track.setFromIp(fromIp);
        GnPersistenceService.getInstance(null).createObject(track);
    }
    EventsService.getInstance().createEvent(user, "PortalAuth",
            "User " + user.getScreenName() + " has logged in " + req.getServerName(), "loginaction", null);
}

From source file:com.expressui.core.MainApplication.java

/**
 * Adds a cookie to the HTTP response.//from w  ww . j  a  v a2s .c  o m
 *
 * @param name   name of the cookie
 * @param value  value
 * @param maxAge max age
 * @see Cookie#Cookie(String, String)
 * @see Cookie#setMaxAge(int)
 */
public void addCookie(String name, String value, int maxAge) {
    Cookie cookie = new Cookie(name, value);
    cookie.setMaxAge(maxAge);
    cookie.setPath("/");
    getResponse().addCookie(cookie);
}

From source file:hudson.security.SecurityRealm.java

/**
 * Handles the logout processing./*from ww  w.j  a  va  2  s  . c om*/
 *
 * <p>
 * The default implementation erases the session and do a few other clean up, then
 * redirect the user to the URL specified by {@link #getPostLogOutUrl(StaplerRequest, Authentication)}.
 *
 * @since 1.314
 */
public void doLogout(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
    HttpSession session = req.getSession(false);
    if (session != null)
        session.invalidate();
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    SecurityContextHolder.clearContext();

    // reset remember-me cookie
    Cookie cookie = new Cookie(ACEGI_SECURITY_HASHED_REMEMBER_ME_COOKIE_KEY, "");
    cookie.setMaxAge(0);
    cookie.setSecure(req.isSecure());
    cookie.setHttpOnly(true);
    cookie.setPath(req.getContextPath().length() > 0 ? req.getContextPath() : "/");
    rsp.addCookie(cookie);

    rsp.sendRedirect2(getPostLogOutUrl(req, auth));
}

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractAuthenticationController.java

@RequestMapping(value = { "/{userParam}/loggedout", "{userParam}/j_spring_security_logout" })
public String loggedout(@PathVariable String userParam, ModelMap map, HttpSession session,
        HttpServletResponse response, HttpServletRequest request) {
    logger.debug("###Entering in loggedout(response) method");
    String showSuffixControl = "false";
    String suffixControlType = "textbox";
    List<String> suffixList = null;
    if (config.getValue(Names.com_citrix_cpbm_username_duplicate_allowed).equals("true")) {
        showSuffixControl = "true";
        if (config.getValue(Names.com_citrix_cpbm_login_screen_tenant_suffix_dropdown_enabled).equals("true")) {
            suffixControlType = "dropdown";
            suffixList = tenantService.getSuffixList();
        }//from  w w w  .  ja  va2  s  .  co m
    }
    map.addAttribute("showSuffixControl", showSuffixControl);
    map.addAttribute("suffixControlType", suffixControlType);
    map.addAttribute("suffixList", suffixList);
    if (config.getBooleanValue(Configuration.Names.com_citrix_cpbm_portal_directory_service_enabled)
            && config.getValue(Names.com_citrix_cpbm_directory_mode).equals("pull")) {
        map.addAttribute("directoryServiceAuthenticationEnabled", "true");
    }
    if (config.getValue(Names.com_citrix_cpbm_public_catalog_display).equals("true")
            && channelService.getDefaultServiceProviderChannel() != null) {
        map.addAttribute("showAnonymousCatalogBrowsing", "true");
    }
    map.addAttribute("showLanguageSelection", "true");
    map.addAttribute("supportedLocaleList", this.getLocaleDisplayName(listSupportedLocales()));
    map.addAttribute("logout", true);
    String redirect = null;
    Enumeration<String> en = session.getAttributeNames();
    while (en.hasMoreElements()) {
        String attr = en.nextElement();
        session.removeAttribute(attr);
    }
    Cookie cookie = new Cookie("JforumSSO", "");
    cookie.setMaxAge(0);
    cookie.setPath("/");
    response.addCookie(cookie);
    if (request.getRequestedSessionId() != null && request.isRequestedSessionIdValid()) {
        // create logout notification begins
        User user = userService.get(userParam);
        String message = "logged.out";
        String messageArgs = user.getUsername();
        eventService.createEvent(new Date(), user, message, messageArgs, Source.PORTAL, Scope.USER,
                Category.ACCOUNT, Severity.INFORMATION, true);
    }
    session.invalidate();
    if (config.getAuthenticationService().compareToIgnoreCase(CAS) == 0) {
        try {
            redirect = StringUtils.isEmpty(config.getCasLogoutUrl()) ? null
                    : config.getCasLogoutUrl() + "?service="
                            + URLEncoder.encode(config.getCasServiceUrl(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            logger.error("Exception encoding: " + redirect, e);
        }
        if (redirect == null) {
            throw new InternalError("CAS authentication required, but login url not set");
        }
    }

    SecurityContextHolder.getContext().setAuthentication(null);
    // ends
    logger.debug("###Exiting loggedout(response) method");
    return redirect == null ? "redirect:/j_spring_security_logout" : "redirect:" + redirect;
}

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>//from  w  w  w  .  j  av a 2 s  .  c  o  m
 * @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:org.collectionspace.chain.controller.WebUIRequest.java

private void setSession() {
    //if(session.isOld())
    //   return; // No need to reset session

    Cookie cookie = new Cookie(COOKIENAME, session.getID());
    cookie.setPath("/");//XXX should be /chain - so either need to have a parameter in cspace-config or try and ask tomcat who we are
    cookie.setMaxAge(60 * lifeInMins);
    response.addCookie(cookie);//from   w  w  w.  j a v  a 2  s  . com
}

From source file:org.apache.jetspeed.modules.actions.JLoginUser.java

public void doPerform(RunData rundata) throws Exception {
    JetspeedRunData data = (JetspeedRunData) rundata;

    String username = data.getParameters().getString("username", "");
    String password = data.getParameters().getString("password", "");

    boolean newUserApproval = JetspeedResources.getBoolean("newuser.approval.enable", false);
    String secretkey = (String) data.getParameters().getString("secretkey", null);
    if (secretkey != null) {

        // its the first logon - we are verifying the secretkey

        // handle the buttons on the ConfirmRegistration page
        String button1 = data.getParameters().getString("submit1", null);
        if (button1 != null && button1.equalsIgnoreCase("Cancel")) {
            data.setScreenTemplate(TurbineTemplate.getDefaultScreen());
            return;
        }//from w w  w.  j a v  a 2 s  .c  om

        // check to make sure the user entered the right confirmation key
        // if not, then send them to the ConfirmRegistration screen            
        JetspeedUser user = JetspeedSecurity.getUser(username);

        if (user == null) {
            logger.warn("JLogin User: Unexpected condition : user is NULL");
            return;
        }
        String confirm_value = user.getConfirmed();
        if (!secretkey.equals(confirm_value) && !confirm_value.equals(JetspeedResources.CONFIRM_VALUE)) {
            if (newUserApproval) {
                data.setMessage(Localization.getString(rundata, "JLOGINUSER_KEYNOTVALID"));
                data.setScreenTemplate("NewUserAwaitingAcceptance");
                return;
            } else {
                if (user.getConfirmed().equals(JetspeedResources.CONFIRM_VALUE_REJECTED)) {
                    data.setMessage(Localization.getString(rundata, "JLOGINUSER_KEYNOTVALID"));
                    data.setScreenTemplate("NewUserRejected");
                    return;
                } else {
                    data.setMessage(Localization.getString(rundata, "JLOGINUSER_KEYNOTVALID"));
                    data.setScreenTemplate("ConfirmRegistration");
                    return;
                }
            }
        }

        user.setConfirmed(JetspeedResources.CONFIRM_VALUE);
        data.setMessage(Localization.getString(rundata, "JLOGINUSER_WELCOME"));
        JetspeedSecurity.saveUser(user);
    }

    JetspeedUser user = null;
    try {
        user = JetspeedSecurity.login(username, password);
        JetspeedSecurity.saveUser(user);
    } catch (LoginException e) {
        data.setScreenTemplate(JetspeedResources.getString(TurbineConstants.TEMPLATE_LOGIN));
        String message = e.getMessage() != null ? e.getMessage() : e.toString();
        data.setMessage(message);
        data.setUser(JetspeedSecurity.getAnonymousUser());
        data.getUser().setHasLoggedIn(new Boolean(false));

        if (e instanceof FailedLoginException) {
            if (!disableCheck(data)) {
                logger.info("JLoginUser: Credential Failure on login for user: " + username);
                data.setMessage(Localization.getString(rundata, "PASSWORDFORM_FAILED_MSG"));
            }
        } else if (e instanceof AccountExpiredException) {
            logger.info("JLoginUser: Account Expired for user " + username);
        } else if (e instanceof CredentialExpiredException) {
            logger.info("JLoginUser: Credentials expired for user: " + username);
            data.setScreenTemplate(
                    JetspeedResources.getString(JetspeedResources.CHANGE_PASSWORD_TEMPLATE, "ChangePassword"));
            data.setMessage(Localization.getString(rundata, "PASSWORDFORM_EXPIRED_MSG"));
            data.getParameters().setString("username", username);
        }

        return;
    } catch (Throwable other) {
        data.setScreenTemplate(JetspeedResources.getString(TurbineConstants.TEMPLATE_ERROR));
        String message = other.getMessage() != null ? other.getMessage() : other.toString();
        data.setMessage(message);
        data.setStackTrace(org.apache.turbine.util.StringUtils.stackTrace(other), other);
        JetspeedUser juser = new FakeJetspeedUser(JetspeedSecurity.getAnonymousUserName(), false);
        data.setUser(juser);
        return;
    }
    if ("T".equals(user.getDisabled())) {
        data.setMessage(Localization.getString(rundata, "JLOGINUSER_ACCOUNT_DISABLED"));
        data.setScreenTemplate(JetspeedResources.getString("logon.disabled.form"));
        data.getUser().setHasLoggedIn(new Boolean(false));
        return;
    }

    // check for being confirmed before allowing someone to finish logging in
    if (data.getUser().hasLoggedIn()) {
        if (JetspeedSecurity.isDisableAccountCheckEnabled()) {
            // dst: this needs some refactoring. I don't believe this api is necessary
            JetspeedSecurity.resetDisableAccountCheck(data.getParameters().getString("username", ""));
        }

        String confirmed = data.getUser().getConfirmed();
        if (confirmed == null || !confirmed.equals(JetspeedResources.CONFIRM_VALUE)) {
            if (confirmed != null && confirmed.equals(JetspeedResources.CONFIRM_VALUE_REJECTED)) {
                data.setMessage(Localization.getString(rundata, "JLOGINUSER_KEYNOTVALID"));
                data.setScreenTemplate("NewUserRejected");
                data.getUser().setHasLoggedIn(new Boolean(false));
                return;
            } else {
                data.setMessage(Localization.getString(rundata, "JLOGINUSER_CONFIRMFIRST"));
                data.setScreenTemplate("ConfirmRegistration");
                data.getUser().setHasLoggedIn(new Boolean(false));
                return;
            }
        }

        // user has logged in successfully at this point

        boolean automaticLogonEnabled = JetspeedResources.getBoolean("automatic.logon.enable", false);
        if (automaticLogonEnabled) {
            //Does the user want to use this facility?
            boolean userRequestsRememberMe = data.getParameters().getBoolean("rememberme", false);
            if (userRequestsRememberMe) {
                //save cookies on the users machine.
                int maxage = JetspeedResources.getInt("automatic.logon.cookie.maxage", -1);
                String comment = JetspeedResources.getString("automatic.logon.cookie.comment", "");
                String domain = JetspeedResources.getString("automatic.logon.cookie.domain");
                String path = JetspeedResources.getString("automatic.logon.cookie.path", "/");

                if (domain == null) {
                    String server = data.getServerName();
                    domain = "." + server;
                }

                String loginCookieValue = null;

                if (JetspeedResources.getString("automatic.logon.cookie.generation", "everylogon")
                        .equals("everylogon")) {
                    loginCookieValue = "" + Math.random();
                    data.getUser().setPerm("logincookie", loginCookieValue);
                    JetspeedSecurity.saveUser(data.getJetspeedUser());
                } else {
                    loginCookieValue = (String) data.getUser().getPerm("logincookie");
                    if (loginCookieValue == null || loginCookieValue.length() == 0) {
                        loginCookieValue = "" + Math.random();
                        data.getUser().setPerm("logincookie", loginCookieValue);
                        JetspeedSecurity.saveUser(data.getJetspeedUser());
                    }
                }

                Cookie userName = new Cookie("username", data.getUser().getUserName());
                Cookie loginCookie = new Cookie("logincookie", loginCookieValue);

                userName.setMaxAge(maxage);
                userName.setComment(comment);
                userName.setDomain(domain);
                userName.setPath(path);

                loginCookie.setMaxAge(maxage);
                loginCookie.setComment(comment);
                loginCookie.setDomain(domain);
                loginCookie.setPath(path);

                data.getResponse().addCookie(userName);
                data.getResponse().addCookie(loginCookie);

            }

        }

    } else {
        disableCheck(data);
    }

}