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.agiletec.plugins.jpcontentfeedback.aps.internalservlet.feedback.ContentFeedbackAction.java

protected void addCookieRating(int commentId) {
    UserDetails currentUser = this.getCurrentUser();
    String cookieName = CheckVotingUtil.getCookieName(currentUser.getUsername(), commentId);
    String cookieValue = CheckVotingUtil.getCookieValue(currentUser.getUsername(), commentId);
    Cookie cookie = new Cookie(cookieName, cookieValue);
    cookie.setMaxAge(365 * 24 * 60 * 60);//one year
    this.getResponse().addCookie(cookie);
}

From source file:com.qut.middleware.esoe.authn.servlet.AuthnServlet.java

/**
 * Sets the session cookie for this principal
 * /*  ww w  .ja  v a  2s.c  o m*/
 * @param data
 */
private void setSessionCookie(AuthnProcessorData data) {
    Cookie sessionCookie = new Cookie(this.sessionTokenName, data.getSessionID());
    sessionCookie.setDomain(this.sessionDomain);
    sessionCookie.setMaxAge(-1); // negative indicates session scope cookie
    sessionCookie.setPath("/");

    data.getHttpResponse().addCookie(sessionCookie);
}

From source file:ch.ralscha.extdirectspring.controller.RouterControllerSimpleTest.java

@Test
public void methodWithRequiredCookieValue() {
    List<Cookie> cookies = new ArrayList<Cookie>();
    cookies.add(new Cookie("intCookie", "1"));
    cookies.add(new Cookie("booleanCookie", "true"));
    ControllerUtil.sendAndReceive(mockMvc, null, cookies, "remoteProviderSimple", "method27", "1;true",
            (Object[]) null);//from w w  w  . ja v a  2s.  c om
    ControllerUtil.sendAndReceive(mockMvc, null, null, "remoteProviderSimple", "method27", null,
            (Object[]) null);
}

From source file:com.vmware.identity.openidconnect.sample.RelyingPartyController.java

private static Cookie logoutSessionCookie() {
    Cookie sessionCookie = new Cookie(SESSION_COOKIE_NAME, "");
    sessionCookie.setPath("/openidconnect-sample-rp");
    sessionCookie.setSecure(true);//ww  w .  j av  a2 s .  c  om
    sessionCookie.setHttpOnly(true);
    sessionCookie.setMaxAge(0);
    return sessionCookie;
}

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

