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.sslexplorer.language.actions.SelectLanguageAction.java

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    String referer = DAVUtilities.encodePath(CoreUtil.getRequestReferer(request), false);
    if (referer == null) {
        throw new CoreException(ErrorConstants.ERR_MISSING_REQUEST_PARAMETER, ErrorConstants.CATEGORY_NAME,
                "referer");
    }/*from   w  ww . j av a 2s . co m*/
    String localeCode = request.getParameter("locale");
    if (localeCode == null) {
        throw new CoreException(ErrorConstants.ERR_MISSING_REQUEST_PARAMETER, ErrorConstants.CATEGORY_NAME,
                "locale");
    }

    /* Tokenize the locale parameter so we only get the first line. This prevents
     * a header injection exploit as the (not validated) locale gets added as 
     * a cookie.
     */
    StringTokenizer t = new StringTokenizer(localeCode);
    String locale = t.nextToken();

    // Parse the locale code
    String country = "";
    String variant = "";
    String lang = locale;
    int idx = locale.indexOf("_");
    if (idx != -1) {
        country = lang.substring(idx + 1);
        lang = lang.substring(0, idx);
    }
    idx = country.indexOf('_');
    if (idx != -1) {
        variant = country.substring(idx + 1);
        country = country.substring(0, idx);
    }

    // Store the new locale in the session and set a persistant cookie
    Locale l = new Locale(lang, country, variant);
    request.getSession().setAttribute(Globals.LOCALE_KEY, l);
    Cookie cookie = new Cookie(SystemProperties.get("sslexplorer.cookie", "SSLX_SSESHID") + "_LANG",
            locale.toString());
    cookie.setMaxAge(60 * 60 * 24 * 7); // a week
    cookie.setPath("/");
    cookie.setSecure(true);
    response.addCookie(cookie);
    return referer == null ? mapping.findForward("home") : new ActionForward(referer, true);
}

From source file:io.cfp.auth.service.CookieService.java

public Cookie getTokenCookie(String tokenValue) {
    Cookie tokenCookie = new Cookie("token", tokenValue);
    tokenCookie.setPath("/");
    tokenCookie.setHttpOnly(true); // secure Token to be invisible from
    // javascript in the browser
    tokenCookie.setDomain(cookieDomain);
    tokenCookie.setMaxAge((int) Duration.ofHours(TokenService.TOKEN_EXPIRATION).getSeconds());
    return tokenCookie;
}

From source file:com.sinosoft.one.mvc.web.var.FlashImpl.java

public void writeNewMessages() {
    if (logger.isDebugEnabled()) {
        logger.debug("writeNextMessages");
    }//www.jav a2s.c  o  m
    HttpServletResponse response = invocation.getResponse();
    List<String> responseCookies = null;
    for (Map.Entry<String, String> entry : next.entrySet()) {
        if (responseCookies == null) {
            responseCookies = new ArrayList<String>(next.size());
        }
        String cookieValue;
        if (entry.getValue() == null) {
            cookieValue = "";
        } else {
            try {
                cookieValue = base64.encodeToString(entry.getValue().getBytes("UTF-8"));
            } catch (UnsupportedEncodingException e) {
                throw new Error(e);
            }
        }
        Cookie cookie = new Cookie(cookiePrefix + entry.getKey(), cookieValue);
        cookie.setPath("/");
        // cookie.setMaxAge(1);
        response.addCookie(cookie);
        responseCookies.add(cookie.getName());
        if (logger.isDebugEnabled()) {
            logger.debug("write flash cookie:" + cookie.getName() + "=" + cookie.getValue());
        }
    }
    for (Map.Entry<String, String> entry : last.entrySet()) {
        if (responseCookies == null || !responseCookies.contains(entry.getKey())) {
            Cookie c = new Cookie(entry.getKey(), null);
            c.setMaxAge(0);
            c.setPath("/");
            response.addCookie(c);
            if (logger.isDebugEnabled()) {
                logger.debug("delete flash cookie:" + c.getName() + "=" + c.getValue());
            }
        }
    }
}

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

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {

    String lang = null;// www  .j a v a  2  s  . c o m
    // check if parameter "mllang" is there
    String mlLang = servletRequest.getParameter("mllang");
    String mlLangContent = servletRequest.getParameter("mllangcontent");
    dumpCookies(servletRequest);
    String locale = positionCookie(servletRequest, servletResponse, mlLang, MLPREF, false);

    if (mlLangContent != null && mlLangContent.equals("reset")) {
        Cookie mlpref = new Cookie(MLPREFCONTENT, ""); // Set expiry date after 24 Hrs forboth the cookies. 
        mlpref.setMaxAge(0);
        ((HttpServletResponse) servletResponse).addCookie(mlpref);
        I18NUtil.setContentLocale(null);
    } else {
        positionCookie(servletRequest, servletResponse, mlLangContent, MLPREFCONTENT, true);
    }
    // create the NullFakeHeaderRequest so WebscriptServlet does not modify
    // the request again.
    // recuperate the lang
    if (locale == null) {
        // default it to "en"
        locale = "en";
    }
    NullFakeHeaderRequest request = new NullFakeHeaderRequest((HttpServletRequest) servletRequest, locale);
    filterChain.doFilter(request, servletResponse);

    return;
}

