Example usage for javax.servlet.http Cookie Cookie

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

Introduction

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

Prototype

public Cookie(String name, String value) 

Source Link

Document

Constructs a cookie with the specified name and value.

Usage

From source file:am.ik.categolj2.app.authentication.AuthenticationHelper.java

void saveAccessTokenInCookie(OAuth2AccessToken accessToken, HttpServletResponse response)
        throws UnsupportedEncodingException {
    Cookie accessTokenValueCookie = new Cookie(Categolj2Cookies.ACCESS_TOKEN_VALUE_COOKIE,
            URLEncoder.encode(accessToken.getValue(), "UTF-8"));
    accessTokenValueCookie.setMaxAge(accessToken.getExpiresIn());
    Cookie accessTokenExpireCookie = new Cookie(Categolj2Cookies.ACCESS_TOKEN_EXPIRATION_COOKIE,
            URLEncoder.encode(String.valueOf(accessToken.getExpiration().getTime()), "UTF-8"));
    accessTokenExpireCookie.setMaxAge(accessToken.getExpiresIn());

    response.addCookie(accessTokenValueCookie);
    response.addCookie(accessTokenExpireCookie);

    OAuth2RefreshToken refreshToken = accessToken.getRefreshToken();
    if (refreshToken != null) {
        Cookie refreshTokenCookie = new Cookie(Categolj2Cookies.REFRESH_TOKEN_VALUE_COOKIE,
                URLEncoder.encode(refreshToken.getValue(), "UTF-8"));
        refreshTokenCookie.setMaxAge(getRefreshTokenMaxAge(accessToken));
        response.addCookie(refreshTokenCookie);
    }//w  ww .j  a  va2 s  .  c  om
}

From source file:com.alfaariss.oa.util.web.CookieTool.java

/**
 * Set Cookie with optional extra context in application context
 * @param sCookie// w w w .  java2s .co  m
 * @param sValue
 * @param sExtraContext
 * @param oRequest
 * @return
 */
public Cookie createCookie(String sCookie, String sValue, String sExtraContext, HttpServletRequest oRequest) {
    assert sValue != null : "Supplied value == null";
    assert oRequest != null : "Supplied request == null";

    Cookie cookie = new Cookie(sCookie, sValue);
    if (_sCookieDomain != null) {
        cookie.setDomain(_sCookieDomain);
        _logger.debug("Created domain cookie on " + _sCookieDomain);
    }

    if (_iCookieVersion != -1) {
        cookie.setVersion(_iCookieVersion);
        _logger.debug("Setting cookie version: " + _iCookieVersion);
    }

    /* format sExtraContext */
    if (sExtraContext == null) {
        sExtraContext = "";
    } else {
        if (!sExtraContext.startsWith("/")) {
            sExtraContext = "/" + sExtraContext;
        }
    }

    String path = oRequest.getContextPath();
    if (path != null && path.length() > 0) {//only set path if path not is empty (when hosted as server root, getContextPath() will return an empty string)
        cookie.setPath(path + sExtraContext);// /openaselect
    } else {//if no contextpath available then setting the cookie path on '/' instead of on the default path (which is for the sso cookie: /openaselect/sso)
        cookie.setPath("/" + sExtraContext);
    }

    cookie.setSecure(_bSecureCookie);

    StringBuffer sbDebug = new StringBuffer("Created '");
    sbDebug.append(sCookie);
    sbDebug.append("' on path=");
    sbDebug.append(cookie.getPath());
    _logger.debug(sbDebug.toString());

    return cookie;
}

From source file:fi.hoski.web.auth.LoginServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setCharacterEncoding("UTF-8");

    response.setHeader("Cache-Control", "private, max-age=0, no-cache");
    String action = request.getParameter("action");
    try {/*  www  . j  a  va2  s . c o  m*/
        if (action == null || action.equals("login")) {
            // login

            String email = request.getParameter("email");
            String password = request.getParameter("password");
            email = (email != null) ? email.trim() : null;

            // 1. check params
            if (email == null || email.isEmpty() || password == null || password.isEmpty()) {
                log("email or password not ok");
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
            } else {
                // 2. check user exists
                Map<String, Object> user = userDirectory.authenticateUser(email, password);
                if (user == null) {
                    log("user not found");
                    response.sendError(HttpServletResponse.SC_FORBIDDEN);
                } else {
                    // 3. create session
                    HttpSession session = request.getSession(true);
                    session.setAttribute(USER, user);

                    response.getWriter().println("Logged in");
                }
            }
        } else {
            // logout

            HttpSession session = request.getSession(false);
            if (session != null) {
                session.setAttribute(USER, null);
                session.invalidate();
            }

            // change Cookie so that Vary: Cookie works
            Cookie c = new Cookie("JSESSIONID", null);
            c.setMaxAge(0);
            response.addCookie(c);

            response.getWriter().println("Logged out");
        }
    } catch (UnavailableException ex) {
        log(ex.getMessage(), ex);
        response.sendError(HttpServletResponse.SC_FORBIDDEN, ex.getMessage());
    } catch (EmailNotUniqueException ex) {
        log(ex.getMessage(), ex);
        response.sendError(HttpServletResponse.SC_FORBIDDEN, ex.getMessage());
    }
}

