Example usage for javax.servlet.http HttpServletRequest getCookies

List of usage examples for javax.servlet.http HttpServletRequest getCookies

Introduction

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

Prototype

public Cookie[] getCookies();

Source Link

Document

Returns an array containing all of the Cookie objects the client sent with this request.

Usage

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

/**
 * SESSION//ww w .  j  a v  a  2 s.c  o m
 * 
 * @param session
 */
public BiddingSession(HttpServletRequest request, BiddingHttpContext biddingHttpContext) {
    this.biddingHttpContext = biddingHttpContext;
    createTime = System.currentTimeMillis();
    this.request = request;
    initCookies(request.getCookies());
    // ? SESSIONID
    sessionId = (String) getAttribute(JSESSION_ID);

    if (StringUtil.isBlank(sessionId)) {
        sessionId = DigestUtils.md5Hex(UniqID.getInstance().getUniqID());
        // COOKIE
        setAttribute(JSESSION_ID, sessionId);

    }

}

From source file:org.apache.sling.auth.xing.login.impl.XingLoginAuthenticationHandler.java

/**
 * we need the <i>hash</i> from the XING cookie (<code>xing_p_lw_s_[...]</code>) and
 * the <i>user data</i> and <i>id</i> from our own cookies (<code>sling_auth_xing_[...]</code>)
 *
 * @param request/*from   w w w.j a  v a2 s  . c om*/
 * @param response
 * @return
 */
@Override
public AuthenticationInfo extractCredentials(final HttpServletRequest request,
        final HttpServletResponse response) {
    logger.debug("extract credentials");

    String hash = null;
    String user = null;
    String userId = null;

    final Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (final Cookie cookie : cookies) {
            final String cookieName = cookie.getName();
            if (cookieName.equals(xingCookie)) {
                hash = readCookieValue(cookie);
                logger.debug("Login with XING? cookie found: {}", hash);
            } else if (cookieName.equals(userCookie)) {
                user = readCookieValue(cookie);
            } else if (cookieName.equals(userIdCookie)) {
                userId = readCookieValue(cookie);
            }
        }
    }

    if (!StringUtils.isEmpty(hash) && !StringUtils.isEmpty(userId) && !StringUtils.isEmpty(user)) {
        logger.debug("valid cookies with hash and user data and id found");
        final AuthenticationInfo authenticationInfo = new AuthenticationInfo(XingLogin.AUTH_TYPE, userId);
        authenticationInfo.put(XingLogin.AUTHENTICATION_CREDENTIALS_HASH_KEY, hash);
        authenticationInfo.put(XingLogin.AUTHENTICATION_CREDENTIALS_USERDATA_KEY, user);
        return authenticationInfo;
    } else {
        logger.debug("unable to extract credentials from request");
        return null;
    }
}

From source file:com.haulmont.cuba.web.sys.CubaApplicationServlet.java

protected String getCookieValue(HttpServletRequest req, String cookieName) {
    if (req.getCookies() == null) {
        return null;
    }//from   w w  w  .j av a2 s  .  c  om

    for (Cookie cookie : req.getCookies()) {
        if (Objects.equals(cookieName, cookie.getName())) {
            return cookie.getValue();
        }
    }
    return null;
}

From source file:org.guanxi.idp.service.GenericAuthHandler.java