From source file:au.gov.dto.springframework.security.web.context.CookieSecurityContextRepository.java

private Cookie createExpireAuthenticationCookie(HttpServletRequest request) {
    Cookie removeSessionCookie = new Cookie(authenticationCookieName, "");
    removeSessionCookie.setPath(authenticationCookiePath);
    removeSessionCookie.setMaxAge(0);
    removeSessionCookie.setHttpOnly(true);
    removeSessionCookie.setSecure(request.isSecure());
    return removeSessionCookie;
}

From source file:com.haulmont.cuba.web.sys.AppCookies.java

public void removeCookie(String name) {
    if (isCookiesEnabled()) {
        Cookie cookie = getCookie(name);
        if (cookie != null) {
            cookie.setValue(null);//from   w w w . j  a v  a  2s.  c om
            cookie.setPath(getCookiePath());
            cookie.setMaxAge(0);
            addCookie(cookie);
        }
    }
}

From source file:com.perimeterx.api.PerimeterX.java

/**
 * Verify http request using cookie or PX server call
 *
 * @param req             - current http call examined by PX
 * @param responseWrapper - response wrapper on which we will set the response according to PX verification. {@see javax.xml.ws.ResponseWrapper}
 * @throws PXException/*from  ww w  .j  ava2  s.  c  o  m*/
 */
public boolean pxVerify(HttpServletRequest req, HttpServletResponseWrapper responseWrapper) throws PXException {
    if (!moduleEnabled()) {
        logger.info("PerimeterX verification SDK is disabled");
        return true;
    }

    // Remove captcha cookie to prevent re-use
    Cookie cookie = new Cookie(Constants.COOKIE_CAPTCHA_KEY, StringUtils.EMPTY);
    cookie.setMaxAge(0);
    responseWrapper.addCookie(cookie);

    PXContext context = new PXContext(req, this.ipProvider, configuration.getAppId());
    if (captchaValidator.verify(context)) {
        return handleVerification(context, responseWrapper, BlockReason.COOKIE);
    }
    S2SCallReason callReason = cookieValidator.verify(context);
    logger.info("Risk API call reason: {}", callReason);
    // Cookie is valid (exists and not expired) so we can block according to it's score
    if (callReason == S2SCallReason.NONE) {
        logger.info("No risk API Call is needed, using cookie");
        return handleVerification(context, responseWrapper, BlockReason.COOKIE);
    }

    context.setS2sCallReason(callReason);
    // Calls risk_api and populate the data retrieved to the context
    RiskRequest request = RiskRequest.fromContext(context);
    RiskResponse response = serverValidator.verify(request);
    context.setScore(response.getScores().getNonHuman());
    context.setUuid(response.getUuid());
    return handleVerification(context, responseWrapper, BlockReason.SERVER);
}

From source file:com.hypersocket.session.json.SessionUtils.java

public void addAPISession(HttpServletRequest request, HttpServletResponse response, Session session) {

    Cookie cookie = new Cookie(HYPERSOCKET_API_SESSION, session.getId());
    cookie.setMaxAge(60 * session.getTimeout());
    cookie.setSecure(request.getProtocol().equalsIgnoreCase("https"));
    cookie.setPath("/");
    //cookie.setDomain(request.getServerName());
    response.addCookie(cookie);/* w ww. j  a v  a2 s  .  c om*/
}

From source file:net.yacy.cora.protocol.ResponseHeader.java

/**
 * Sets Cookie on the client machine./*from   ww w . j  a  v a  2 s . c o m*/
 *
 * @param name Cookie name
 * @param value Cookie value
 * @param maxage time to live in seconds, none negative number, according to https://tools.ietf.org/html/rfc2109, 0=discard in https://tools.ietf.org/html/rfc2965
 * @param path Path the cookie belongs to. Default - "/". Can be <b>null</b>.
 * @param domain Domain this cookie belongs to. Default - domain name. Can be <b>null</b>.
 * @param secure If true cookie will be send only over safe connection such as https
 * @see further documentation: <a href="http://docs.sun.com/source/816-6408-10/cookies.htm">docs.sun.com</a>
 */
public void setCookie(final String name, final String value, final Integer maxage, final String path,
        final String domain, final boolean secure) {
    /*
    * TODO:Here every value can be validated for correctness if needed
    * For example semicolon should be not in any of the values
    * However an exception in this case would be an overhead IMHO.
    */
    if (!name.isEmpty()) {
        if (this.cookieStore == null)
            this.cookieStore = new ArrayList<Cookie>();
        Cookie c = new Cookie(name, value);
        if (maxage != null && maxage >= 0)
            c.setMaxAge(maxage);
        if (path != null)
            c.setPath(path);
        if (domain != null)
            c.setDomain(domain);
        if (secure)
            c.setSecure(secure);
        this.cookieStore.add(c);
    }
}

From source file:org.apereo.portal.url.UrlCanonicalizingFilter.java

protected void clearRedirectCount(HttpServletRequest request, HttpServletResponse response) {
    final Cookie cookie = new Cookie(COOKIE_NAME, "");
    cookie.setPath(request.getContextPath());
    cookie.setMaxAge(0);
    response.addCookie(cookie);/*  www.  ja  va2 s.  co  m*/
}