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.microsoft.azure.oidc.filter.helper.impl.SimpleAuthenticationHelper.java

private String addCookie(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse,
        final String cookieName, final String cookieValue) {
    if (httpRequest == null || httpResponse == null || cookieName == null || cookieValue == null) {
        throw new PreconditionException("Required parameter is null");
    }/*from  ww  w .  j  a  va 2  s  .c  o  m*/
    final Cookie cookie = new Cookie(cookieName, "");
    cookie.setValue(cookieValue);
    cookie.setMaxAge(-1);
    cookie.setSecure(true);
    cookie.setDomain(httpRequest.getServerName());
    cookie.setPath("/");
    cookie.setHttpOnly(true);
    httpResponse.addCookie(cookie);
    return cookie.getValue();
}

From source file:com.zz.globalsession.filter.AbstractGlobalSessionFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest _req = (HttpServletRequest) req;
    HttpServletResponse _res = (HttpServletResponse) res;

    if (isGlobalSessionHttpRequest(_req)) {

        if (log.isDebugEnabled()) {
            log.debug("GlobalSessionHttpRequest is already applied.");
        }/*from w  ww. j  av  a2 s.  co  m*/
        chain.doFilter(_req, _res);

    } else if (settings.getExcludeRegExp() != null
            && _req.getRequestURI().matches(settings.getExcludeRegExp())) {

        if (log.isDebugEnabled()) {
            log.debug("This URI is excluded. (URI: " + _req.getRequestURI() + ")");
        }
        chain.doFilter(_req, _res);

    } else {

        Cookie currentValidSessionIdCookie = getCurrentValidSessionIdCookie(_req);

        String sessionIdValue = null;
        if (currentValidSessionIdCookie == null) {
            // copy JSESSIONID value to original session
            sessionIdValue = _req.getSession().getId();
        } else {
            // current original session is valid
            sessionIdValue = currentValidSessionIdCookie.getValue();
        }

        if (currentValidSessionIdCookie == null) {
            Cookie newSessionIdCookie = generateSessionIdCookie(sessionIdValue);
            // [Note] httpOnly is not supported by Servlet API 2.x, so need
            // to call #addHeader instead of #addCookie
            /*  */
            String setCookie = CookieUtil.createSetCookieHeaderValue(newSessionIdCookie, settings.isHttpOnly());
            _res.addHeader("Set-Cookie", setCookie);

            // _res.addCookie(newSessionIdCookie);
            setSessionStatus(_req, SessionStatus.fixed);

            if (log.isDebugEnabled()) {
                log.debug("SessionId cookie is updated. (" + sessionIdValue + ")");
            }
        }

        // doFilter with the request wrapper
        GlobalSessionHttpRequest _wrappedReq = createGlobalSessionRequest(_req, sessionIdValue);
        chain.doFilter(_wrappedReq, _res);

        // update attributes, expiration
        GlobalHttpSession session = _wrappedReq.getSession();
        session.reloadAttributes(); // need reloading from the store to work
                                    // with GlassFish
        session.save();
    }
}

From source file:com.liusoft.dlog4j.velocity.DLOG_Stat_VelocityTool.java

/**
 * ?//from   w w  w.  j a  v a2s.c om
 * @param site
 */
public boolean execute(HttpServletRequest request, HttpServletResponse response, SiteBean site, int source) {
    boolean write_db = false;
    Cookie u_cookie = RequestUtils.getCookie(request, KEY_COOKIE);
    String ident = getSiteIdAsString(site);
    if (u_cookie == null) {
        //Cookie?
        Calendar t = Calendar.getInstance();
        t.add(Calendar.DATE, 1);
        DateUtils.resetTime(t);
        int maxAge = (int) (t.getTime().getTime() - System.currentTimeMillis()) / 1000;
        RequestUtils.setCookie(request, response, KEY_COOKIE, ident, maxAge);
        write_db = true;
    } else {
        String cookie_value = u_cookie.getValue();
        if (cookie_value.indexOf(ident) < 0) {
            //Cookie?
            Calendar t = Calendar.getInstance();
            t.add(Calendar.DATE, 1);
            DateUtils.resetTime(t);
            int maxAge = (int) (t.getTime().getTime() - System.currentTimeMillis()) / 1000;
            //Cookie
            RequestUtils.setCookie(request, response, KEY_COOKIE, cookie_value + ident, maxAge);
            write_db = true;
        }
    }
    if (write_db && site != null) {
        //
        try {
            VisitStatDAO.writeStatData(site.getId(), 1, source);
            return true;
        } catch (Exception e) {
            log.error("write visit stat failed.", e);
        }
    }
    return false;
}

