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:org.etudes.jforum.ControllerUtils.java

/**
 * Add or update a cookie. This method adds a cookie, serializing its value using XML.
 *
 * @param name The cookie name.//from w  w w.  j av  a2s  . com
 * @param value The cookie value
 */
public static void addCookie(String name, String value) {
    Cookie cookie = new Cookie(name, value);
    cookie.setMaxAge(3600 * 24 * 365);
    cookie.setPath("/");

    JForumBaseServlet.getResponse().addCookie(cookie);
}

From source file:com.erudika.para.utils.Utils.java

/**
 * Sets a cookie.//from  www .ja v a2s  . co  m
 * @param name the name
 * @param value the value
 * @param req HTTP request
 * @param res HTTP response
 * @param httpOnly HTTP only flag
 * @param maxAge max age
 */
public static void setRawCookie(String name, String value, HttpServletRequest req, HttpServletResponse res,
        boolean httpOnly, int maxAge) {
    if (StringUtils.isBlank(name) || StringUtils.isBlank(value) || req == null || res == null) {
        return;
    }
    Cookie cookie = new Cookie(name, value);
    cookie.setHttpOnly(httpOnly);
    cookie.setMaxAge(maxAge < 0 ? Config.SESSION_TIMEOUT_SEC.intValue() : maxAge);
    cookie.setPath("/");
    cookie.setSecure(req.isSecure());
    res.addCookie(cookie);
}

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

/**
 * Create a new visit cookie and return it.
 * /*w  w w  . j av a 2 s .c om*/
 * @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.liferay.portal.action.LoginAction.java

public static void login(HttpServletRequest req, HttpServletResponse res, String login, String password,
        boolean rememberMe) throws Exception {

    CookieKeys.validateSupportCookie(req);

    HttpSession ses = req.getSession();/*  w w w  .j av a 2  s  .c om*/

    long userId = GetterUtil.getLong(login);

    int authResult = Authenticator.FAILURE;

    Company company = PortalUtil.getCompany(req);

    //
    boolean ldaplogin = false;
    if (PrefsPropsUtil.getString(company.getCompanyId(), PropsUtil.LDAP_AUTH_ENABLED).equals("true")) {
        LdapContext ctx = PortalLDAPUtil.getContext(company.getCompanyId());
        String accountname = "";
        try {
            User user1 = UserLocalServiceUtil.getUserByScreenName(company.getCompanyId(), login);
            Properties env = new Properties();

            String baseProviderURL = PrefsPropsUtil.getString(company.getCompanyId(),
                    PropsUtil.LDAP_BASE_PROVIDER_URL);
            String userDN = PrefsPropsUtil.getString(company.getCompanyId(), PropsUtil.LDAP_USERS_DN);
            String baseDN = PrefsPropsUtil.getString(company.getCompanyId(), PropsUtil.LDAP_BASE_DN);
            String filter = PrefsPropsUtil.getString(company.getCompanyId(), PropsUtil.LDAP_AUTH_SEARCH_FILTER);
            filter = StringUtil.replace(filter,
                    new String[] { "@company_id@", "@email_address@", "@screen_name@", "@user_id@" },
                    new String[] { String.valueOf(company.getCompanyId()), "", login, login });
            try {
                SearchControls cons = new SearchControls(SearchControls.SUBTREE_SCOPE, 1, 0, null, false,
                        false);

                NamingEnumeration enu = ctx.search(userDN, filter, cons);
                if (enu.hasMoreElements()) {
                    SearchResult result = (SearchResult) enu.nextElement();
                    accountname = result.getName();
                }
            } catch (Exception e1) {
                e1.printStackTrace();
            }

            env.put(Context.INITIAL_CONTEXT_FACTORY, PrefsPropsUtil.getString(PropsUtil.LDAP_FACTORY_INITIAL));
            env.put(Context.PROVIDER_URL, LDAPUtil.getFullProviderURL(baseProviderURL, baseDN));
            env.put(Context.SECURITY_PRINCIPAL, accountname + "," + userDN);
            env.put(Context.SECURITY_CREDENTIALS, password);

            new InitialLdapContext(env, null);
            ldaplogin = true;
            System.out.println("LDAP Login");
        } catch (Exception e) {
            SessionErrors.add(req, "ldapAuthentication");
            e.printStackTrace();
            System.out.println("LDAP error login");
            return;
        }
    }

    //

    Map headerMap = new HashMap();

    Enumeration enu1 = req.getHeaderNames();

    while (enu1.hasMoreElements()) {
        String name = (String) enu1.nextElement();

        Enumeration enu2 = req.getHeaders(name);

        List headers = new ArrayList();

        while (enu2.hasMoreElements()) {
            String value = (String) enu2.nextElement();

            headers.add(value);
        }

        headerMap.put(name, (String[]) headers.toArray(new String[0]));
    }

    Map parameterMap = req.getParameterMap();

    if (company.getAuthType().equals(CompanyImpl.AUTH_TYPE_EA)) {
        authResult = UserLocalServiceUtil.authenticateByEmailAddress(company.getCompanyId(), login, password,
                headerMap, parameterMap);

        userId = UserLocalServiceUtil.getUserIdByEmailAddress(company.getCompanyId(), login);
    } else if (company.getAuthType().equals(CompanyImpl.AUTH_TYPE_SN)) {
        authResult = UserLocalServiceUtil.authenticateByScreenName(company.getCompanyId(), login, password,
                headerMap, parameterMap);

        userId = UserLocalServiceUtil.getUserIdByScreenName(company.getCompanyId(), login);
    } else if (company.getAuthType().equals(CompanyImpl.AUTH_TYPE_ID)) {
        authResult = UserLocalServiceUtil.authenticateByUserId(company.getCompanyId(), userId, password,
                headerMap, parameterMap);
    }

    boolean OTPAuth = false;

    if (GetterUtil.getBoolean(PropsUtil.get("use.yubicoauthentication"), false) == true) {
        String otppasswd = ParamUtil.getString(req, "otp");
        String userslist = GetterUtil.getString(PropsUtil.get("yubico.users.not.require.otp"), "root");
        if (userslist.contains(login)) {
            authResult = Authenticator.SUCCESS;
        } else {
            OTPAuth = SecurityUtils.verifyOTP(otppasswd, login);
            if (authResult == Authenticator.SUCCESS && OTPAuth) {
                authResult = Authenticator.SUCCESS;
            } else {
                authResult = Authenticator.FAILURE;
            }
        }
    }

    if (PrefsPropsUtil.getString(company.getCompanyId(), PropsUtil.LDAP_AUTH_ENABLED).equals("true")) {
        if (!login.equals("root")) {
            if (ldaplogin) {
                authResult = Authenticator.SUCCESS;
            }
        }
    }

    if (authResult == Authenticator.SUCCESS) {

        boolean loginViaPortal = true;

        setLoginCookies(req, res, ses, userId, rememberMe);
        // login to epsos
        String language = GeneralUtils.getLocale(req);
        SpiritEhrWsClientInterface webService = EpsosHelperService.getInstance().getWebService(req);

        InitUserObj initUserObj = EpsosHelperImpl.createEpsosUserInformation(req, res, language, webService,
                userId, company.getCompanyId(), login, loginViaPortal);
        SpiritUserClientDto usr = initUserObj.getUsr();
        Assertion assertion = initUserObj.getAssertion();

        if (Validator.isNotNull(usr)) {
            req.getSession().setAttribute(EpsosHelperService.EPSOS_LOGIN_INFORMATION_ASSERTIONID,
                    assertion.getID());
            req.getSession().setAttribute(EpsosHelperService.EPSOS_LOGIN_INFORMATION_ASSERTION, assertion);
            req.getSession().setAttribute(EPSOS_LOGIN_INFORMATION_ATTRIBUTE, usr);
        } else {
            SessionErrors.add(req, "User doesn't belong to epSOS role so you can't login");
        }

        if (Validator.isNull(usr) && (!(login.equals("root")))) {
            try {
                Cookie cookie = new Cookie(CookieKeys.ID, StringPool.BLANK);
                cookie.setMaxAge(0);
                cookie.setPath("/");

                CookieKeys.addCookie(res, cookie);

                cookie = new Cookie(CookieKeys.PASSWORD, StringPool.BLANK);
                cookie.setMaxAge(0);
                cookie.setPath("/");

                CookieKeys.addCookie(res, cookie);

                try {
                    ses.invalidate();
                } catch (Exception e) {
                }

            } catch (Exception e) {
                req.setAttribute(PageContext.EXCEPTION, e);

            }
            throw new AuthException();

        }

    } else {
        throw new AuthException();
    }
}

