Example usage for javax.servlet.http Cookie getValue

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

Introduction

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

Prototype

public String getValue() 

Source Link

Document

Gets the current value of this Cookie.

Usage

From source file:com.xpn.xwiki.stats.impl.StatsUtil.java

/**
 * Try to find the visiting session of the current request, or create a new one if this request is not part of a
 * visit. The session is searched in the following way:
 * <ol>/*w ww .  j  av a2 s.  c  om*/
 * <li>the java session is searched for the visit object</li>
 * <li>try to find the stored session using the cookie</li>
 * <li>try to find the session by matching the IP and User Agent</li>
 * </ol>
 * The session is invalidated if:
 * <ul>
 * <li>the cookie is not the same as the stored cookie</li>
 * <li>more than 30 minutes have elapsed from the previous request</li>
 * <li>the user is not the same</li>
 * </ul>
 * 
 * @param context The context of this request.
 * @return The visiting session, retrieved from the database or created.
 * @since 1.4M1
 */
public static VisitStats findVisit(XWikiContext context) {
    XWikiRequest request = context.getRequest();
    HttpSession session = request.getSession(true);

    VisitStats visitObject = StatsUtil.getVisitFromSession(session);

    Cookie cookie = (Cookie) context.get(CONTPROP_STATS_COOKIE);
    boolean newcookie = ((Boolean) context.get(CONTPROP_STATS_NEWCOOKIE)).booleanValue();

    if (visitObject == null) {
        visitObject = findVisitByCookieOrIPUA(context);
    }

    if (visitObject == null || !isVisitObjectValid(visitObject, context)) {
        visitObject = createNewVisit(context);
    } else {
        if (!newcookie) {
            // If the cookie is not yet the unique ID we need to change that
            String uniqueID = visitObject.getUniqueID();
            String oldcookie = visitObject.getCookie();

            if (!uniqueID.equals(oldcookie)) {
                // We need to store the oldID so that we can remove the older entry
                // since the entry identifiers are changing
                VisitStats newVisitObject = (VisitStats) visitObject.clone();
                newVisitObject.rememberOldObject(visitObject);
                newVisitObject.setUniqueID(cookie.getValue());
                visitObject = newVisitObject;
            }
        }

        if ((!context.getUser().equals(XWikiRightService.GUEST_USER_FULLNAME))
                && (visitObject.getUser().equals(XWikiRightService.GUEST_USER_FULLNAME))) {
            // The user has changed from guest to an authenticated user
            // We want to record this
            VisitStats newVisitObject = visitObject;
            newVisitObject.rememberOldObject(visitObject);
            newVisitObject.setName(context.getUser());
            visitObject = newVisitObject;
        }
    }

    // Keep the visit object in the session
    StatsUtil.setVisitInSession(session, visitObject);

    return visitObject;
}

From source file:org.craftercms.security.processors.impl.AddSecurityCookiesProcessorTest.java

@Test
public void testAddCookiesLoggedOut() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    RequestContext context = new RequestContext(request, response);
    RequestSecurityProcessor flushResponseProcessor = new RequestSecurityProcessor() {

        @Override/*from   ww  w.  jav a 2  s.  c  om*/
        public void processRequest(RequestContext context, RequestSecurityProcessorChain processorChain)
                throws Exception {
            context.getResponse().getOutputStream().flush();
        }

    };

    Cookie ticketCookie = new Cookie(SecurityUtils.TICKET_COOKIE_NAME, new ObjectId().toString());
    Cookie profileLastModifiedCookie = new Cookie(SecurityUtils.PROFILE_LAST_MODIFIED_COOKIE_NAME,
            String.valueOf(System.currentTimeMillis()));

    request.setCookies(ticketCookie, profileLastModifiedCookie);

    RequestSecurityProcessorChain chain = new RequestSecurityProcessorChainImpl(
            Arrays.asList(processor, flushResponseProcessor).iterator());

    processor.processRequest(context, chain);

    ticketCookie = response.getCookie(SecurityUtils.TICKET_COOKIE_NAME);

    assertNotNull(ticketCookie);
    assertEquals(null, ticketCookie.getValue());
    assertEquals(0, ticketCookie.getMaxAge());

    profileLastModifiedCookie = response.getCookie(SecurityUtils.PROFILE_LAST_MODIFIED_COOKIE_NAME);

    assertNotNull(profileLastModifiedCookie);
    assertEquals(null, profileLastModifiedCookie.getValue());
    assertEquals(0, profileLastModifiedCookie.getMaxAge());
}

From source file:com.google.gsa.valve.modules.ldap.LDAPUniqueCreds.java

/**
 * Sets the LDAP authentication cookie//from   ww w.jav a  2  s.co  m
 * 
 * @return the LDAP authentication cookie
 */
