Example usage for javax.servlet.http Cookie setPath

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

Introduction

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

Prototype

public void setPath(String uri) 

Source Link

Document

Specifies a path for the cookie to which the client should return the cookie.

Usage

From source file:org.dspace.app.dav.DAVServlet.java

/**
 * Set a new cookie -- only bother if there is no existing cookie or it's at
 * least halfway stale, so you're not churning it.. When force is true,
 * always set a fresh cookie. (e.g. after mac failure upon server restart,
 * etc)/*from ww w  .  j  a va2s.c o  m*/
 * <p>
 * 
 * @param context -
 * get user from context
 * @param request the request
 * @param response the response
 * @param force the force
 */
protected static void putAuthCookie(Context context, HttpServletRequest request, HttpServletResponse response,
        boolean force) {
    Cookie cookie = gimmeCookie(request);
    long now = new Date().getTime();
    if (!force && cookie != null) {
        String crumb[] = cookie.getValue().split("\\!");
        if (crumb.length == 4) {
            long timestamp = -1;
            try {
                timestamp = Long.parseLong(crumb[0]);
            } catch (NumberFormatException e) {
            }

            // check freshness - skip setting cookie if old one isn't stale
            if (timestamp > 0 && (now - timestamp) < (COOKIE_SELL_BY / 2)) {
                return;
            }
        }
    }
    EPerson user = context.getCurrentUser();
    if (user == null) {
        return;
    }
    String value = String.valueOf(now) + "!" + String.valueOf(user.getID()) + "!" + request.getRemoteAddr()
            + "!";
    String mac = Utils.getMD5(value + cookieSecret);
    cookie = new Cookie(COOKIE_NAME, value + mac);
    cookie.setPath(request.getContextPath());
    response.addCookie(cookie);

    log.debug("Setting new cookie, value = \"" + value + mac + "\"");
}

From source file:org.acegisecurity.ui.rememberme.TokenBasedRememberMeServices.java

protected Cookie makeCancelCookie(HttpServletRequest request) {
    Cookie cookie = new Cookie(cookieName, null);
    cookie.setMaxAge(0);//from   w  w w  . ja v  a2 s  .  c o  m
    cookie.setPath(StringUtils.hasLength(request.getContextPath()) ? request.getContextPath() : "/");

    return cookie;
}

From source file:com.qut.middleware.esoe.authn.servlet.AuthnServlet.java

/**
 * Sets the session cookie for this principal
 * /*  ww  w . j  a va2  s .co m*/
 * @param data
 */
private void setSessionCookie(AuthnProcessorData data) {
    Cookie sessionCookie = new Cookie(this.sessionTokenName, data.getSessionID());
    sessionCookie.setDomain(this.sessionDomain);
    sessionCookie.setMaxAge(-1); // negative indicates session scope cookie
    sessionCookie.setPath("/");

    data.getHttpResponse().addCookie(sessionCookie);
}

From source file:de.metas.procurement.webui.service.impl.LoginRememberMeService.java

private void createRememberMeCookie(final User user) {
    try {//w ww. jav a 2 s . c o  m
        final String rememberMeToken = createRememberMeToken(user);
        final Cookie rememberMeCookie = new Cookie(COOKIENAME_RememberMe, rememberMeToken);

        final int maxAge = (int) TimeUnit.SECONDS.convert(cookieMaxAgeDays, TimeUnit.DAYS);
        rememberMeCookie.setMaxAge(maxAge);

        final String path = "/"; // (VaadinService.getCurrentRequest().getContextPath());
        rememberMeCookie.setPath(path);
        VaadinService.getCurrentResponse().addCookie(rememberMeCookie);
        logger.debug("Cookie added for {}: {} (maxAge={}, path={})", user, rememberMeToken, maxAge, path);
    } catch (final Exception e) {
        logger.warn("Failed creating cookie for user: {}. Skipped.", user, e);
    }
}

From source file:org.b3log.solo.processor.LoginProcessor.java

/**
 * Tries to login with cookie./*from w  w  w  . j  a va  2s.co  m*/
 *
 * @param request the specified request
 * @param response the specified response
 */