From source file:de.eorganization.hoopla.server.services.LoginServiceImpl.java

@Override
public LoginInfo login(String requestUri) {
    LoginInfo loginInfo = new LoginInfo();
    loginInfo.setLoggedIn(false);/*ww w.  j a v  a 2  s.  c o  m*/
    loginInfo.setLoginUrl(userService.createLoginURL(requestUri));

    Map<String, String> cookies = CookiesUtil.getCookiesStringMap(getThreadLocalRequest().getCookies());
    log.info("Got cookies " + cookies);
    String oauthService = cookies.get("oauth.service");

    log.info("Logging in with OAuth service " + oauthService);

    if (oauthService != null) {
        try {
            String accessTokenString = cookies.get("oauth.accessToken");
            String accessSecret = cookies.get("oauth.secret");
            if (accessTokenString == null)
                return loginInfo;

            log.info("Retrieved access token " + accessTokenString);
            Token accessToken = new Token(accessTokenString, accessSecret);
            log.info("Token object " + accessToken.getToken() + ", " + accessToken.getSecret());

            OAuth2Provider provider = OAuth2Provider.valueOf(oauthService);
            OAuthService service = provider.getOAuthService();

            Cookie serviceTokenCookie = new Cookie("oauth.service", provider.toString());
            serviceTokenCookie.setMaxAge(14 * 24 * 60 * 60);
            serviceTokenCookie.setPath("/");
            getThreadLocalResponse().addCookie(serviceTokenCookie);
            Cookie accessTokenCookie = new Cookie("oauth.accessToken", accessTokenString);
            accessTokenCookie.setMaxAge(14 * 24 * 60 * 60);
            accessTokenCookie.setPath("/");
            getThreadLocalResponse().addCookie(accessTokenCookie);
            Cookie accessSecretCookie = new Cookie("oauth.secret", accessSecret);
            accessSecretCookie.setMaxAge(14 * 24 * 60 * 60);
            accessSecretCookie.setPath("/");
            getThreadLocalResponse().addCookie(accessSecretCookie);

            if (OAuth2Provider.GOOGLE.equals(provider)) {
                OAuthRequest req = new OAuthRequest(Verb.GET, "https://www.googleapis.com/oauth2/v1/userinfo");
                service.signRequest(accessToken, req);
                Response response = req.send();
                log.info("Requested user info from google: " + response.getBody());

                JSONObject googleUserInfo = new JSONObject(response.getBody());
                log.info("got user info: " + googleUserInfo.getString("given_name") + ", "
                        + googleUserInfo.getString("family_name"));

                Member tempMember = new HooplaServiceImpl()
                        .findMemberBySocialId(googleUserInfo.getString("id"));

                if (tempMember == null) {
                    tempMember = new Member();

                    tempMember.setSocialId(googleUserInfo.getString("id"));
                    tempMember.setFirstname(googleUserInfo.getString("given_name"));
                    tempMember.setLastname(googleUserInfo.getString("family_name"));
                    tempMember.setNickname(googleUserInfo.getString("name"));
                    tempMember.setProfilePic(googleUserInfo.getString("picture"));

                    req = new OAuthRequest(Verb.GET, "https://www.googleapis.com/plus/v1/people/me");
                    service.signRequest(accessToken, req);
                    response = req.send();
                    log.info("Requested more user info from google: " + response.getBody());

                    JSONObject googleUserInfo2 = new JSONObject(response.getBody());
                    log.info("got user info: " + googleUserInfo2.getString("nickname") + ", "
                            + googleUserInfo2.getString("displayName"));
                    if (googleUserInfo2 != null && googleUserInfo2.getJSONArray("emails") != null)
                        for (int i = 0; i < googleUserInfo2.getJSONArray("emails").length(); i++) {
                            JSONObject emailInfo = googleUserInfo2.getJSONArray("emails").optJSONObject(i);
                            if (emailInfo != null && emailInfo.getBoolean("primary")) {
                                tempMember.setEmail(emailInfo.getString("value"));
                                tempMember = new HooplaServiceImpl().registerMember(tempMember);
                                loginInfo.setLoggedIn(true);
                                break;
                            }
                        }
                } else
                    loginInfo.setLoggedIn(true);

                loginInfo.setMember(tempMember);

            } else if (OAuth2Provider.TWITTER.equals(provider)) {
                OAuthRequest req = new OAuthRequest(Verb.GET,
                        "https://api.twitter.com/1/account/verify_credentials.json");
                service.signRequest(accessToken, req);
                log.info("Requesting from twitter " + req.getCompleteUrl());
                Response response = req.send();
                log.info("Requested user info from twitter: " + response.getBody());
                JSONObject twitterUserInfo = new JSONObject(response.getBody());
                log.info("got user info: " + twitterUserInfo.getString("name") + ", "
                        + twitterUserInfo.getString("screen_name"));

                Member tempMember = new HooplaServiceImpl()
                        .findMemberBySocialId(new Integer(twitterUserInfo.getInt("id")).toString());
                if (tempMember == null) {
                    tempMember = new Member();
                    tempMember.setSocialId(new Integer(twitterUserInfo.getInt("id")).toString());
                    tempMember.setFirstname(twitterUserInfo.getString("name").split(" ")[0]);
                    tempMember.setLastname(twitterUserInfo.getString("name").split(" ", 2)[1]);
                    tempMember.setNickname(twitterUserInfo.getString("screen_name"));
                    tempMember.setProfilePic(twitterUserInfo.getString("profile_image_url"));
                } else
                    loginInfo.setLoggedIn(true);
                loginInfo.setMember(tempMember);

            } else if (OAuth2Provider.FACEBOOK.equals(provider)) {
                OAuthRequest req = new OAuthRequest(Verb.GET, "https://graph.facebook.com/me");
                service.signRequest(accessToken, req);
                log.info("Requesting from facebook " + req.getCompleteUrl());
                Response response = req.send();
                log.info("Requested user info from facebook: " + response.getBody());
                JSONObject facebookUserInfo = new JSONObject(response.getBody());
                log.info("got user info: " + facebookUserInfo.getString("name") + ", "
                        + facebookUserInfo.getString("username"));

                Member tempMember = new HooplaServiceImpl()
                        .findMemberBySocialId(facebookUserInfo.getString("id"));
                if (tempMember == null) {
                    tempMember = new Member();
                    tempMember.setSocialId(new Integer(facebookUserInfo.getString("id")).toString());
                    tempMember.setFirstname(facebookUserInfo.getString("first_name"));
                    tempMember.setLastname(facebookUserInfo.getString("last_name"));
                    tempMember.setNickname(facebookUserInfo.getString("username"));
                    tempMember.setProfilePic("https://graph.facebook.com/" + facebookUserInfo.getString("id")
                            + "/picture?type=large");
                    tempMember.setEmail(facebookUserInfo.getString("email"));
                    tempMember = new HooplaServiceImpl().registerMember(tempMember);
                }

                loginInfo.setLoggedIn(true);
                loginInfo.setMember(tempMember);
            }
            loginInfo.setLogoutUrl("/logout/oauth");
            log.info("Set loginInfo to " + loginInfo);
            return loginInfo;
        } catch (Exception e) {
            log.log(Level.WARNING, e.getLocalizedMessage(), e);
        }
    } else {

        User user = userService.getCurrentUser();

        if (userService.isUserLoggedIn() && user != null) {
            loginInfo.setLoggedIn(true);
            loginInfo.setMember(new HooplaServiceImpl().saveOrGetMember(user));
            loginInfo.setLogoutUrl(userService.createLogoutURL(requestUri));
        }
        log.info("Logged in with google services " + loginInfo);
    }

    return loginInfo;

}

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