public Cookie settingCookie() {
    // Instantiate a new cookie
    Cookie extAuthCookie = new Cookie("gsa_ad_auth", "true");
    String authCookieDomain = null;
    String authCookiePath = null;

    // Cache cookie properties
    authCookieDomain = valveConf.getAuthCookieDomain();
    authCookiePath = valveConf.getAuthCookiePath();

    // Set extra cookie parameters
    extAuthCookie.setDomain(authCookieDomain);
    extAuthCookie.setPath(authCookiePath);
    extAuthCookie.setMaxAge(authMaxAge);

    // Log info
    logger.debug("Adding cookie: " + extAuthCookie.getName() + ":" + extAuthCookie.getValue() + ":"
            + extAuthCookie.getPath() + ":" + extAuthCookie.getDomain() + ":" + extAuthCookie.getSecure());

    return extAuthCookie;
}

From source file:com.enonic.vertical.adminweb.AdminLogInServlet.java

private void handlerLogin(HttpServletRequest request, HttpServletResponse response, ExtendedMap formItems)
        throws VerticalAdminException {
    String uid = formItems.getString("username", null);
    String passwd = formItems.getString("password", null);
    UserStoreKey userStoreKey;//from  w w  w  .j a  va  2  s . c  o m
    String userStoreKeyStr = formItems.getString("userstorekey", null);
    AdminService admin = lookupAdminBean();

    if (userStoreKeyStr != null) {
        userStoreKey = new UserStoreKey(userStoreKeyStr);
    } else {
        userStoreKey = userStoreService.getDefaultUserStore().getKey();
    }

    securityService.logoutAdminUser();
    HttpSession session = request.getSession(true);

    session.setAttribute("selectedloginuserstore", userStoreKey.toString());

    // language
    AdminConsoleTranslationService languageMap = AdminConsoleTranslationService.getInstance();
    String languageCode;
    Cookie cookie = CookieUtil.getCookie(request, "languageCode");
    if (cookie == null) {
        languageCode = languageMap.getDefaultLanguageCode();
    } else {
        languageCode = cookie.getValue();
    }
    session.setAttribute("languageCode", languageCode);

    User user = null;
    String errorCode = null;
    try {
        if (uid == null || passwd == null) {
            String message = "User and/or password not set.";
            VerticalAdminLogger.error(this.getClass(), 0, message, null);
            session.setAttribute("loginerrorcode", EC_401_MISSING_USER_PASSWD);
            session.setAttribute("loginerror", message);
            session.setMaxInactiveInterval(SESSION_TIMEOUT_ERROR);
            errorCode = EC_401_MISSING_USER_PASSWD;
        } else {
            // authenticate user
            QualifiedUsername qualifiedUsername;
            if (UserEntity.isBuiltInUser(uid)) {
                qualifiedUsername = new QualifiedUsername(uid);
            } else {
                qualifiedUsername = new QualifiedUsername(userStoreKey, uid);
            }
            user = securityService.loginAdminUser(qualifiedUsername, passwd);
        }
    } catch (InvalidCredentialsException vse) {
        String message = "Failed to authenticate user (domain key: %0): %1";
        Object[] msgData = { userStoreKey, uid };
        VerticalAdminLogger.warn(this.getClass(), 0, message, msgData, null);
        message = StringUtil.expandString(message, msgData, vse);
        session.setAttribute("loginerrorcode", EC_401_USER_PASSWD_WRONG);
        session.setAttribute("loginerror", message);
        session.setMaxInactiveInterval(SESSION_TIMEOUT_ERROR);
        errorCode = EC_401_USER_PASSWD_WRONG;
        String remoteAdr = request.getRemoteAddr();
        createLogEntry(user, admin, userStoreKey, remoteAdr, LogType.LOGIN_FAILED.asInteger(), uid);
    } catch (AdminConsoleAccessDeniedException e) {
        String message = "User is not authorized to use administration console.";
        VerticalAdminLogger.error(this.getClass(), 0, message, null);
        session.setAttribute("loginerrorcode", EC_401_ACCESS_DENIED);
        session.setAttribute("loginerror", message);
        session.setMaxInactiveInterval(SESSION_TIMEOUT_ERROR);
        errorCode = EC_401_ACCESS_DENIED;
    }

    if (errorCode != null) {
        if (formItems.containsKey("editContent")) {
            ExtendedMap parameters = new ExtendedMap();
            parameters.put("editContent", formItems.getInt("editContent"));
            redirectClientToAdminPath("login", parameters, request, response);
            return;
        }
        redirectClientToAdminPath("login", request, response);
        return;
    }

    // no errors occured during authentication and authorization of user

    String remoteAdr = request.getRemoteAddr();
    user.setSelectedLanguageCode(languageCode);

    try {
        final boolean loggingSuccessful = createLogEntry(user, admin, userStoreKey, remoteAdr,
                LogType.LOGIN.asInteger(), null);
        // Log login (only let the user log in if creation of log entry was successfull):
        if (!loggingSuccessful) {
            String message = "Failed to create log entry of user login";
            VerticalAdminLogger.error(this.getClass(), 0, message, null);
            session.setAttribute("loginerrorcode", EC_500_UNEXPECTED_ERROR);
            session.setAttribute("loginerror", message);
            session.setMaxInactiveInterval(SESSION_TIMEOUT_ERROR);
            return;
        }

        if (userStoreKey != null) {
            logUserStoreLogin(user, admin, request.getRemoteAddr(), request.getRemoteHost(), userStoreKey);
        }

        // Reset some cookie data:
        String deploymentPath = DeploymentPathResolver.getAdminDeploymentPath(request);

        if (userStoreKey != null) {
            CookieUtil.setCookie(response, user.getKey() + "userstorekey", userStoreKey.toString(), -1,
                    deploymentPath);
        }

        CookieUtil.setCookie(response, user.getKey() + "selectedunitkey", "-1", -1, deploymentPath);
        // If the enterpriseadmin user did'nt select a domain,
        // show system tab page, else show domain tab page.
        Cookie tabPageCookie = CookieUtil.getCookie(request, user.getKey() + "mainmenu_selectedTabPage");
        int tabPage = -1;
        if (tabPageCookie != null) {
            tabPage = Integer.parseInt(tabPageCookie.getValue());
        }

        CookieUtil.setCookie(response, user.getKey() + "mainmenu_selectedTabPage", String.valueOf(tabPage), -1,
                deploymentPath);
        session.setAttribute("selectedunitkey", "-1");

        ExtendedMap parameters = new ExtendedMap();
        parameters.put("page", "0");
        if (formItems.containsKey("rightframe")) {
            parameters.put("rightframe", formItems.getString("rightframe"));
        }
        if (formItems.containsKey("referer")) {
            parameters.put("referer", formItems.getString("referer", ""));
        }

        //ren: VS-1970
        if (formItems.containsKey("editContent")) {
            parameters.put("editContent", formItems.getInt("editContent"));
        }
        //end: VS-1970
        session.removeAttribute("loginerrorcode");
        session.removeAttribute("loginerror");
        redirectClientToAdminPath("adminpage", parameters, request, response);

    } catch (VerticalAdminException vae) {
        String message = "Failed to redirect to admin page: %t";
        VerticalAdminLogger.fatalAdmin(this.getClass(), 0, message, vae);
    }

}