From source file:com.acme.demo.web.LogoutController.java

private void handleLogOutResponse(HttpServletRequest request, HttpServletResponse response) {
    Cookie[] cookies = request.getCookies();
    for (Cookie cookie : cookies) {
        cookie.setMaxAge(0);
        cookie.setValue(null);/* w w  w.j a  v  a  2 s  . c  om*/
        cookie.setPath("/");
        response.addCookie(cookie);
    }

}

From source file:spring.travel.site.controllers.LogoutController.java

@RequestMapping(method = RequestMethod.GET)
public View logout(HttpServletResponse response) {
    Cookie cookie = new Cookie(cookieName, "");
    cookie.setMaxAge(0);
    response.addCookie(cookie);//from w w  w  .jav  a  2 s  .co  m
    return new RedirectView("/");
}

From source file:shiver.me.timbers.spring.security.CookieJwtLogoutHandler.java

@Override
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
    final Cookie cookie = bakery.bake(tokenName, "");
    cookie.setMaxAge(0);
    response.addCookie(cookie);//  w w w. j  av  a 2s.c om
}

From source file:org.osmsurround.ae.oauth.OauthCookieService.java

private Cookie createOneYearCookie(String name, String value) {
    Cookie cookie = new Cookie(name, value);
    cookie.setMaxAge(60 * 60 * 24 * 365);
    return cookie;
}

From source file:io.cfp.auth.MainCtrl.java

@RequestMapping("/logout")
public String logout(HttpServletResponse response, @CookieValue(required = false) String token,
        @CookieValue(required = false) String returnTo) {

    Cookie tokenCookie = cookieService.getTokenCookie("");
    tokenCookie.setMaxAge(0);
    response.addCookie(tokenCookie);/*from   www . j a va  2  s. c o  m*/

    tokenSrv.remove(token);

    return "redirect:/";
}

From source file:net.longfalcon.web.LogoutController.java

@RequestMapping("/logout")
public String logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
        HttpSession httpSession, Model model) {
    try {/*from   w  ww.  j  a  v  a  2  s  .  com*/
        httpSession.invalidate();
        Cookie uidCookie = new Cookie("uid", "");
        uidCookie.setMaxAge(-1);
        Cookie idhCookie = new Cookie("idh", "");
        idhCookie.setMaxAge(-1);
        httpServletResponse.addCookie(uidCookie);
        httpServletResponse.addCookie(idhCookie);
    } catch (Exception e) {
        _log.error(e, e);
    }
    model.asMap().clear();
    return "redirect:/";
}