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:com.tenduke.example.webadmin.SessionManager.java

/**
 * Creates an authenticated session./* w  w  w . j  a va  2  s. co  m*/
 * @param request Client HTTP request.
 * @param response HTTP response.
 * @param user User information as a JSON object.
 * @return Session information object as result.
 */
public SessionInformation 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);
    //
    return sessionInfo;
}

From source file:com.baron.bm.controller.MemberController.java

@RequestMapping("/logout") // 
public String logout(HttpServletRequest request, MemberModel model, HttpServletResponse response) {

    for (Cookie cookie : request.getCookies()) {
        if (cookie.getName().equals("bm_id")) {
            cookie.setMaxAge(0);/*from w  w w  .  jav  a 2  s  .  c  o  m*/
            model.setId("0");
            response.addCookie(new Cookie("bm_id", model.getId()));
        } else if (cookie.getName().equals("bm_permission")) {
            cookie.setMaxAge(0);
            model.setPermission("0");
            response.addCookie(new Cookie("bm_permission", model.getPermission()));
        }
    }
    return "logout";
}

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

@Override
public LoginInfo login(String requestUri) throws Exception {
    LoginInfo loginInfo = new LoginInfo();
    loginInfo.setLoggedIn(false);//from   w w  w .  ja  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 = AmiManager.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 = AmiManager.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 = AmiManager
                        .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 = AmiManager.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 = AmiManager.registerMember(tempMember);
                }

                loginInfo.setLoggedIn(true);
                loginInfo.setMember(tempMember);
            }
            loginInfo.setLogoutUrl("/logout/oauth");
            log.info("Set loginInfo to " + loginInfo);
            return loginInfo;
        } catch (OverQuotaException oqe) {
            log.log(Level.WARNING, oqe.getLocalizedMessage(), oqe);
            throw new OutOfQuotaException("Out of Quota!", oqe);
        } 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(AmiManager.saveOrGetMember(user));
            loginInfo.setLogoutUrl(userService.createLogoutURL(requestUri));
        }
        log.info("Logged in with google services " + loginInfo);
    }

    return loginInfo;

}

From source file:com.utest.webservice.impl.v2.UserWebServiceImpl.java

@PUT
@Path("/login")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Override/*from   ww w .j  a  va2 s  .  c o m*/
public Boolean login(@Context MessageContext context) throws Exception {
    Integer auth = UserUtil.getCurrentUserId();
    if (auth == null) {
        throw new org.apache.cxf.interceptor.security.AccessDeniedException("No logged in user!");
    }
    final AuthenticatedUserInfo authInfo = (AuthenticatedUserInfo) SecurityContextHolder.getContext()
            .getAuthentication().getPrincipal();
    String sessionId = SessionUtil.extractSession(context, true);
    userService.login(authInfo, sessionId);

    String token = Base64.encodeObject(SecurityContextHolder.getContext().getAuthentication(),
            Base64.GZIP | Base64.DONT_BREAK_LINES);
    Cookie loginCookie = new Cookie(SessionUtil.AUTH_TOKEN, token);
    // time to live
    loginCookie.setMaxAge(getLoginExpirationSeconds());
    context.getHttpServletResponse().addCookie(loginCookie);
    return Boolean.TRUE;
}

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

/**
 * cookie/*from ww  w .j a va 2 s .c om*/
 * 
 * @param request
 *            HttpServletRequest
 * @param response
 *            HttpServletResponse
 * @param name
 *            cookie??
 * @param path
 *            
 * @param domain
 *            
 */