public static void tryLogInWithCookie(final HttpServletRequest request, final HttpServletResponse response) {
    final Cookie[] cookies = request.getCookies();
    if (null == cookies || 0 == cookies.length) {
        return;
    }

    try {
        for (int i = 0; i < cookies.length; i++) {
            final Cookie cookie = cookies[i];

            if (!"b3log-latke".equals(cookie.getName())) {
                continue;
            }

            final JSONObject cookieJSONObject = new JSONObject(cookie.getValue());

            final String userEmail = cookieJSONObject.optString(User.USER_EMAIL);
            if (Strings.isEmptyOrNull(userEmail)) {
                break;
            }

            final JSONObject user = userQueryService.getUserByEmail(userEmail.toLowerCase().trim());
            if (null == user) {
                break;
            }

            final String userPassword = user.optString(User.USER_PASSWORD);
            final String hashPassword = cookieJSONObject.optString(User.USER_PASSWORD);
            if (MD5.hash(userPassword).equals(hashPassword)) {
                Sessions.login(request, response, user);
                LOGGER.log(Level.INFO, "Logged in with cookie[email={0}]", userEmail);
            }
        }
    } catch (final Exception e) {
        LOGGER.log(Level.WARNING, "Parses cookie failed, clears the cookie[name=b3log-latke]", e);

        final Cookie cookie = new Cookie("b3log-latke", null);
        cookie.setMaxAge(0);
        cookie.setPath("/");

        response.addCookie(cookie);
    }
}

From source file:it.scoppelletti.programmerpower.web.security.SsoRememberMeServices.java

/**
 * Inizializza il cookie per l&rsquo;autenticazione persistente.
 * //from  ww  w  .  ja  va 2 s.  c  o m
 * @param  value  Valore.
 * @param  maxAge Scadenza.
 * @return        Oggetto.
 */
private Cookie buildCookie(String value, int maxAge) {
    Cookie cookie;

    cookie = new Cookie(getCookieName(), value);
    if (myCookieDomain != null) {
        cookie.setDomain(myCookieDomain);
    }
    cookie.setPath(myCookiePath);
    cookie.setMaxAge(maxAge);

    return cookie;
}

From source file:com.ctc.storefront.controllers.pages.CartPageController.java

private void setCookie(final HttpServletResponse response, final CartData cartData) {
    final Cookie cookie = new Cookie("cartQuantity", String.valueOf(cartData.getTotalUnitCount()));
    cookie.setMaxAge(60 * 60);//from   w  w w  .  j av a2  s  .com
    cookie.setPath("/");
    cookie.setDomain(getSiteConfigService().getString(CART_COUNT_COOKIE_DOMAIN_NAME, ".ctc.com"));
    response.addCookie(cookie);
}

From source file:hudson.Functions.java

/**
 * Used by <tt>layout.jelly</tt> to control the auto refresh behavior.
 *
 * @param noAutoRefresh/*from w w  w  .j  ava  2 s  . com*/
 *      On certain pages, like a page with forms, will have annoying interference
 *      with auto refresh. On those pages, disable auto-refresh.
 */
public static void configureAutoRefresh(HttpServletRequest request, HttpServletResponse response,
        boolean noAutoRefresh) {
    if (noAutoRefresh)
        return;

    String param = request.getParameter("auto_refresh");
    boolean refresh = isAutoRefresh(request);
    if (param != null) {
        refresh = Boolean.parseBoolean(param);
        Cookie c = new Cookie("hudson_auto_refresh", Boolean.toString(refresh));
        // Need to set path or it will not stick from e.g. a project page to the dashboard.
        // Using request.getContextPath() might work but it seems simpler to just use the hudson_ prefix
        // to avoid conflicts with any other web apps that might be on the same machine.
        c.setPath("/");
        c.setMaxAge(60 * 60 * 24 * 30); // persist it roughly for a month
        response.addCookie(c);
    }
    if (refresh) {
        response.addHeader("Refresh", "10");
    }
}

From source file:org.acegisecurity.ui.rememberme.TokenBasedRememberMeServices.java

protected Cookie makeValidCookie(String tokenValueBase64, HttpServletRequest request, long maxAge) {
    Cookie cookie = new Cookie(cookieName, tokenValueBase64);
    cookie.setMaxAge(new Long(maxAge).intValue());
    cookie.setPath(StringUtils.hasLength(request.getContextPath()) ? request.getContextPath() : "/");

    return cookie;
}

From source file:com.zz.globalsession.filter.AbstractGlobalSessionFilter.java

private Cookie generateSessionIdCookie(String sessionIdValue) {

    Cookie sessionIdCookie = new Cookie(settings.getSessionIdKey(), sessionIdValue);
    if (settings.getDomain() != null) {
        sessionIdCookie.setDomain(settings.getDomain());
    }//from   w w  w.  ja v  a2s  .  com
    if (settings.getPath() != null) {
        sessionIdCookie.setPath(settings.getPath());
    } else {
        sessionIdCookie.setPath("/");
    }
    if (settings.isSecure())
        sessionIdCookie.setSecure(settings.isSecure());
    // [Note] httpOnly is not supported by Servlet API 2.x, so add it
    // manually later.
    return sessionIdCookie;
}