public static void login(HttpServletRequest req, HttpServletResponse res, String login, String password,
        boolean rememberMe) throws Exception {

    CookieKeys.validateSupportCookie(req);

    HttpSession ses = req.getSession();//from   ww w .  j a v  a 2 s.c om

    long userId = GetterUtil.getLong(login);

    int authResult = Authenticator.FAILURE;

    Company company = PortalUtil.getCompany(req);

    //
    boolean ldaplogin = false;
    if (PrefsPropsUtil.getString(company.getCompanyId(), PropsUtil.LDAP_AUTH_ENABLED).equals("true")) {
        LdapContext ctx = PortalLDAPUtil.getContext(company.getCompanyId());
        String accountname = "";
        try {
            User user1 = UserLocalServiceUtil.getUserByScreenName(company.getCompanyId(), login);
            Properties env = new Properties();

            String baseProviderURL = PrefsPropsUtil.getString(company.getCompanyId(),
                    PropsUtil.LDAP_BASE_PROVIDER_URL);
            String userDN = PrefsPropsUtil.getString(company.getCompanyId(), PropsUtil.LDAP_USERS_DN);
            String baseDN = PrefsPropsUtil.getString(company.getCompanyId(), PropsUtil.LDAP_BASE_DN);
            String filter = PrefsPropsUtil.getString(company.getCompanyId(), PropsUtil.LDAP_AUTH_SEARCH_FILTER);
            filter = StringUtil.replace(filter,
                    new String[] { "@company_id@", "@email_address@", "@screen_name@", "@user_id@" },
                    new String[] { String.valueOf(company.getCompanyId()), "", login, login });
            try {
                SearchControls cons = new SearchControls(SearchControls.SUBTREE_SCOPE, 1, 0, null, false,
                        false);

                NamingEnumeration enu = ctx.search(userDN, filter, cons);
                if (enu.hasMoreElements()) {
                    SearchResult result = (SearchResult) enu.nextElement();
                    accountname = result.getName();
                }
            } catch (Exception e1) {
                e1.printStackTrace();
            }

            env.put(Context.INITIAL_CONTEXT_FACTORY, PrefsPropsUtil.getString(PropsUtil.LDAP_FACTORY_INITIAL));
            env.put(Context.PROVIDER_URL, LDAPUtil.getFullProviderURL(baseProviderURL, baseDN));
            env.put(Context.SECURITY_PRINCIPAL, accountname + "," + userDN);
            env.put(Context.SECURITY_CREDENTIALS, password);

            new InitialLdapContext(env, null);
            ldaplogin = true;
            System.out.println("LDAP Login");
        } catch (Exception e) {
            SessionErrors.add(req, "ldapAuthentication");
            e.printStackTrace();
            System.out.println("LDAP error login");
            return;
        }
    }

    //

    Map headerMap = new HashMap();

    Enumeration enu1 = req.getHeaderNames();

    while (enu1.hasMoreElements()) {
        String name = (String) enu1.nextElement();

        Enumeration enu2 = req.getHeaders(name);

        List headers = new ArrayList();

        while (enu2.hasMoreElements()) {
            String value = (String) enu2.nextElement();

            headers.add(value);
        }

        headerMap.put(name, (String[]) headers.toArray(new String[0]));
    }

    Map parameterMap = req.getParameterMap();

    if (company.getAuthType().equals(CompanyImpl.AUTH_TYPE_EA)) {
        authResult = UserLocalServiceUtil.authenticateByEmailAddress(company.getCompanyId(), login, password,
                headerMap, parameterMap);

        userId = UserLocalServiceUtil.getUserIdByEmailAddress(company.getCompanyId(), login);
    } else if (company.getAuthType().equals(CompanyImpl.AUTH_TYPE_SN)) {
        authResult = UserLocalServiceUtil.authenticateByScreenName(company.getCompanyId(), login, password,
                headerMap, parameterMap);

        userId = UserLocalServiceUtil.getUserIdByScreenName(company.getCompanyId(), login);
    } else if (company.getAuthType().equals(CompanyImpl.AUTH_TYPE_ID)) {
        authResult = UserLocalServiceUtil.authenticateByUserId(company.getCompanyId(), userId, password,
                headerMap, parameterMap);
    }

    boolean OTPAuth = false;

    if (GetterUtil.getBoolean(PropsUtil.get("use.yubicoauthentication"), false) == true) {
        String otppasswd = ParamUtil.getString(req, "otp");
        String userslist = GetterUtil.getString(PropsUtil.get("yubico.users.not.require.otp"), "root");
        if (userslist.contains(login)) {
            authResult = Authenticator.SUCCESS;
        } else {
            OTPAuth = SecurityUtils.verifyOTP(otppasswd, login);
            if (authResult == Authenticator.SUCCESS && OTPAuth) {
                authResult = Authenticator.SUCCESS;
            } else {
                authResult = Authenticator.FAILURE;
            }
        }
    }

    if (PrefsPropsUtil.getString(company.getCompanyId(), PropsUtil.LDAP_AUTH_ENABLED).equals("true")) {
        if (!login.equals("root")) {
            if (ldaplogin) {
                authResult = Authenticator.SUCCESS;
            }
        }
    }

    if (authResult == Authenticator.SUCCESS) {

        boolean loginViaPortal = true;

        setLoginCookies(req, res, ses, userId, rememberMe);
        // login to epsos
        String language = GeneralUtils.getLocale(req);
        SpiritEhrWsClientInterface webService = EpsosHelperService.getInstance().getWebService(req);

        InitUserObj initUserObj = EpsosHelperImpl.createEpsosUserInformation(req, res, language, webService,
                userId, company.getCompanyId(), login, loginViaPortal);
        SpiritUserClientDto usr = initUserObj.getUsr();
        Assertion assertion = initUserObj.getAssertion();

        if (Validator.isNotNull(usr)) {
            req.getSession().setAttribute(EpsosHelperService.EPSOS_LOGIN_INFORMATION_ASSERTIONID,
                    assertion.getID());
            req.getSession().setAttribute(EpsosHelperService.EPSOS_LOGIN_INFORMATION_ASSERTION, assertion);
            req.getSession().setAttribute(EPSOS_LOGIN_INFORMATION_ATTRIBUTE, usr);
        } else {
            SessionErrors.add(req, "User doesn't belong to epSOS role so you can't login");
        }

        if (Validator.isNull(usr) && (!(login.equals("root")))) {
            try {
                Cookie cookie = new Cookie(CookieKeys.ID, StringPool.BLANK);
                cookie.setMaxAge(0);
                cookie.setPath("/");

                CookieKeys.addCookie(res, cookie);

                cookie = new Cookie(CookieKeys.PASSWORD, StringPool.BLANK);
                cookie.setMaxAge(0);
                cookie.setPath("/");

                CookieKeys.addCookie(res, cookie);

                try {
                    ses.invalidate();
                } catch (Exception e) {
                }

            } catch (Exception e) {
                req.setAttribute(PageContext.EXCEPTION, e);

            }
            throw new AuthException();

        }

    } else {
        throw new AuthException();
    }
}