From source file:org.springframework.test.web.servlet.htmlunit.HtmlUnitRequestBuilderTest.java

@Test
public void buildRequestCookiesMulti() {
    webRequest.setAdditionalHeader("Cookie", "name=value; name2=value2");

    MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);

    Cookie[] cookies = actualRequest.getCookies();
    assertThat(cookies.length).isEqualTo(2);
    Cookie cookie = cookies[0];
    assertThat(cookie.getName()).isEqualTo("name");
    assertThat(cookie.getValue()).isEqualTo("value");
    cookie = cookies[1];//from w w w .j ava 2  s  .c  o  m
    assertThat(cookie.getName()).isEqualTo("name2");
    assertThat(cookie.getValue()).isEqualTo("value2");
}

From source file:ch.ralscha.extdirectspring.util.ParametersResolver.java

private Object resolveCookieValue(HttpServletRequest request, ParameterInfo parameterInfo) {

    Cookie cookieValue = WebUtils.getCookie(request, parameterInfo.getName());
    String value = null;/*ww w .ja  va 2s . c om*/

    if (cookieValue != null) {
        value = this.urlPathHelper.decodeRequestString(request, cookieValue.getValue());
    } else {
        value = parameterInfo.getDefaultValue();
    }

    if (value != null) {
        return convertValue(value, parameterInfo);
    }

    // value is null and the parameter is java.util.Optional then return an empty
    // Optional
    if (parameterInfo.isJavaUtilOptional()) {
        return javaUtilOptionalEmpty;
    }

    if (parameterInfo.isRequired()) {
        throw new IllegalStateException("Missing cookie '" + parameterInfo.getName() + "' of type ["
                + parameterInfo.getTypeDescriptor().getType() + "]");
    }

    return null;
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.externalServices.OAuthAction.java

/** ACTIONS **/
// http://localhost:8080/ciapl/external/oauth/userdialog&client_id=123123&redirect_uri=http://www.google.com

public ActionForward getUserPermission(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    String clientId = request.getParameter("client_id");
    String redirectUrl = request.getParameter("redirect_uri");
    Person person = getLoggedPerson(request);

    if (!StringUtils.isEmpty(clientId) && !StringUtils.isEmpty(redirectUrl)) {
        if (person == null) {
            //redirect person to this action with client id in session

            final String cookieValue = clientId + "|" + redirectUrl;
            response.addCookie(/*from  w  w  w.jav  a 2 s  .  com*/
                    new Cookie(OAUTH_SESSION_KEY, Base64.getEncoder().encodeToString(cookieValue.getBytes())));
            if (CoreConfiguration.casConfig().isCasEnabled()) {
                response.sendRedirect(CoreConfiguration.casConfig().getCasLoginUrl(
                        CoreConfiguration.getConfiguration().applicationUrl() + "/oauth/userdialog"));
            } else {
                response.sendRedirect(request.getContextPath() + "/oauth/userdialog");
            }
            return null;
        } else {
            return redirectToRedirectUrl(mapping, request, response, person, clientId, redirectUrl);
        }
    } else {
        if (person != null) {
            // this is the request that will recover client id from session
            final Cookie cookie = CookieReaderUtils.getCookieForName(OAUTH_SESSION_KEY, request);
            if (cookie == null) {
                logger.debug("Cookie can't be null because this a direct request from this action with cookie");
                return mapping.findForward("oauthErrorPage");
            }
            final String sessionClientId = cookie.getValue();
            if (!StringUtils.isEmpty(sessionClientId)) {
                return redirectToRedirectUrl(mapping, request, response, person, cookie);
            }
        } else {
            logger.debug("Person should not be null since this a redirect from this action with cookie");
        }
    }

    return mapping.findForward("oauthErrorPage");

}

From source file:ELK.ELKController.java

private String getSessionCookie(final Request request) {
    if (request.raw().getCookies() == null) {
        return null;
    }//from  ww  w.j  a va2  s .  c  o  m
    for (Cookie cookie : request.raw().getCookies()) {
        if (cookie.getName().equals("session")) {
            return cookie.getValue();
        }
    }
    return null;
}

From source file:net.jforum.core.SessionManager.java

/**
 * Checks user credentials / automatic login.
 *
 * @param userSession The UserSession instance associated to the user's session
 * @return <code>true</code> if auto login was enabled and the user was sucessfuly logged in.
 *//*  w  ww  .j  av  a 2s.c o  m*/
private boolean checkAutoLogin(UserSession userSession) {
    Cookie userIdCookie = userSession.getCookie(this.config.getValue(ConfigKeys.COOKIE_USER_ID));
    Cookie hashCookie = userSession.getCookie(this.config.getValue(ConfigKeys.COOKIE_USER_HASH));
    Cookie autoLoginCookie = userSession.getCookie(this.config.getValue(ConfigKeys.COOKIE_AUTO_LOGIN));

    if (hashCookie != null && userIdCookie != null
            && !userIdCookie.getValue().equals(this.config.getValue(ConfigKeys.ANONYMOUS_USER_ID))
            && autoLoginCookie != null && "1".equals(autoLoginCookie.getValue())) {
        String userId = userIdCookie.getValue();
        String uidHash = hashCookie.getValue();

        User user = this.userRepository.get(Integer.parseInt(userId));

        if (user == null || user.isDeleted() || StringUtils.isEmpty(user.getSecurityHash())) {
            userSession.becomeAnonymous(this.config.getInt(ConfigKeys.ANONYMOUS_USER_ID));
            return false;
        }

        String securityHash = MD5.hash(user.getSecurityHash());

        if (!securityHash.equals(uidHash)) {
            userSession.becomeAnonymous(this.config.getInt(ConfigKeys.ANONYMOUS_USER_ID));
            return false;
        } else {
            userSession.setUser(user);
            this.configureUserSession(userSession, user);
            return true;
        }
    }

    return false;
}

From source file:com.microsoft.azure.oidc.filter.helper.impl.SimpleAuthenticationHelper.java

private HttpServletRequest clearSessionCoookie(final HttpServletRequest httpRequest,
        final HttpServletResponse httpResponse, final Token token, final State state) {
    if (httpRequest == null || httpResponse == null || token == null || state == null) {
        throw new PreconditionException("Required parameter is null");
    }//from  w  ww.j ava 2  s .c  o  m
    final Cookie redisSessionCookie = getCookie(httpRequest, "SESSION");
    final Cookie javaSessionCookie = getCookie(httpRequest, "JSESSIONID");
    if (redisSessionCookie != null || javaSessionCookie != null) {
        if (token.getUserID().toString().equals(state.getUserID())) {
            if (redisSessionCookie != null && redisSessionCookie.getValue().equals(state.getSessionName())) {
                return httpRequest;
            }
            if (javaSessionCookie != null && javaSessionCookie.getValue().equals(state.getSessionName())) {
                return httpRequest;
            }
        }
        if (redisSessionCookie != null) {
            redisSessionCookie.setMaxAge(0);
            httpResponse.addCookie(redisSessionCookie);
            HttpSession session = httpRequest.getSession(false);
            if (session != null) {
                session.invalidate();
            }
        }
        if (javaSessionCookie != null) {
            javaSessionCookie.setMaxAge(0);
            httpResponse.addCookie(javaSessionCookie);
            HttpSession session = httpRequest.getSession(false);
            if (session != null) {
                session.invalidate();
            }
        }
        return new HttpServletRequestWrapper(httpRequest) {
            @Override
            public Cookie[] getCookies() {
                final List<Cookie> cookieList = new ArrayList<Cookie>();
                for (Cookie cookie : httpRequest.getCookies()) {
                    if (!cookie.getName().equals("SESSION") && !cookie.getName().equals("JSESSIONID")) {
                        cookieList.add(cookie);
                    }
                }
                final Cookie[] cookieArray = new Cookie[cookieList.size()];
                cookieList.toArray(cookieArray);
                return cookieArray;
            }
        };
    }
    return httpRequest;
}