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:cn.vlabs.umt.ui.servlet.login.LoginMethod.java

public static void generateAutoFill(HttpServletResponse response, HttpServletRequest request,
        LoginInfo loginInfo) {//w w  w .  jav a  2 s  .co  m
    Cookie autoFill = new Cookie(Attributes.AUTO_FILL, loginInfo.getLoginNameInfo().getLoginName());
    autoFill.setPath("/");
    autoFill.setMaxAge(Integer.MAX_VALUE);
    response.addCookie(autoFill);
}

From source file:com.liusoft.dlog4j.util.RequestUtils.java

/**
 * COOKIE//from  ww  w .j a va 2  s .  com
 * 
 * @param name
 * @param value
 * @param maxAge
 */
public static void setCookie(HttpServletRequest request, HttpServletResponse response, String name,
        String value, int maxAge) {
    Cookie cookie = new Cookie(name, value);
    cookie.setMaxAge(maxAge);
    String serverName = request.getServerName();
    String domain = getDomainOfServerName(serverName);
    if (domain != null && domain.indexOf('.') != -1) {
        cookie.setDomain('.' + domain);
    }
    cookie.setPath("/");
    response.addCookie(cookie);
}

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

/**
 * Logins the specified user from the specified request.
 *
 * @param response the specified response
 * @param user     the specified user, for example,
 *                 {//w  ww .  java2  s .c o m
 *                 "userEmail": "",
 *                 "userPassword": ""
 *                 }
 */
public static void login(final JSONObject user, final HttpServletResponse response) {
    try {
        final String userId = user.optString(Keys.OBJECT_ID);
        final JSONObject cookieJSONObject = new JSONObject();
        cookieJSONObject.put(Keys.OBJECT_ID, userId);
        cookieJSONObject.put(User.USER_PASSWORD, user.optString(User.USER_PASSWORD));

        final String random = RandomStringUtils.randomAlphanumeric(16);
        cookieJSONObject.put(Keys.TOKEN, user.optString(User.USER_PASSWORD) + ":" + random);

        final String cookieValue = Crypts.encryptByAES(cookieJSONObject.toString(), COOKIE_SECRET);
        final Cookie cookie = new Cookie(COOKIE_NAME, cookieValue);
        cookie.setPath("/");
        cookie.setMaxAge(COOKIE_EXPIRY);
        cookie.setHttpOnly(COOKIE_HTTP_ONLY);
        response.addCookie(cookie);
    } catch (final Exception e) {
        LOGGER.log(Level.WARN, "Can not write cookie", e);
    }
}

From source file:com.ofbizcn.securityext.login.LoginEvents.java

public static void setUsername(HttpServletRequest request, HttpServletResponse response) {
    HttpSession session = request.getSession();
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    String domain = EntityUtilProperties.getPropertyValue("url.properties", "cookie.domain", delegator);
    // first try to get the username from the cookie
    synchronized (session) {
        if (UtilValidate.isEmpty(getUsername(request))) {
            // create the cookie and send it back
            Cookie cookie = new Cookie(usernameCookieName, request.getParameter("USERNAME"));
            cookie.setMaxAge(60 * 60 * 24 * 365);
            cookie.setPath("/");
            cookie.setDomain(domain);/*w  w  w.j ava 2s  .  c o  m*/
            response.addCookie(cookie);
        }
    }
}

From source file:org.b3log.latke.util.Requests.java

/**
 * Determines whether the specified request has been served.
 * //from   w  w w .  ja  v  a  2  s.c  o m
 * <p>
 * A "served request" is a request a URI as former one. For example, if a client is request "/test", all requests from the client 
 * subsequent in 24 hours will be treated as served requests, requested URIs save in client cookie (name: "visited").
 * </p>
 * 
 * <p>
 * If the specified request has not been served, appends the request URI in client cookie. 
 * </p>
 * 
 * <p>
 * Sees this issue (https://github.com/b3log/b3log-solo/issues/44) for more details.
 * </p>
 * 
 * @param request the specified request
 * @param response the specified response
 * @return {@code true} if the specified request has been served, returns {@code false} otherwise
 */
public static boolean hasBeenServed(final HttpServletRequest request, final HttpServletResponse response) {
    final Cookie[] cookies = request.getCookies();

    if (null == cookies || 0 == cookies.length) {
        return false;
    }

    Cookie cookie;
    boolean needToCreate = true;
    boolean needToAppend = true;
    JSONArray cookieJSONArray = null;

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

            if (!"visited".equals(cookie.getName())) {
                continue;
            }

            cookieJSONArray = new JSONArray(cookie.getValue());
            if (null == cookieJSONArray || 0 == cookieJSONArray.length()) {
                return false;
            }

            needToCreate = false;

            for (int j = 0; j < cookieJSONArray.length(); j++) {
                final String visitedURL = cookieJSONArray.optString(j);

                if (request.getRequestURI().equals(visitedURL)) {
                    needToAppend = false;
                    return true;
                }
            }
        }

        if (needToCreate) {
            final StringBuilder builder = new StringBuilder("[").append("\"").append(request.getRequestURI())
                    .append("\"]");

            final Cookie c = new Cookie("visited", builder.toString());

            c.setMaxAge(COOKIE_EXPIRY);
            c.setPath("/");
            response.addCookie(c);
        } else if (needToAppend) {
            cookieJSONArray.put(request.getRequestURI());

            final Cookie c = new Cookie("visited", cookieJSONArray.toString());

            c.setMaxAge(COOKIE_EXPIRY);
            c.setPath("/");
            response.addCookie(c);
        }
    } catch (final Exception e) {
        LOGGER.log(Level.WARNING, "Parses cookie failed, clears the cookie[name=visited]", e);

        final Cookie c = new Cookie("visited", null);

        c.setMaxAge(0);
        c.setPath("/");

        response.addCookie(c);
    }

    return false;
}

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

