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:com.expressui.core.MainApplication.java

/**
 * Adds a cookie to the HTTP response./*from   ww w .j av  a  2  s  .  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:org.apache.tapestry.ApplicationServlet.java

/**
 *  Invoked from the {@link IEngine engine}, just prior to starting to
 *  render a response, when the locale has changed.  The servlet writes a
 *  {@link Cookie} so that, on subsequent request cycles, an engine localized
 *  to the selected locale is chosen.//from w  ww.java 2s.co m
 *
 *  <p>At this time, the cookie is <em>not</em> persistent.  That may
 *  change in subsequent releases.
 *
 *  @since 1.0.1
 **/

public void writeLocaleCookie(Locale locale, IEngine engine, RequestContext cycle) {
    if (LOG.isDebugEnabled())
        LOG.debug("Writing locale cookie " + locale);

    Cookie cookie = new Cookie(LOCALE_COOKIE_NAME, locale.toString());
    cookie.setPath(engine.getServletPath());

    cycle.addCookie(cookie);
}

From source file:CookieServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {

    Cookie cookie = null;
    Cookie[] cookies = request.getCookies();
    boolean newCookie = false;

    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equals("mycookie")) {
                cookie = cookies[i];/*from  w ww.jav a  2 s  . c om*/
            }
        }
    }
    if (cookie == null) {
        newCookie = true;
        int maxAge;
        try {
            maxAge = new Integer(getServletContext().getInitParameter("cookie-age")).intValue();
        } catch (Exception e) {
            maxAge = -1;
        }

        cookie = new Cookie("mycookie", "" + getNextCookieValue());
        cookie.setPath(request.getContextPath());
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();

    out.println("<html>");
    out.println("<head>");
    out.println("<title>Cookie info</title>");
    out.println("</head>");
    out.println("<body>");

    out.println("<h2> Information about the cookie named \"mycookie\"</h2>");

    out.println("Cookie value: " + cookie.getValue() + "<br>");
    if (newCookie) {
        out.println("Cookie Max-Age: " + cookie.getMaxAge() + "<br>");
        out.println("Cookie Path: " + cookie.getPath() + "<br>");
    }

    out.println("</body>");
    out.println("</html>");

    out.close();
}

From source file:com.tremolosecurity.proxy.SessionManagerImpl.java

private HttpSession createOpenSession(HttpServletRequest req, HttpServletResponse resp, ServletContext ctx)
        throws Exception {

    byte[] idBytes = new byte[20];
    random.nextBytes(idBytes);// ww  w. j a v  a 2 s .co  m
    StringBuffer b = new StringBuffer();
    b.append('f').append(Hex.encodeHexString(idBytes));
    String id = b.toString();

    // HttpSession session = req.getSession(true);
    TremoloHttpSession tsession = new TremoloHttpSession(id);
    tsession.setOpen(true);
    tsession.refresh(this.ctx, this);
    this.anonMech.createSession(tsession, this.anonChainType);

    AuthController actl = (AuthController) tsession.getAttribute(ProxyConstants.AUTH_CTL);

    AuthInfo auInfo = actl.getAuthInfo();
    auInfo.setAuthComplete(true);

    // session.setAttribute(app.getCookieConfig().getSessionCookieName(),
    // tsession);

    tsession.setAttribute(OpenUnisonConstants.TREMOLO_SESSION_ID, id);

    // TODO add global session timeout
    // tsession.setMaxInactiveInterval(app.getCookieConfig().getTimeout());

    // TODO add global open session name
    Cookie sessionCookie = new Cookie(cfg.getCfg().getApplications().getOpenSessionCookieName(), id);

    sessionCookie.setPath("/");
    sessionCookie.setSecure(cfg.getCfg().getApplications().isOpenSessionSecure());
    sessionCookie.setHttpOnly(cfg.getCfg().getApplications().isOpenSessionHttpOnly());
    sessionCookie.setMaxAge(-1);
    // TODO add secure?
    // sessionCookie.setSecure(app.getCookieConfig().isSecure());
    resp.addCookie(sessionCookie);

    sessions.put(id, tsession);

    return tsession;
}

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

