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.persistent.cloudninja.controller.TenantTaskListController.java

private Cookie getTenantLogoCookieInResponse(String tenantId, String cookieName) {
    String logoUrl = "";
    Tenant tenant = hibernateTemplate.get(Tenant.class, tenantId);
    String logoFilename = tenant.getLogoFileName();
    if (null == logoFilename || logoFilename.trim().length() == 0) {
        logoUrl = "";
    } else {//  w  w  w.ja  v a  2 s  .  c  o  m

        //create logo URL from config property file
        logoUrl = getLogoUrlFromConfig(logoFilename, tenantId);
    }
    Cookie logoCokie = new Cookie("CLOUDNINJALOGO", logoUrl);
    logoCokie.setMaxAge(-1);
    logoCokie.setPath("/");
    return logoCokie;

}

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

@Override
public LoginInfo login(String requestUri) {
    LoginInfo loginInfo = new LoginInfo();
    loginInfo.setLoggedIn(false);//w  ww.  j a va  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:de.eorganization.crawler.server.services.LoginServiceImpl.java

@Override
public LoginInfo login(String requestUri) throws Exception {
    LoginInfo loginInfo = new LoginInfo();
    loginInfo.setLoggedIn(false);//  w ww . java2 s  .co  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:es.pode.visualizador.presentacion.modificarPerfil.ModificarPerfilControllerImpl.java

/**
 * @see es.pode.administracion.presentacion.adminusuarios.modificarPerfil.ModificarPerfilController#modificarUsuarioMismo(org.apache.struts.action.ActionMapping,
 *      es.pode.administracion.presentacion.adminusuarios.modificarPerfil.ModificarUsuarioMismoForm,
 *      javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 *//*from ww  w  .  j  ava2s. c  o  m*/
public final void modificarUsuarioMismo(ActionMapping mapping,
        es.pode.visualizador.presentacion.modificarPerfil.ModificarUsuarioMismoForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

    String resultado = null;
    try {
        //String idiomaSelected = LdapUserDetailsUtils.getIdioma();
        String nombre = request.getParameter("nombre");
        String apellido1 = request.getParameter("apellido1");
        Long id = Long.valueOf(request.getParameter("id"));
        String apellido2 = request.getParameter("apellido2");
        String email = request.getParameter("email");
        String idioma = request.getParameter("idioma");
        String idiomaBusqueda = request.getParameter("idiomaBusqueda");
        String tipoEmpaquetador = request.getParameter("tipoEmpaquetador");
        String clave = request.getParameter("clave");
        String openIdUrl = request.getParameter("openIdUrl");
        String repitaClave = request.getParameter("repitaClave");
        String tipoCatalogador = request.getParameter("tipoCatalogador");
        long cuota = 0;
        Matcher matcher = null;
        if (request.getParameter("cuota").length() > 0) {
            Pattern maskNum = Pattern.compile("[0-9]+");
            matcher = maskNum.matcher(request.getParameter("cuota"));
            if (!matcher.matches()) {
                if (log.isDebugEnabled())
                    log.debug("cuota caracter ilegal");
                throw new ValidatorException("{errors.modificarusuario.cuota}");
            }
            cuota = Long.valueOf(request.getParameter("cuota")).longValue();
            cuota = cuota * 1024 * 1024;
        }

        UsuarioVO usuarioVO = this.getSrvAdminUsuariosService().descripcionUsuario(id);
        // Validaciones de los campos que recogemos del formulario
        Pattern mask = Pattern.compile("[^\\\\?\\\\!\\>\\#\\&\\<\\@\\$\\/\\\'\\\"]+");
        // Validaciones para password
        Pattern maskPwd = Pattern.compile("[^\\\\?\\\\!\\>\\#\\&\\<\\@\\$\\/\\\'\\\"]+");

        if (nombre.length() <= 0) {
            log("nombre.length() <= 0");
            throw new ValidatorException("{errors.modificarusuario.nombre}");
        }
        matcher = mask.matcher(nombre);
        if (!matcher.matches()) {
            log("nombre caracter ilegal");

            throw new ValidatorException("{errors.modificarusuario.nombre.caracterIlegal}");
        }

        if (apellido1.length() <= 0) {
            log("apellido1.length() <= 0");

            throw new ValidatorException("{errors.modificarusuario.apellido1}");
        }
        matcher = mask.matcher(apellido1);
        if (!matcher.matches()) {
            log("apellido1 caracter ilegal");
            throw new ValidatorException("{errors.modificarusuario.apellido1.caracterIlegal}");
        }
        if (apellido2.length() > 0) {
            matcher = mask.matcher(apellido2);
            if (!matcher.matches()) {
                log("apellido2 caracter ilegal");
                throw new ValidatorException("{errors.modificarusuario.apellido2.caracterIlegal}");
            }
        }
        /*
         * if (apellido2.length() <= 0) { log("apellido2.length() <=
         * 0");
         * 
         * throw new
         * ValidatorException("{errors.modificarusuario.apellido2}"); }
         * matcher = mask.matcher(apellido2); if (!matcher.matches()) {
         * log("apellido2 caracter ilegal"); throw new
         * ValidatorException("{errors.altausuario.modificarusuario.caracterIlegal}"); }
         */
        if (email.length() <= 0) {
            log("email.length() <= 0");
            throw new ValidatorException("{errors.modificarusuario.email}");
        }
        if (!((email.indexOf("@") > 0) && (email.indexOf(".") > 0))) {
            throw new ValidatorException("{errors.modificarusuario.emailIncorrecto}");
        }

        if ((clave == null) || (clave.equalsIgnoreCase(""))) {
            log("No se modifica la clave");
        } else {
            if (clave.length() < 7) {
                log("clave .length() <= 7");
                throw new ValidatorException("{errors.modificarusuario.clave}");
            }

            matcher = maskPwd.matcher(clave);
            if (!matcher.matches()) {
                log("contrasea caracter ilegal");
                throw new ValidatorException("{errors.modificarusuario.clave.caracterIlegal}");
            }

            if (!(clave.equalsIgnoreCase(repitaClave))) {
                throw new ValidatorException("{errors.modificarusuario.claveDistintas}");
            }
            usuarioVO.setClave(clave);
        }
        if (openIdUrl != null && openIdUrl.length() > 0) {
            UsuarioVO usuariovo = this.getSrvAdminUsuariosService().obtenerUsuarioConOpenId(openIdUrl);
            if (usuariovo != null && !usuariovo.getUsuario().equals(usuarioVO.getUsuario())) {
                if (log.isDebugEnabled())
                    log.debug("Ese identificador de openId ya existe en la base de datos");
                throw new ValidatorException("{errors.altausuario.existe.openId}");
            }

        }
        if (idiomaBusqueda == null) {
            throw new ValidatorException("{errors.modificarusuario.idiomaBusqueda}");
        }
        if (idiomaBusqueda.length() <= 0) {
            log("empaquetador .length() <= 0");
            throw new ValidatorException("{errors.modificarusuario.idiomaBusqueda}");
        }

        if (idioma == null) {
            throw new ValidatorException("{errors.modificarusuario.idioma}");
        }
        if (idioma.length() <= 0) {
            log("empaquetador .length() <= 0");
            throw new ValidatorException("{errors.modificarusuario.idioma}");
        }

        if (tipoEmpaquetador == null) {
            throw new ValidatorException("{errors.modificarusuario.tipoEmpaquetador}");
        }
        if (tipoEmpaquetador.length() <= 0) {
            log("empaquetador .length() <= 0");
            throw new ValidatorException("{errors.modificarusuario.tipoEmpaquetador}");
        }

        // /////Fin de validaciones de campo //////////

        usuarioVO.setNombre(nombre);
        usuarioVO.setApellido1(apellido1);
        usuarioVO.setApellido2(apellido2);
        usuarioVO.setEmail(email);
        usuarioVO.setTipoEmpaquetador(tipoEmpaquetador);
        usuarioVO.setIdioma(idioma);
        usuarioVO.setIdiomaBusqueda(idiomaBusqueda);
        usuarioVO.setTipoCatalogador(tipoCatalogador);
        usuarioVO.setCuota(new Long(cuota));
        usuarioVO.setOpenIdUrl(openIdUrl);

        usuarioVO.setId(id);
        resultado = this.getSrvAdminUsuariosService().modificarUsuario(usuarioVO);
        // Fijamos la cookie de modificarPerfil
        String cookiesPerfil = this.getPropertyValue("cookieModificarPerfil");
        Long tiempo = new Long(System.currentTimeMillis());
        Cookie cookie = new Cookie(cookiesPerfil, tiempo.toString());
        cookie.setPath("/");
        response.addCookie(cookie);
        log("se ha creado la cookie MODIFICAR_PERFIL " + tiempo);
    } catch (ValidatorException ve) {
        log.error("se ha producido una validatorException");
        resultado = "FALLO.MODIFICARUSUARIO";
        throw ve;
    } catch (Exception e) {
        log.error("Error: " + e);
        resultado = "FALLO.MODIFICARUSUARIO";
        throw new ValidatorException("{modificarUsuario.error}");

    } finally {

        // /Elimino de la sesion la descripcion del grupo

        form.setResultadoModificacion(resultado);
    }

}

From source file:org.jahia.bin.Logout.java

protected void removeAuthCookie(HttpServletRequest request, HttpServletResponse response) {
    // now let's destroy the cookie authentication if there was one
    // set for this user.
    JahiaUser curUser = JCRSessionFactory.getInstance().getCurrentUser();
    JCRPropertyWrapper cookieAuthKey = null;
    try {/*  www  .j  a v  a2  s .c o  m*/
        if (!JahiaUserManagerService.isGuest(curUser)) {
            JCRUserNode userNode = userManagerService.lookupUserByPath(curUser.getLocalPath());
            String userPropertyName = cookieAuthConfig.getUserPropertyName();
            if (userNode != null && userNode.hasProperty(userPropertyName)) {
                cookieAuthKey = userNode.getProperty(userPropertyName);
            }
        }
        if (cookieAuthKey != null) {
            Cookie authCookie = new Cookie(cookieAuthConfig.getCookieName(), cookieAuthKey.getString());
            authCookie
                    .setPath(StringUtils.isNotEmpty(request.getContextPath()) ? request.getContextPath() : "/");
            authCookie.setMaxAge(0); // means we want it deleted now !
            authCookie.setHttpOnly(cookieAuthConfig.isHttpOnly());
            authCookie.setSecure(cookieAuthConfig.isSecure());
            response.addCookie(authCookie);
            cookieAuthKey.remove();
            cookieAuthKey.getSession().save();
        }
    } catch (RepositoryException e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:com.redhat.rhn.frontend.servlets.PxtCookieManager.java

/**
 * Creates a new pxt cookie with the specified session id and timeout.
 *
 * @param pxtSessionId The id of the pxt session for which the cookie is being created.
 *
 * @param request The current request./*  w  w  w  .j a v  a  2s .  c o  m*/
 *
 * @param timeout The max age of the cookie in seconds.
 *
 * @return a new pxt cookie.
 */
public Cookie createPxtCookie(Long pxtSessionId, HttpServletRequest request, int timeout) {

    String cookieName = getCookieName(request);
    String cookieValue = pxtSessionId + "x" + SessionManager.generateSessionKey(pxtSessionId.toString());

    Cookie pxtCookie = new Cookie(cookieName, cookieValue);
    // BZ #454876
    // when not using setDomain, default "Host" will be set for the cookie
    // there's no need to use domain and besides that it causes trouble,
    //  when accessing the server within the local network (without FQDN)
    // pxtCookie.setDomain(request.getServerName());
    pxtCookie.setMaxAge(timeout);
    pxtCookie.setPath(DEFAULT_PATH);
    pxtCookie.setSecure(ConfigDefaults.get().isSSLAvailable());

    return pxtCookie;
}

From source file:com.nominanuda.web.http.ServletHelper.java

public Cookie servletCookie(HttpCookie c) {
    Cookie _c = new Cookie(c.getName(), c.getValue());
    if (c.getComment() != null) {
        _c.setComment(c.getComment());//from   www  .  j  a v a  2  s . c o m
    }
    if (c.getDomain() != null) {
        _c.setDomain(c.getDomain());
    }
    if (c.getPath() != null) {
        _c.setPath(c.getPath());
    }
    _c.setSecure(c.getSecure());
    _c.setVersion(c.getVersion());
    _c.setHttpOnly(c.getDiscard());
    _c.setMaxAge((int) c.getMaxAge());
    return _c;
}

From source file:org.jsecurity.web.attr.CookieAttribute.java

public void removeValue(ServletRequest servletRequest, ServletResponse response) {
    HttpServletRequest request = toHttp(servletRequest);
    Cookie cookie = getCookie(request, getName());
    if (cookie != null) {
        cookie.setMaxAge(0);//  w  w  w  .  ja  v a 2  s  .c  o m
        //JSEC-94: Must set the path on the outgoing cookie (some browsers don't retain it from the
        //retrieved cookie?)
        cookie.setPath(getPath() == null ? request.getContextPath() : getPath());
        cookie.setSecure(isSecure());
        toHttp(response).addCookie(cookie);
    }
}

From source file:de.metas.procurement.webui.service.impl.LoginRememberMeService.java

private void removeRememberMeCookie() {
    try {//from  www  .java  2s.  c  o  m
        Cookie cookie = getRememberMeCookie();
        if (cookie == null) {
            return;
        }

        cookie = new Cookie(COOKIENAME_RememberMe, null);
        cookie.setValue(null);
        cookie.setMaxAge(0); // by setting the cookie maxAge to 0 it will deleted immediately
        cookie.setPath("/");
        VaadinService.getCurrentResponse().addCookie(cookie);

        logger.debug("Cookie removed");
    } catch (final Exception e) {
        logger.warn("Failed removing the cookie", e);
    }
}

From source file:com.mentor.questa.vrm.jenkins.QuestaVrmHostAction.java

public void doFlipMode(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {

    // flip!//from w w w  .  ja v  a 2 s.  c o m
    boolean showActions = !getActionCookie(req);

    // set the updated value
    Cookie cookie = new Cookie("HostAction_showActions", String.valueOf(showActions));
    List anc = req.getAncestors();
    Ancestor a = (Ancestor) anc.get(anc.size() - 2);
    cookie.setPath(a.getUrl()); // just for this project
    cookie.setMaxAge(60 * 60 * 24 * 365); // 1 year

    rsp.addCookie(cookie);

    // back to the same page
    rsp.sendRedirect(".");
}