/**
 * @param response/*from w w w .j  av a2s. c o m*/
 * @param config
 * @param value
 * 
 * @throws Exception
 */
private void removeCookie(HttpServletResponse response, SessionAttributeConfig config) throws Exception {
    String cookieName = config.getNickName();

    Cookie cookie = new Cookie(cookieName, null);
    ;
    // COOKIE
    String cookiePath = COOKIE_PATH;

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

    cookie.setPath(cookiePath);

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

    cookie.setMaxAge(0);
    String domain = config.getDomain();

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

    response.addCookie(cookie);
}

From source file:com.wikipy.security.AuthenticationFilter.java

public static Cookie createNewCookie(HttpServletResponse httpResp) {
    Cookie cookie = new Cookie(ARG_TICKET, UUID.randomUUID().toString());
    cookie.setMaxAge(24 * 60 * 60);/*from   www. j  ava  2  s  .c o  m*/
    cookie.setPath("/");
    httpResp.addCookie(cookie);
    return cookie;
}

From source file:de.appsolve.padelcampus.utils.LoginUtil.java

private void deleteCookie(HttpServletRequest request, HttpServletResponse response, String path) {
    Cookie cookie = new Cookie(COOKIE_LOGIN_TOKEN, null);
    cookie.setDomain(request.getServerName());
    cookie.setMaxAge(0);//from w w  w .j  a va  2s  .  c  om
    if (!StringUtils.isEmpty(path)) {
        cookie.setPath(path);
    }
    response.addCookie(cookie);
}