/**
 * Setup a cookie: expiration date, path, domain + send it to the response.
 * /*from   ww w .  j ava  2s  .  co  m*/
 * @param cookie The cookie to setup.
 * @param sessionCookie Whether the cookie is only for this session, or for a longer period.
 * @param cookieDomain The domain for which the cookie is set.
 * @param response The servlet response.
 */
public void setupCookie(Cookie cookie, boolean sessionCookie, String cookieDomain,
        HttpServletResponse response) {
    if (!sessionCookie) {
        setMaxAge(cookie);
    }
    cookie.setPath(this.cookiePath);
    if (cookieDomain != null) {
        cookie.setDomain(cookieDomain);
    }
    addCookie(response, cookie);
}

From source file:com.taobao.ad.easyschedule.exsession.request.session.SessionCookieStore.java

/**
 * @param response/*  www  . j a va 2s  .  c  o  m*/
 * @param config
 * @param value
 * 
 * @throws Exception
 */
private void saveCookie(HttpServletResponse response, SessionAttributeConfig config, Object value)
        throws Exception {
    String cookieName = config.getNickName();
    int lifeTime = config.getLifeTime();

    //COOKIE
    String attrValue = getEncodedValue(config, value);
    Cookie cookie = null;

    if (attrValue != null) {
        // if (config.isEncrypt()) {
        attrValue = URLEncoder.encode(attrValue, "UTF-8");
        // }

        cookie = new Cookie(cookieName, attrValue);
    } else {
        cookie = new Cookie(cookieName, "");
    }

    log.debug("cookie name: " + cookieName + "  cookie value: " + attrValue);

    //COOKIE
    String cookiePath = COOKIE_PATH;

    if (config.getCookiePath() != null) {
        cookiePath = config.getCookiePath();
    }

    cookie.setPath(cookiePath);

    if (lifeTime > 0) {
        cookie.setMaxAge(lifeTime);
    }

    String domain = config.getDomain();

    if ((domain != null) && (domain.length() > 0)) {
        cookie.setDomain(domain);
    }

    response.addCookie(cookie);
}

From source file:com.google.gsa.valve.modules.ldap.LDAPSSO.java

/**
 * Sets the LDAP authentication cookie//from  w w w  . ja v  a  2  s.co  m
 * 
 * @return the LDAP authentication cookie
 */
public Cookie settingCookie() {
    // Instantiate a new cookie
    Cookie extAuthCookie = new Cookie(SSO_COOKIE_NAME, "true");
    String authCookieDomain = null;
    String authCookiePath = null;

    // Cache cookie properties
    authCookieDomain = valveConf.getAuthCookieDomain();
    authCookiePath = valveConf.getAuthCookiePath();

    // Set extra cookie parameters
    extAuthCookie.setDomain(authCookieDomain);
    extAuthCookie.setPath(authCookiePath);
    extAuthCookie.setMaxAge(authMaxAge);

    // Log info
    logger.debug("Adding cookie: " + extAuthCookie.getName() + ":" + extAuthCookie.getValue() + ":"
            + extAuthCookie.getPath() + ":" + extAuthCookie.getDomain() + ":" + extAuthCookie.getSecure());

    return extAuthCookie;
}

From source file:org.kuali.mobility.shared.controllers.HomeController.java

/**
 * Controller method for the preference screen
 */// w  w w  .ja v a 2  s  . c  om