From source file:org.eclipse.userstorage.tests.util.USSServer.java

private Session getSession(HttpServletRequest request) {
    String csrfToken = request.getHeader("X-CSRF-Token");
    if (csrfToken != null) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("SESSION".equals(cookie.getName())) {
                    String sessionID = cookie.getValue();
                    Session session = sessions.get(sessionID);

                    if (session != null && session.getCSRFToken().equals(csrfToken)) {
                        return session;
                    }//from w w  w .j  a va2 s  .  c  o  m

                    break;
                }
            }
        }
    }

    return null;
}

From source file:it.scoppelletti.programmerpower.web.security.CasClient.java

/**
 * Restituisce il ticket di autenticazione registrato come cookie.
 * //from  ww  w .ja  va2 s . c o m
 * @param  req  Richiesta.
 * @param  resp Risposta.
 * @return      Valore. Se il ticket non &egrave; stato registrato,
 *              restituisce {@code null}.
 */
public String getTicketGrantingTicket(HttpServletRequest req, HttpServletResponse resp) {
    Cookie cookie;

    if (req == null) {
        throw new ArgumentNullException("req");
    }
    if (myTGTCookieGenerator == null) {
        throw new PropertyNotSetException(toString(), "ticketGrantingTicketCookieGenerator");
    }

    cookie = WebUtils.getCookie(req, myTGTCookieGenerator.getCookieName());
    if (cookie == null) {
        return null;
    }

    return cookie.getValue();
}

From source file:com.qut.middleware.spep.servlet.AuthenticationServletTest.java

/**
 * @throws Exception//from  w  ww  .  j  ava  2  s .  co  m
 */
