Example usage for javax.servlet.http Cookie setDomain

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

Introduction

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

Prototype

public void setDomain(String domain) 

Source Link

Document

Specifies the domain within which this cookie should be presented.

Usage

From source file:cn.vlabs.umt.ui.servlet.login.LoginMethod.java

/**
 * ??cookie//  w w w .  j a  v a2 s .c  o m
 * */
public static void generateSsoCookie(HttpServletResponse response, HttpServletRequest request,
        LoginInfo loginInfo) throws UnsupportedEncodingException {
    PCookie pcookie = (PCookie) ServiceFactory.getBean(request, "PCookie");
    // Pcookie
    String encrypted = pcookie
            .encrypt(loginInfo.getUser().getCstnetId() + "/" + RequestUtil.getRemoteIP(request) + "/"
                    + loginInfo.getPasswordType() + "/" + System.currentTimeMillis());
    Cookie cookie = new Cookie(Attributes.COOKIE_NAME, encrypted);
    cookie.setPath("/");
    cookie.setMaxAge(MAX_COOKIE_AGE);
    response.addCookie(cookie);
    Cookie umtIdCookie = new Cookie(Attributes.SSO_FLAG, SessionUtils.getUserId(request) + "");
    umtIdCookie.setDomain(Attributes.SSO_FLAG_DOMAIN);
    umtIdCookie.setPath("/");
    umtIdCookie.setMaxAge(LoginMethod.MAX_COOKIE_AGE);
    response.addCookie(umtIdCookie);
}

From source file:com.anjz.util.CookieUtils.java

private static void setCookie(String key, String value, int maxAge, String path, String domainName,
        final boolean httpOnly, final boolean secure, HttpServletResponse response) {
    if (response != null) {
        Cookie cookie = new Cookie(key, value);
        cookie.setMaxAge(maxAge);//  w  w w .j  av a  2 s.  c o  m
        if (StringUtils.isNotBlank(path)) {
            cookie.setPath(path);
        } else {
            cookie.setPath(PATH);
        }
        if (StringUtils.isNotBlank(domainName)) {
            cookie.setDomain(domainName);
        }
        cookie.setVersion(0);
        cookie.setSecure(secure);
        if (httpOnly) {
            final StringBuffer buf = new StringBuffer();
            getCookieHeaderValue(cookie, buf, httpOnly);
            response.addHeader(getCookieHeaderName(cookie), buf.toString());
        } else {
            response.addCookie(cookie);
        }
    }
}

From source file:com.iterzp.momo.utils.WebUtils.java

/**
 * cookie//from www  . jav a 2s.  c  o  m
 * 
 * @param request
 *            HttpServletRequest
 * @param response
 *            HttpServletResponse
 * @param name
 *            cookie??
 * @param value
 *            cookie
 * @param maxAge
 *            (??: )
 * @param path
 *            
 * @param domain
 *            
 * @param secure
 *            ??
 */
public static void addCookie(HttpServletRequest request, HttpServletResponse response, String name,
        String value, Integer maxAge, String path, String domain, Boolean secure) {
    Assert.notNull(request);
    Assert.notNull(response);
    Assert.hasText(name);
    try {
        name = URLEncoder.encode(name, "UTF-8");
        value = URLEncoder.encode(value, "UTF-8");
        Cookie cookie = new Cookie(name, value);
        if (maxAge != null) {
            cookie.setMaxAge(maxAge);
        }
        if (StringUtils.isNotEmpty(path)) {
            cookie.setPath(path);
        }
        if (StringUtils.isNotEmpty(domain)) {
            cookie.setDomain(domain);
        }
        if (secure != null) {
            cookie.setSecure(secure);
        }
        response.addCookie(cookie);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
}

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);
            response.addCookie(cookie);/*from w  w w  . j  a v  a  2  s .com*/
        }
    }
}

From source file:com.o2o.util.WebUtils.java

public static void clearCookie(HttpServletRequest request, HttpServletResponse response, String path,
        String domain) {/*from ww  w.  j ava 2 s.c  om*/
    Assert.notNull(request);
    Assert.notNull(response);
    try {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie_old : cookies) {
            String name = URLEncoder.encode(cookie_old.getName(), "UTF-8");
            Cookie cookie = new Cookie(name, null);
            cookie.setMaxAge(0);
            if (StringUtils.isNotEmpty(path)) {
                cookie.setPath(path);
            }
            if (StringUtils.isNotEmpty(domain)) {
                cookie.setDomain(domain);
            }
            response.addCookie(cookie);
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
}

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);
            response.addCookie(cookie);//from  w  ww  .  j  a  v  a 2  s  . co  m
        }
    }
}

From source file:com.google.gsa.valve.modules.utils.CookieManagement.java

/**
 * Transforms Apache cookies into Servlet Cookies
 * /*from   w  ww  .  jav  a 2s  .  c  o m*/
 * @param apacheCookie apache cookie 
 * 
 * @return servlet cookie
 */
public static javax.servlet.http.Cookie transformApacheCookie(
        org.apache.commons.httpclient.Cookie apacheCookie) {

    javax.servlet.http.Cookie newCookie = null;

    if (apacheCookie != null) {
        Date expire = apacheCookie.getExpiryDate();
        int maxAge = -1;

        if (expire == null) {
            maxAge = -1;
        } else {
            Date now = Calendar.getInstance().getTime();
            // Convert milli-second to second
            Long second = new Long((expire.getTime() - now.getTime()) / 1000);
            maxAge = second.intValue();
        }

        newCookie = new javax.servlet.http.Cookie(apacheCookie.getName(), apacheCookie.getValue());
        //Hardcoding the domain
        newCookie.setDomain(apacheCookie.getDomain());
        newCookie.setPath(apacheCookie.getPath());
        newCookie.setMaxAge(maxAge);
        newCookie.setSecure(apacheCookie.getSecure());
    }
    return newCookie;
}