From source file:com.tenduke.example.scribeoauth.SessionManager.java

/**
 * Creates an authenticated session./*from  w w w.j  a v a  2s . c  om*/
 * @param request Client HTTP request.
 * @param response HTTP response.
 * @param user User information as a JSON object.
 */
public void createSession(final HttpServletRequest request, final HttpServletResponse response,
        final JSONObject user) {
    //
    final String sessionId = UUID.randomUUID().toString();
    final SessionInformation sessionInfo = new SessionInformation(sessionId, user);
    //
    final String cookieValue = MessageFormat.format(SESSION_COOKIE_PATTERN, sessionId,
            resolveUserProfileId(user));
    //
    setSessionInformation(sessionInfo);
    //
    final Cookie cookie = new Cookie(SIGNED_SESSION_COOKIE_NAME, cookieValue);
    cookie.setMaxAge(COOKIE_MAX_AGE);
    cookie.setPath("/");
    response.addCookie(cookie);
}

From source file:net.lightbody.bmp.proxy.jetty.http.HashSSORealm.java

public void setSingleSignOn(HttpRequest request, HttpResponse response, Principal principal,
        Credential credential) {/*from   ww w .  ja v a2 s  .com*/

    String ssoID = null;

    synchronized (_ssoId2Principal) {
        // Create new SSO ID
        while (true) {
            ssoID = Long.toString(Math.abs(_random.nextLong()), 30 + (int) (System.currentTimeMillis() % 7));
            if (!_ssoId2Principal.containsKey(ssoID))
                break;
        }

        if (log.isDebugEnabled())
            log.debug("set ssoID=" + ssoID);
        _ssoId2Principal.put(ssoID, principal);
        _ssoPrincipal2Credential.put(principal, credential);
        _ssoUsername2Id.put(principal.getName(), ssoID);
    }

    Cookie cookie = new Cookie(SSO_COOKIE_NAME, ssoID);
    cookie.setPath("/");
    response.addSetCookie(cookie);
}

From source file:org.dspace.webmvc.theme.ThemeChangeInterceptor.java

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
        ModelAndView modelAndView) throws Exception {
    ThemeResolver themeResolver = RequestContextUtils.getThemeResolver(request);
    if (themeResolver == null) {
        throw new IllegalStateException("No ThemeResolver found: not in a DispatcherServlet request?");
    }//w  w w  . j  a  v  a2s . c  o m

    String newTheme = request.getParameter(this.paramName);
    if (newTheme != null) {
        themeResolver.setThemeName(request, response, newTheme);
        response.addCookie(new Cookie("themeName", newTheme));
    } else {
        ThemeMapEntry bestMatch = null;

        for (ThemeMapEntry entry : themeMappings) {

            if (entry.mapType == MapType.VIEW || entry.mapType == MapType.ANY) {
                if (modelAndView != null && pathMatcher.match(entry.path, modelAndView.getViewName())) {
                    if (entry.isBestMatch(bestMatch)) {
                        bestMatch = entry;
                    }
                }
            }

            if (entry.mapType == MapType.URL || entry.mapType == MapType.ANY) {
                String path = urlPathHelper.getLookupPathForRequest(request);
                if (pathMatcher.match(entry.path, path)) {
                    if (entry.isBestMatch(bestMatch)) {
                        bestMatch = entry;
                    }
                }
            }

            if (entry.mapType == MapType.CONTROLLER || entry.mapType == MapType.ANY) {

            }
        }

        if (bestMatch != null) {
            themeResolver.setThemeName(request, response, bestMatch.themeName);
        } else if (request.getCookies() != null) {
            for (Cookie cookie : request.getCookies()) {
                if ("themeName".equals(cookie.getName())) {
                    themeResolver.setThemeName(request, response, cookie.getValue());
                }
            }
        }
    }

    super.postHandle(request, response, handler, modelAndView);
}