protected boolean auth(String spEntityID, HttpServletRequest request, HttpServletResponse response) {
    // Look for our cookie. This is after any application cookie handler has authenticated the user
    String cookieName = getCookieName();
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (int c = 0; c < cookies.length; c++) {
            if (cookies[c].getName().equals(cookieName)) {
                // Retrieve the principal from the servlet context
                if (servletContext.getAttribute(cookies[c].getValue()) == null) {
                    // Out of date cookie value, so remove the cookie
                    cookies[c].setMaxAge(0);
                    response.addCookie(cookies[c]);
                } else {
                    // Found the principal from a previously established authentication
                    request.setAttribute(Guanxi.REQUEST_ATTR_IDP_PRINCIPAL,
                            (GuanxiPrincipal) servletContext.getAttribute(cookies[c].getValue()));
                    return true;
                }//from   ww  w  .j  ava 2  s . c  o m
            }
        }
    }

    // Are we getting an authentication request from the login page?
    if (request.getParameter("guanxi:mode") != null) {
        if (request.getParameter("guanxi:mode").equalsIgnoreCase("authenticate")) {
            // Get a new GuanxiPrincipal...
            GuanxiPrincipal principal = gxPrincipalFactory.createNewGuanxiPrincipal(request);
            if (authenticator.authenticate(principal, request.getParameter("userid"),
                    request.getParameter("password"))) {
                // ...associate it with a login name...
                if (principal.getName() == null) {
                    //The login name from the authenticator page
                    principal.setName(request.getParameter("userid"));
                }
                // ...store it in the request for the SSO to use...
                request.setAttribute(Guanxi.REQUEST_ATTR_IDP_PRINCIPAL, principal);
                // ...and store it in application scope for the rest of the profile to use
                servletContext.setAttribute(principal.getUniqueId(), principal);

                // Get a new cookie ready to reference the principal in the servlet context
                Cookie cookie = new Cookie(getCookieName(), principal.getUniqueId());
                cookie.setDomain((String) servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_COOKIE_DOMAIN));
                cookie.setPath(idpConfig.getCookie().getPath());
                if (((Integer) (servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_COOKIE_AGE)))
                        .intValue() != -1)
                    cookie.setMaxAge(
                            ((Integer) (servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_COOKIE_AGE)))
                                    .intValue());
                response.addCookie(cookie);

                return true;
            } // if (authenticator.authenticate...
            else {
                logger.error("Authentication error : " + authenticator.getErrorMessage());
                request.setAttribute("message",
                        messageSource.getMessage("authentication.error", null, request.getLocale()));
                try {
                    request.getRequestDispatcher(errorPage).forward(request, response);
                } catch (Exception e) {
                    logger.error("Could not display authentication error page", e);
                }
                return false;
            }
        }
    } // if (request.getParameter("guanxi:mode") != null) {

    // No embedded cookie authentication or local auth, so show the login page
    String authPage = null;
    AuthPage[] authPages = idpConfig.getAuthenticatorPages().getAuthPageArray();
    for (int c = 0; c < authPages.length; c++) {
        // We'll use the default auth page if none is specified for this service provider
        if (authPages[c].getProviderId().equals(Guanxi.DEFAULT_AUTH_PAGE_MARKER)) {
            authPage = authPages[c].getUrl();
        }

        // Customised auth page for this service provider
        if (authPages[c].getProviderId().equals(request.getParameter(spEntityID))) {
            authPage = authPages[c].getUrl();
        }
    }

    addRequiredParamsAsPrefixedAttributes(request);
    try {
        request.getRequestDispatcher(authPage).forward(request, response);
    } catch (Exception e) {
        logger.error("Could not display authentication page", e);
    }

    return false;
}

From source file:net.duckling.ddl.web.controller.LynxHomeController.java

@SuppressWarnings("unchecked")
private JSONObject userStatus(HttpServletRequest request) {
    VWBSession session = VWBSession.findSession(request);
    JSONObject obj = new JSONObject();
    obj.put("haveUmtId", false);
    if (session != null && session.isAuthenticated()) {
        obj.put("status", true);
        obj.put("userEmail", ((UserPrincipal) session.getCurrentUser()).getFullName());
    } else {/*w w  w . j av a 2  s .  c om*/
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            obj.put("status", false);
            Integer i = (Integer) request.getSession().getAttribute("redirect_uri_count");
            if (i != null && i > 2) {
                request.getSession().setAttribute("redirect_uri_count", 0);
            } else {
                for (Cookie cookie : cookies) {
                    if ("UMTID".equals(cookie.getName())) {
                        obj.put("haveUmtId", true);
                        break;
                    }
                }
            }
        } else {
            obj.put("status", false);
        }
    }
    return obj;
}

From source file:com.music.web.util.AutoLoginInterceptor.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {

    // don't handle ajax or resource requests
    String requestedWith = request.getHeader("X-Requested-With");
    if (handler instanceof ResourceHttpRequestHandler
            || (requestedWith != null && requestedWith.equals("XMLHttpRequest"))) {
        return true;
    }//from   www.  j a v  a 2 s. c o m

    if (userContext.getUser() == null && request.getCookies() != null) {
        Cookie[] cookies = request.getCookies();

        String authToken = null;
        String series = null;

        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(SocialSignInAdapter.AUTH_TOKEN_COOKIE_NAME)) {
                authToken = cookie.getValue();
            } else if (cookie.getName().equals(SocialSignInAdapter.AUTH_TOKEN_SERIES_COOKIE_NAME)) {
                series = cookie.getValue();
            }
        }

        if (authToken != null && series != null) {
            User user = userService.rememberMeLogin(authToken, series);
            if (user != null) {
                adapter.signIn(user, response, false);
            }
        }
    }
    return true;
}

From source file:seava.j4e.web.controller.ui.extjs.AbstractUiExtjsController.java