From source file:com.liferay.portal.action.LoginAction.java

public static void setLoginCookies(HttpServletRequest req, HttpServletResponse res, HttpSession ses,
        long userId, boolean rememberMe) throws PortalException, SystemException, EncryptorException {
    if (GetterUtil.getBoolean(PropsUtil.get(PropsUtil.SESSION_ENABLE_PHISHING_PROTECTION))) {

        // Invalidate the previous session to prevent phishing

        LastPath lastPath = (LastPath) ses.getAttribute(WebKeys.LAST_PATH);

        // GNOMON Gi9: KEEP ANY USER_CARRY ATTRIBUTES (for example shopping cart)
        HashMap userCarryAttributes = getUserCarryAttributes(ses);

        try {//from  w  w  w.  j a va  2 s  .c  o m
            ses.invalidate();
        } catch (Exception e) {
            _log.info("Session has already invalidated");
        }

        ses = req.getSession(true);

        addSessionAttributes(ses, userCarryAttributes);

        if (lastPath != null) {
            ses.setAttribute(WebKeys.LAST_PATH, lastPath);
        }
    }

    // Set cookies

    String domain = PropsUtil.get(PropsUtil.SESSION_COOKIE_DOMAIN);

    User user = UserLocalServiceUtil.getUserById(userId);
    Company company = CompanyLocalServiceUtil.getCompanyById(user.getCompanyId());
    String userIdString = String.valueOf(userId);

    ses.setAttribute("j_username", userIdString);
    ses.setAttribute("j_password", user.getPassword());
    ses.setAttribute("j_remoteuser", userIdString);

    ses.setAttribute(WebKeys.USER_PASSWORD, user.getPassword());

    Cookie idCookie = new Cookie(CookieKeys.ID, UserLocalServiceUtil.encryptUserId(userIdString));

    if (Validator.isNotNull(domain)) {
        idCookie.setDomain(domain);
    }

    idCookie.setPath(StringPool.SLASH);

    Cookie passwordCookie = new Cookie(CookieKeys.PASSWORD,
            Encryptor.encrypt(company.getKeyObj(), user.getPassword()));

    if (Validator.isNotNull(domain)) {
        passwordCookie.setDomain(domain);
    }

    passwordCookie.setPath(StringPool.SLASH);

    int loginMaxAge = GetterUtil.getInteger(PropsUtil.get(PropsUtil.COMPANY_SECURITY_AUTO_LOGIN_MAX_AGE),
            CookieKeys.MAX_AGE);

    if (GetterUtil.getBoolean(PropsUtil.get(PropsUtil.SESSION_DISABLED))) {

        rememberMe = true;
    }

    if (rememberMe) {
        idCookie.setMaxAge(loginMaxAge);
        passwordCookie.setMaxAge(loginMaxAge);
    } else {
        idCookie.setMaxAge(0);
        passwordCookie.setMaxAge(0);
    }

    Cookie loginCookie = new Cookie(CookieKeys.LOGIN, user.getLogin());

    if (Validator.isNotNull(domain)) {
        loginCookie.setDomain(domain);
    }

    loginCookie.setPath(StringPool.SLASH);
    loginCookie.setMaxAge(loginMaxAge);

    Cookie screenNameCookie = new Cookie(CookieKeys.SCREEN_NAME,
            Encryptor.encrypt(company.getKeyObj(), user.getScreenName()));

    if (Validator.isNotNull(domain)) {
        screenNameCookie.setDomain(domain);
    }

    screenNameCookie.setPath(StringPool.SLASH);
    screenNameCookie.setMaxAge(loginMaxAge);

    CookieKeys.addCookie(res, idCookie);
    CookieKeys.addCookie(res, passwordCookie);
    CookieKeys.addCookie(res, loginCookie);
    CookieKeys.addCookie(res, screenNameCookie);

    //add entry to user tracking if needed
    boolean trackUser = GetterUtil.getBoolean(PropsUtil.get(user.getCompanyId(), "gn.user.tracking.enabled"),
            false);
    if (trackUser) {
        GnUserTracking track = new GnUserTracking();
        track.setCompanyId(user.getCompanyId());
        track.setUserId(user.getUserId());
        track.setLoginDate(new Date());
        String fromIp = req.getHeader("X-Forwarded-For");
        if (Validator.isNull(fromIp))
            fromIp = req.getRemoteAddr() + (Validator.isNotNull(req.getRemoteHost())
                    && !req.getRemoteAddr().equals(req.getRemoteHost()) ? "( " + req.getRemoteHost() + " )"
                            : "");

        track.setFromIp(fromIp);
        GnPersistenceService.getInstance(null).createObject(track);
    }
    EventsService.getInstance().createEvent(user, "PortalAuth",
            "User " + user.getScreenName() + " has logged in " + req.getServerName(), "loginaction", null);
}

From source file:fi.helsinki.opintoni.security.CustomAuthenticationSuccessHandler.java

private void addCookie(HttpServletResponse response, Cookie cookie) {
    cookie.setDomain("helsinki.fi");
    cookie.setPath("/");
    response.addCookie(cookie);/*w w  w. j  a v a 2 s.c o  m*/
}

From source file:org.jasig.cas.web.support.CookieRetrievingCookieGeneratorTests.java

public void testCookieRetrieve() {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final Cookie cookie = new Cookie("test", "test");
    cookie.setDomain("cas.org");
    cookie.setMaxAge(5);/*from   www  .  j a  va 2 s . co m*/
    request.setCookies(new Cookie[] { cookie });

    assertEquals("test", this.g.retrieveCookieValue(request));

}