From source file:ch.ralscha.extdirectspring.controller.RouterControllerOptionalTest.java

@Test
public void testPoll5() throws Exception {
    List<Cookie> cookies = new ArrayList<Cookie>();
    cookies.add(new Cookie("cookie", "cookieValue"));

    ExtDirectPollResponse resp = ControllerUtil.performPollRequest(mockMvc, "remoteProviderOptional", "opoll5",
            "opoll5", null, null, cookies);

    assertThat(resp).isNotNull();/*from   w ww  .  ja  v  a 2s  .  c  o  m*/
    assertThat(resp.getType()).isEqualTo("event");
    assertThat(resp.getName()).isEqualTo("opoll5");
    assertThat(resp.getData()).isEqualTo("23;dummy;cookieValue");
    assertThat(resp.getWhere()).isNull();
    assertThat(resp.getMessage()).isNull();
}

From source file:ch.ralscha.extdirectspring.controller.RouterControllerPollTest.java

@Test
public void pollRequiredCookieWithoutValue() throws Exception {
    List<Cookie> cookies = new ArrayList<Cookie>();
    cookies.add(new Cookie("cookie", "cookieValue"));

    ExtDirectPollResponse resp = ControllerUtil.performPollRequest(mockMvc, "pollProvider",
            "messageCookieValue1", "messageCookieValue1", null, null, cookies);

    assertThat(resp).isNotNull();/*  w  ww. jav a 2  s  .  c  o m*/
    assertThat(resp.getType()).isEqualTo("event");
    assertThat(resp.getName()).isEqualTo("messageCookieValue1");
    assertThat(resp.getData()).isEqualTo("null;null;cookieValue");
    assertThat(resp.getWhere()).isNull();
    assertThat(resp.getMessage()).isNull();
}

From source file:com.vmware.identity.samlservice.LogoutState.java

private void removeSessionCookie(String cookieName, HttpServletResponse response) {
    Validate.notNull(response);//from   ww  w.j  a v a 2s  . c  om
    if (cookieName == null || cookieName.isEmpty()) {
        log.warn("Cookie name is null or empty. Ignoring.");
        return;
    }
    log.debug("Removing cookie " + cookieName);
    Cookie sessionCookie = new Cookie(cookieName, "");
    sessionCookie.setPath("/");
    sessionCookie.setSecure(true);
    sessionCookie.setHttpOnly(true);
    sessionCookie.setMaxAge(0);
    response.addCookie(sessionCookie);
}

From source file:com.qut.middleware.esoe.authn.servlet.AuthnServlet.java

/**
 * Clears a provided session identifying cookie when some invalid value has been presented
 * //from  w  ww .  jav  a  2  s . c om
 * @param data
 *            Local request AuthnProcessoreData bean
 */
private void clearSessionCookie(AuthnProcessorData data) {
    /* Remove the value of the users session cookie at the ESOE */
    Cookie sessionCookie = new Cookie(this.sessionTokenName, ""); //$NON-NLS-1$
    sessionCookie.setDomain(this.sessionDomain);
    sessionCookie.setSecure(false);
    data.getHttpResponse().addCookie(sessionCookie);
}