@Test
public void testPost2a() throws Exception {
    final LineVectorOutputStream outputStream = new LineVectorOutputStream();
    final String sessionID = "9809283409182304981234-923-501209348091234";
    final String base64RequestURL = new String(Base64.encodeBase64(this.defaultRequestURL.getBytes("UTF-8")));

    Modify<AuthnProcessorData> modifyAuthnProcessorData = new ModifyAuthnProcessorData(sessionID, null, null);

    Capture<Cookie> captureCookie = new Capture<Cookie>();

    this.authnProcessor.processAuthnResponse(modify(modifyAuthnProcessorData), (Response) notNull());
    expectLastCall().anyTimes();

    startMock();

    this.authenticationServlet.init(this.servletConfig);

    String samlResponse = new String(Base64.encodeBase64("some response document".getBytes("UTF-8")));

    ServletOutputStream out = new OutputStreamServletOutputStream(outputStream);

    HttpServletRequest request = createMock(HttpServletRequest.class);
    expect(request.getParameter("SAMLResponse")).andReturn(samlResponse).anyTimes();

    HttpServletResponse response = createMock(HttpServletResponse.class);
    response.addCookie(capture(captureCookie));
    expectLastCall().once();
    // Make sure we get redirected to the default URL
    response.sendRedirect(this.defaultRequestURL);
    expectLastCall().once();

    replay(request);
    replay(response);

    this.authenticationServlet.doPost(request, response);

    verify(request);
    verify(response);

    Cookie spepCookie = null;
    for (Cookie cookie : captureCookie.getCaptured()) {
        if (cookie.getName().equals(this.tokenName)) {
            spepCookie = cookie;
            break;
        }
    }

    assertNotNull(spepCookie);
    assertEquals(this.tokenName, spepCookie.getName());
    assertEquals(sessionID, spepCookie.getValue());

    endMock();
}

From source file:com.qut.middleware.spep.servlet.AuthenticationServletTest.java

/**
 * @throws Exception// www.  j  a v  a 2s  .c o m
 */
@Test
public void testPost2b() throws Exception {
    final LineVectorOutputStream outputStream = new LineVectorOutputStream();
    final String sessionID = "9809283409182304981234-923-501209348091234";
    final String requestURL = "http://lol.request.url/somepage.jsp";
    final String base64RequestURL = new String(Base64.encodeBase64(requestURL.getBytes("UTF-8")));

    Modify<AuthnProcessorData> modifyAuthnProcessorData = new ModifyAuthnProcessorData(sessionID,
            base64RequestURL, null);

    Capture<Cookie> captureCookie = new Capture<Cookie>();

    this.authnProcessor.processAuthnResponse(modify(modifyAuthnProcessorData), (Response) notNull());
    expectLastCall().anyTimes();

    startMock();

    this.authenticationServlet.init(this.servletConfig);

    String samlResponse = new String(Base64.encodeBase64("some response document".getBytes("UTF-8")));

    ServletOutputStream out = new OutputStreamServletOutputStream(outputStream);

    HttpServletRequest request = createMock(HttpServletRequest.class);
    expect(request.getParameter("SAMLResponse")).andReturn(samlResponse).anyTimes();

    HttpServletResponse response = createMock(HttpServletResponse.class);
    response.addCookie(capture(captureCookie));
    expectLastCall().once();
    // Make sure we get redirected to the session URL
    response.sendRedirect(requestURL);
    expectLastCall().once();

    replay(request);
    replay(response);

    this.authenticationServlet.doPost(request, response);

    verify(request);
    verify(response);

    Cookie spepCookie = null;
    for (Cookie cookie : captureCookie.getCaptured()) {
        if (cookie.getName().equals(this.tokenName)) {
            spepCookie = cookie;
            break;
        }
    }

    assertNotNull(spepCookie);
    assertEquals(this.tokenName, spepCookie.getName());
    assertEquals(sessionID, spepCookie.getValue());

    endMock();
}

From source file:net.nan21.dnet.core.web.controller.ui.extjs.AbstractUiExtjsController.java

/**
 * Resolve the user's current language from the cookie.
 * //ww  w. ja  va2  s  . c o m
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
private String resolveLang(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Cookie[] cookies = request.getCookies();
    Cookie c = this.getCookie(cookies, Constants.COOKIE_NAME_LANG);
    if (c == null) {

        String value = this.getSettings().getParam(SysParams_Core.CORE_DEFAULT_LANGUAGE);

        c = this.createCookie(Constants.COOKIE_NAME_LANG, value, 60 * 60 * 24 * 365);
        response.addCookie(c);
    }

    String lang = request.getParameter(Constants.REQUEST_PARAM_LANG);
    if (lang == null || lang.equals("")) {
        lang = c.getValue();
    } else {
        c.setMaxAge(0);
        c = this.createCookie(Constants.COOKIE_NAME_LANG, lang, 60 * 60 * 24 * 365);
        response.addCookie(c);
    }
    return lang;
}