@RequestMapping(value = "preferences", method = RequestMethod.GET)
public String preferences(@CookieValue(value = "homeLayout", required = false) String homeLayoutCookie,
        @RequestParam(value = "homeLayout", required = false) String homeLayoutParam,
        HttpServletRequest request, HttpServletResponse response, Model uiModel) {
    User user = (User) request.getSession().getAttribute(Constants.KME_USER_KEY);
    String homeToolName = "home";
    List<Campus> campuses = getCampusService().findCampusesByTool(homeToolName);
    List<HomeScreen> homeScreens = getAdminService().getAllHomeScreens();

    String currentLayout = homeLayoutCookie;

    boolean useSecureCookie = Boolean
            .parseBoolean(this.getKmeProperties().getProperty("kme.secure.cookie", "false"));
    // Change layout if requested
    if (!StringUtils.isEmpty(homeLayoutParam)) {
        currentLayout = LayoutUtil.getValidLayout(homeLayoutParam, kmeProperties);
        Cookie layoutCookie = new Cookie("homeLayout", currentLayout);
        int cookieMaxAge = Integer.parseInt(getKmeProperties().getProperty("cookie.max.age", "3600"));
        layoutCookie.setMaxAge(cookieMaxAge); // default one hour, should implement in kme.config.properties.
        layoutCookie.setPath(request.getContextPath());
        layoutCookie.setSecure(useSecureCookie);
        response.addCookie(layoutCookie);
    }

    // Determine current home layout
    boolean allowLayoutChange = false;
    if (kmeProperties != null) {
        allowLayoutChange = Boolean
                .parseBoolean(kmeProperties.getProperty("home.layout.userEditable", "false"));
        if (allowLayoutChange) {
            currentLayout = LayoutUtil.getValidLayout(currentLayout, kmeProperties);
            uiModel.addAttribute("currentLayout", currentLayout);
            uiModel.addAttribute("availableLayouts", HomeScreen.LAYOUTS);
        }
    }

    List<Sender> senders = senderService.findAllUnhiddenSenders();

    // Add attributes to model
    uiModel.addAttribute("senders", senders);
    uiModel.addAttribute("toolName", homeToolName);
    uiModel.addAttribute("campuses", campuses);
    uiModel.addAttribute("homeScreens", homeScreens);
    uiModel.addAttribute("user", user);
    uiModel.addAttribute("supportedLanguages", getSupportedLanguages());
    uiModel.addAttribute("allowLayoutChange", allowLayoutChange);
    if ("3".equalsIgnoreCase(getKmeProperties().getProperty("kme.uiVersion", "classic"))) {
        return "ui3/home/preferences";
    }
    return "preferences";
}

From source file:org.b3log.solo.util.Solos.java

/**
 * Gets the current logged-in user.//from   w w w.j  a v a 2  s  .  c  o  m
 *
 * @param request  the specified request
 * @param response the specified response
 * @return the current logged-in user, returns {@code null} if not found
 */
public static JSONObject getCurrentUser(final HttpServletRequest request, final HttpServletResponse response) {
    final Cookie[] cookies = request.getCookies();
    if (null == cookies || 0 == cookies.length) {
        return null;
    }

    final BeanManager beanManager = BeanManager.getInstance();
    final UserRepository userRepository = beanManager.getReference(UserRepository.class);
    try {
        for (int i = 0; i < cookies.length; i++) {
            final Cookie cookie = cookies[i];
            if (!COOKIE_NAME.equals(cookie.getName())) {
                continue;
            }

            final String value = Crypts.decryptByAES(cookie.getValue(), COOKIE_SECRET);
            final JSONObject cookieJSONObject = new JSONObject(value);

            final String userId = cookieJSONObject.optString(Keys.OBJECT_ID);
            if (StringUtils.isBlank(userId)) {
                break;
            }

            JSONObject user = userRepository.get(userId);
            if (null == user) {
                break;
            }

            final String userPassword = user.optString(User.USER_PASSWORD);
            final String token = cookieJSONObject.optString(Keys.TOKEN);
            final String hashPassword = StringUtils.substringBeforeLast(token, ":");
            if (userPassword.equals(hashPassword)) {
                login(user, response);

                return user;
            }
        }
    } catch (final Exception e) {
        LOGGER.log(Level.TRACE, "Parses cookie failed, clears the cookie [name=" + COOKIE_NAME + "]");

        final Cookie cookie = new Cookie(COOKIE_NAME, null);
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    return null;
}

From source file:org.jasig.portal.portlet.dao.jpa.PortletCookieImpl.java

@Override
public Cookie toCookie() {
    Cookie cookie = new Cookie(this.name, this.value);
    cookie.setComment(this.comment);
    if (this.domain != null) {
        // FYI: setDomain requires non-null argument (requirement not documented)
        cookie.setDomain(this.domain);
    }//from   ww  w .  j  a  v a 2s.co m

    final int maxAge;
    if (this.expires == null) {
        maxAge = -1;
    } else {
        maxAge = (int) TimeUnit.MILLISECONDS.toSeconds(this.expires.getTime() - System.currentTimeMillis());
    }
    cookie.setMaxAge(maxAge);
    cookie.setPath(this.path);
    cookie.setSecure(this.secure);
    cookie.setVersion(this.version);
    return cookie;
}