public static void removeCookie(HttpServletRequest request, HttpServletResponse response, String name,
        String path, String domain) {
    Assert.notNull(request);
    Assert.notNull(response);
    Assert.hasText(name);
    try {
        name = URLEncoder.encode(name, "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:demo.oauth.client.controllers.TemporaryCredentialsController.java

@RequestMapping("/handleTemporaryCredentials")
public ModelAndView handleRequest(@ModelAttribute(value = "oAuthParams") OAuthParams oAuthParams,
        HttpServletResponse response) {//from   w  w  w.  ja  v  a  2  s .  c  o m

    OAuthServiceProvider provider;
    OAuthConsumer consumer;
    OAuthAccessor accessor;

    OAuthClient client = new OAuthClient(new URLConnectionClient());

    oAuthParams.setErrorMessage(null);
    String temporaryCredentialsEndpointUrl = oAuthParams.getTemporaryCredentialsEndpoint();
    if (temporaryCredentialsEndpointUrl == null || "".equals(temporaryCredentialsEndpointUrl)) {
        oAuthParams.setErrorMessage("Missing temporary credentials endpoint url");
    }
    String clientId = oAuthParams.getClientID();
    if (clientId == null || "".equals(clientId)) {
        oAuthParams.setErrorMessage("Missing client identifier");
    }
    String secret = oAuthParams.getClientSecret();
    if (secret == null || "".equals(secret)) {
        oAuthParams.setErrorMessage("Missing client shared-secret");
    }

    if (oAuthParams.getErrorMessage() == null) {
        provider = new OAuthServiceProvider(temporaryCredentialsEndpointUrl,
                oAuthParams.getResourceOwnerAuthorizationEndpoint(), oAuthParams.getTokenRequestEndpoint());
        consumer = new OAuthConsumer(null, clientId, secret, provider);
        accessor = new OAuthAccessor(consumer);

        Map<String, String> parameters = new HashMap<String, String>();
        parameters.put(OAuth.OAUTH_SIGNATURE_METHOD, oAuthParams.getSignatureMethod());
        parameters.put(OAuth.OAUTH_NONCE, UUID.randomUUID().toString());
        parameters.put(OAuth.OAUTH_TIMESTAMP, String.valueOf(System.currentTimeMillis() / 1000));
        parameters.put(OAuth.OAUTH_CALLBACK, oAuthParams.getCallbackURL());
        parameters.put("realm", "private");
        parameters.put("scope", "read_info modify_info");

        try {
            accessor.consumer.setProperty(OAuthClient.PARAMETER_STYLE, ParameterStyle.AUTHORIZATION_HEADER);
            client.getRequestToken(accessor, OAuthMessage.POST, parameters.entrySet());
        } catch (Exception e) {
            oAuthParams.setErrorMessage(e.toString());
        }

        oAuthParams.setOauthToken(accessor.requestToken);
        oAuthParams.setOauthTokenSecret(accessor.tokenSecret);
        Cookie cId = new Cookie("clientID", oAuthParams.getClientID());
        Cookie cSec = new Cookie("clientSecret", oAuthParams.getClientSecret());
        Cookie tokenSec = new Cookie("tokenSec", accessor.tokenSecret);
        response.addCookie(cId);
        response.addCookie(cSec);
        response.addCookie(tokenSec);
    }

    ModelAndView modelAndView = new ModelAndView();
    if (oAuthParams.getErrorMessage() != null) {
        modelAndView.setViewName("temporaryCredentials");
    } else {
        modelAndView.setViewName("authorizeResourceOwner");
    }

    return modelAndView;
}

From source file:io.syndesis.rest.v1.handler.connection.ConnectionHandler.java

@Override
public Connection create(@Context SecurityContext sec,
        @ConvertGroup(from = Default.class, to = AllValidations.class) final Connection connection) {
    final Date rightNow = new Date();
    final Connection updatedConnection = new Connection.Builder().createFrom(connection).createdDate(rightNow)
            .lastUpdated(rightNow).userId(sec.getUserPrincipal().getName()).build();

    final Set<CredentialFlowState> flowStates = CredentialFlowState.Builder.restoreFrom(state::restoreFrom,
            request);//from   w  ww. ja  va2s  . c o m

    final Connection connectionToCreate = flowStates.stream().map(s -> {
        final Cookie removal = new Cookie(s.persistenceKey(), "");
        removal.setPath("/");
        removal.setMaxAge(0);

        response.addCookie(removal);

        return credentials.apply(updatedConnection, s);
    }).findFirst().orElse(updatedConnection);

    return Creator.super.create(sec, connectionToCreate);
}

From source file:org.unidle.web.LocationMethodArgumentResolverTest.java

@Test
public void testResolveArgumentWithCookieOverride() throws Exception {
    mockRequest.setRemoteAddr(MELBOURNE.address);
    mockRequest.setCookies(new Cookie("address", SYDNEY.address));

    final Location result = (Location) subject.resolveArgument(null, null, new ServletWebRequest(mockRequest),
            null);/* w  w w.  j  av  a  2  s  .com*/

    assertThat(result).satisfies(hasCity("Sydney")).satisfies(hasSubdivision("New South Wales"))
            .satisfies(hasCountry("Australia")).satisfies(hasContinent("Oceania"));
}

From source file:org.mascherl.session.MascherlSessionStorage.java

public void saveSession(MascherlSession session, HttpServletResponse response) {
    if (!session.wasModified()) {
        return; // no need to update an unmodified session
    }//from w  w  w .  j  av a2s .c o m

    String data = session.serialize();
    if (data.length() > MAX_DATA_SIZE) {
        throw new IllegalStateException("Session data exceeds limit");
    }

    String encryptedValue = cryptoHelper.encryptAES(data);

    Cookie cookie = new Cookie(cookieName, encryptedValue);
    cookie.setMaxAge(EXPIRE_ON_BROWSER_CLOSE);
    response.addCookie(cookie);
}

From source file:org.sharetask.security.StoreUserInformationAuthenticationSuccessHandler.java

@Override
public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response,
        Authentication authentication) throws IOException, ServletException {

    if (authentication instanceof ClientAuthenticationToken) {
        log.debug("Token is pac4j token.");

        String language = Language.EN.getCode();
        UsernamePasswordAuthenticationToken authentToken;
        final CommonProfile profile = (CommonProfile) ((ClientAuthenticationToken) authentication)
                .getUserProfile();// w  w w . ja  v  a  2  s. c o m
        if (userRepository.findByUsername(profile.getEmail()) == null) {
            log.debug("User with name: {} doesne exist's. Will be created", profile.getEmail());
            final UserInformation userInformation = new UserInformation(profile.getEmail());
            userInformation.setName(profile.getFirstName());
            userInformation.setSurName(profile.getFamilyName());
            userInformation.setLanguage(language);
            final ArrayList<Role> list = new ArrayList<Role>();
            list.add(Role.ROLE_USER);
            userInformation.setRoles(list);
            userRepository.save(userInformation);
            final List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
            authorities.add(new SimpleGrantedAuthority(Role.ROLE_USER.name()));
            authentToken = new UsernamePasswordAuthenticationToken(profile.getEmail(), "", authorities);
        } else {
            final UserInformation user = userRepository.read(profile.getEmail());
            language = user.getLanguage();
            final Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            authentToken = new UsernamePasswordAuthenticationToken(profile.getEmail(), "", authorities);
        }
        // language cookie
        final Cookie locale = new Cookie(RequestUltil.LOCALE, language);
        locale.setMaxAge(-1);
        locale.setPath("/");
        response.addCookie(locale);

        SecurityContextHolder.getContext().setAuthentication(authentToken);
    }

    super.onAuthenticationSuccess(request, response, authentication);
}