/**
 * Logouts the specified user./*from www  . j  a v a  2s. c om*/
 *
 * @param request  the specified request
 * @param response the specified response
 * @return {@code true} if succeed, otherwise returns {@code false}
 */
public static void logout(final HttpServletRequest request, final HttpServletResponse response) {
    if (null != response) {
        final Cookie cookie = new Cookie(COOKIE_NAME, null);
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);
    }
}

From source file:org.apache.ofbiz.securityext.login.LoginEvents.java

public static void setUsername(HttpServletRequest request, HttpServletResponse response) {
    HttpSession session = request.getSession();
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    String domain = EntityUtilProperties.getPropertyValue("url", "cookie.domain", delegator);
    // first try to get the username from the cookie
    synchronized (session) {
        if (UtilValidate.isEmpty(getUsername(request))) {
            // create the cookie and send it back
            Cookie cookie = new Cookie(usernameCookieName, request.getParameter("USERNAME"));
            cookie.setMaxAge(60 * 60 * 24 * 365);
            cookie.setPath("/");
            cookie.setDomain(domain);/*from w w w .  j a  v  a 2s.c o m*/
            response.addCookie(cookie);
        }
    }
}

From source file:org.exoplatform.social.webui.Utils.java

/**
 * /*from  w  ww.  jav  a  2s.  c om*/
 * @param value
 */
public static void setCookies(String key, String value) {
    //
    removeCookie(key);

    //
    PortalRequestContext request = Util.getPortalRequestContext();
    Cookie cookie = new Cookie(key, value);
    cookie.setPath(request.getRequest().getContextPath());
    cookie.setMaxAge(Integer.MAX_VALUE);
    request.getResponse().addCookie(cookie);
}

From source file:org.itracker.web.util.LoginUtilities.java

public static User setupSession(User user, String encPassword, HttpServletRequest request,
        HttpServletResponse response) {/*ww w .  ja  va 2s. c  o  m*/
    if (user == null) {
        logger.warn("setupSession: null user", (logger.isDebugEnabled() ? new RuntimeException() : null));
        throw new IllegalArgumentException("null user");
    }

    UserService userService = ServletContextUtils.getItrackerServices().getUserService();

    if (logger.isDebugEnabled()) {
        logger.debug("Creating new session");
    }
    HttpSession session = request.getSession(true);

    if (logger.isDebugEnabled()) {
        logger.debug("Setting session timeout to " + getConfiguredSessionTimeout() + " minutes");
    }
    session.setMaxInactiveInterval(getConfiguredSessionTimeout() * 60);

    if (logger.isDebugEnabled()) {
        logger.debug("Setting session tracker");
    }
    session.setAttribute(Constants.SESSION_TRACKER_KEY, new SessionTracker(user.getLogin(), session.getId()));

    if (logger.isDebugEnabled()) {
        logger.debug("Setting user information");
    }
    session.setAttribute(Constants.USER_KEY, user);

    if (logger.isDebugEnabled()) {
        logger.debug("Setting preferences for user " + user.getLogin());
    }
    UserPreferences userPrefs = user.getPreferences();
    // TODO : this is a hack, remove when possible
    if (userPrefs == null) {
        logger.warn("setupSession: got user with no preferences!: " + user + " (prefs: " + user.getPreferences()
                + ")");
        userPrefs = new UserPreferences();
    }
    session.setAttribute(Constants.PREFERENCES_KEY, userPrefs);

    if (logger.isDebugEnabled()) {
        logger.debug("Setting user " + user + " locale to "
                + ITrackerResources.getLocale(userPrefs.getUserLocale()));
    }
    session.setAttribute(Constants.LOCALE_KEY, ITrackerResources.getLocale(userPrefs.getUserLocale()));

    // TODO: cookie could be removed
    Cookie cookie = new Cookie(Constants.COOKIE_NAME, "");
    cookie.setPath(request.getContextPath());

    cookie.setValue("");
    cookie.setMaxAge(0);

    response.addCookie(cookie);

    if (logger.isDebugEnabled()) {
        logger.debug("Setting permissions for user " + user.getLogin());
    }
    Map<Integer, Set<PermissionType>> usersMapOfProjectIdsAndSetOfPermissionTypes = userService
            .getUsersMapOfProjectIdsAndSetOfPermissionTypes(user, AuthenticationConstants.REQ_SOURCE_WEB);
    session.setAttribute(Constants.PERMISSIONS_KEY, usersMapOfProjectIdsAndSetOfPermissionTypes);

    // Reset some session forms
    session.setAttribute(Constants.SEARCH_QUERY_KEY, null);

    SessionManager.clearSessionNeedsReset(user.getLogin());
    if (logger.isDebugEnabled()) {
        logger.debug("User session data updated.");
    }
    return user;
}

From source file:com.shishu.utility.string.StringUtil.java

public static void setCookie(HttpServletResponse response, String CookieName, String CookieVal, int CookieAge)
        throws UnsupportedEncodingException {
    Cookie cookie = new Cookie(CookieName, URLEncoder.encode(CookieVal, "utf-8"));
    cookie.setMaxAge(CookieAge);//from w  w  w .  java2 s.  com
    cookie.setPath("/");
    response.addCookie(cookie);
}