/**
 * Resolve the user's current language from the cookie.
 * //ww  w  . java2 s  .  com
 * @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(SysParam.CORE_DEFAULT_LANGUAGE.name());

        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;
}

From source file:seava.j4e.web.controller.ui.extjs.AbstractUiExtjsController.java

/**
 * Resolve the user's current theme from the cookie.
 * /*  ww w .  jav  a 2 s  .  co m*/
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
private String resolveTheme(HttpServletRequest request, HttpServletResponse response) throws Exception {

    Cookie[] cookies = request.getCookies();
    Cookie c = this.getCookie(cookies, Constants.COOKIE_NAME_THEME);

    if (c == null) {

        String value = this.getSettings().getParam(SysParam.CORE_DEFAULT_THEME_EXTJS.name());
        c = this.createCookie(Constants.COOKIE_NAME_THEME, value, 60 * 60 * 24 * 365);
        response.addCookie(c);
    }

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

From source file:com.netpace.cms.sso.filter.OpenSSOClientAdapter.java

/**
 * Tries to create an SSOToken based on the HTTP request
 * // w w  w .j  ava2s . c o m
 * @param request
 * @return The token or null if session not valid
 */
public SSOToken createTokenFrom(HttpServletRequest request) {
    System.out.println("OpenSSOClientAdapter.createTokenFrom: Start");
    if (logger.isDebugEnabled()) {
        logger.debug("OpenSSOClientAdapter.createTokenFrom: Start");
    }
    SSOToken token = null;
    try {
        //         token = tokenManager.createSSOToken(request);
        Cookie[] requestCookies = request.getCookies();
        for (int i = 0; i < requestCookies.length; i++) {
            Cookie cookie = requestCookies[i];
            String ssoTokenId = java.net.URLDecoder.decode(cookie.getValue(), "UTF-8");
            if (cookie.getName().equals(AlfrescoFacade.OPENSSO_COOKIE_NAME)) {
                token = tokenManager.createSSOToken(ssoTokenId);
                if (logger.isDebugEnabled()) {
                    logger.debug("token: " + token);
                }
                boolean sessionValid = tokenManager.isValidToken(token);
                if (sessionValid) {
                    return token;
                }
            }
        }
    } catch (SSOException e) {
        logger.info("Request does not contain a valid session");
        logger.error(e, e);
    } catch (UnsupportedEncodingException e) {
        logger.error(e, e);
    }
    if (logger.isDebugEnabled()) {
        logger.debug("OpenSSOClientAdapter.createTokenFrom: End");
    }
    System.out.println("OpenSSOClientAdapter.createTokenFrom: End");
    return token;
}

From source file:com.itjenny.web.ArticleController.java

@RequestMapping(value = "{title}/{chapterCssId}", method = RequestMethod.POST)
public ModelAndView checkAnswer(HttpServletRequest request, @PathVariable String title,
        @PathVariable String chapterCssId, @RequestParam String answer) {
    Integer chapterIndex = Integer.valueOf(chapterCssId.replace(Consts.CHAPTER, StringUtils.EMPTY));
    ModelAndView mav = new ModelAndView();
    ModelMap model = new ModelMap();
    for (Cookie cookie : request.getCookies()) {
        if (cookie.getName().equals("keynote")) {
            Article article = articleService.get(title);
            if (article == null || !article.getUserId().equals(sessionService.getLoginUser().getUserId())) {
                break;
            }/*from w w  w  .j  a  v  a 2  s  . c om*/

            // keynote mode
            if (!articleService.isChapterExisted(title, chapterIndex + 1)) {
                bookmarkService.complete(title);
                return new ModelAndView("redirect:/article/" + title + "/license");
            }
            model.addAttribute("chapter", articleService.getChapter(title, chapterIndex + 1));
            model.addAttribute("totalSection", articleService.getTotalSection(title));
            model.addAttribute("answer", articleService.getChapter(title, chapterIndex).getQuiz().getAnswer());
            mav.setViewName(View.CHAPTER);
            mav.addAllObjects(model);

            bookmarkService.updateChapter(title, chapterIndex + 1);
            return mav;
        }
    }

    // word mode
    Chapter chapter = articleService.getChapter(title, chapterIndex);
    if (answerService.check(chapter, answer)) {
        if (!articleService.isChapterExisted(title, chapterIndex + 1)) {
            bookmarkService.complete(title);
            return new ModelAndView("redirect:/article/" + title + "/license");
        }
        model.addAttribute("chapter", articleService.getChapter(title, chapterIndex + 1));
        model.addAttribute("totalSection", articleService.getTotalSection(title));
        model.addAttribute("answer", articleService.getChapter(title, chapterIndex).getQuiz().getAnswer());
        mav.setViewName(View.CHAPTER);
        mav.addAllObjects(model);

        bookmarkService.updateChapter(title, chapterIndex + 1);
    } else {
        mav.setViewName(View.WRONG);
        mav.addAllObjects(model);
    }
    return mav;
}