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.glaf.core.util.RequestUtils.java

public static String getActorId(HttpServletRequest request) {
    String actorId = null;/* www . j a  v a2 s.  c  o  m*/
    String ip = getIPAddress(request);
    ip = DigestUtils.md5Hex(ip);
    HttpSession session = request.getSession(false);
    if (session != null) {
        String value = (String) session.getAttribute(Constants.LOGIN_INFO);
        Map<String, String> cookieMap = decodeValues(ip, value);
        if (StringUtils.equals(cookieMap.get(Constants.LOGIN_IP), ip)) {
            actorId = cookieMap.get(Constants.LOGIN_ACTORID);
            logger.debug("#actorId=" + actorId);
        }
    }

    if (actorId == null) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (StringUtils.equals(cookie.getName(), Constants.COOKIE_NAME)) {
                    String value = cookie.getValue();
                    Map<String, String> cookieMap = decodeValues(ip, value);
                    // logger.debug("#cookieMap=" + cookieMap);
                    if (StringUtils.equals(cookieMap.get(Constants.LOGIN_IP), ip)) {
                        String time = cookieMap.get(Constants.TS);
                        long now = Long.MAX_VALUE - System.currentTimeMillis();
                        if (StringUtils.isNumeric(time)
                                && (Long.parseLong(time) - now) < COOKIE_LIVING_SECONDS * 1000) {
                            actorId = cookieMap.get(Constants.LOGIN_ACTORID);
                            break;
                        }
                    }
                }
            }
        }
    }

    logger.debug("@actorId=" + actorId);

    return actorId;
}

From source file:com.glaf.core.util.RequestUtils.java

public static String getCurrentSystem(HttpServletRequest request) {
    String currentSystem = null;//from w w  w.j  a  v  a  2 s.  c  o  m
    String paramValue = request.getParameter(Constants.SYSTEM_NAME);
    if (StringUtils.isNotEmpty(paramValue)) {
        return paramValue;
    }
    String ip = getIPAddress(request);
    ip = DigestUtils.md5Hex(ip);
    HttpSession session = request.getSession(false);
    if (session != null) {
        String value = (String) session.getAttribute(Constants.LOGIN_INFO);
        Map<String, String> cookieMap = decodeValues(ip, value);
        if (StringUtils.equals(cookieMap.get(Constants.LOGIN_IP), ip)) {
            currentSystem = cookieMap.get(Constants.SYSTEM_NAME);
        }
    }

    if (currentSystem == null) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (StringUtils.equals(cookie.getName(), Constants.COOKIE_NAME)) {
                    String value = cookie.getValue();
                    Map<String, String> cookieMap = decodeValues(ip, value);
                    if (StringUtils.equals(cookieMap.get(Constants.LOGIN_IP), ip)) {
                        String time = cookieMap.get(Constants.TS);
                        long now = Long.MAX_VALUE - System.currentTimeMillis();
                        if (StringUtils.isNumeric(time)
                                && (Long.parseLong(time) - now) < COOKIE_LIVING_SECONDS * 1000) {
                            currentSystem = cookieMap.get(Constants.SYSTEM_NAME);
                            break;
                        }
                    }
                }
            }
        }
    }

    return currentSystem;
}

From source file:org.geonode.security.GeoNodeCookieProcessingFilter.java

private String getGeoNodeCookieValue(HttpServletRequest request) {
    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine("Inspecting the http request looking for the GeoNode Session ID.");
    }//  ww  w  .j  a  v  a 2  s  . com
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.fine("Found " + cookies.length + " cookies!");
        }
        for (Cookie c : cookies) {
            if (GEONODE_COOKIE_NAME.equals(c.getName())) {
                if (LOGGER.isLoggable(Level.FINE)) {
                    LOGGER.fine("Found GeoNode cookie: " + c.getValue());
                }
                return c.getValue();
            }
        }
    } else {
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.fine("Found no cookies!");
        }
    }

    return null;
}

From source file:com.acc.storefront.filters.RequestLoggerFilter.java

protected void logCookies(final HttpServletRequest httpRequest) {
    if (LOG.isDebugEnabled()) {
        final Cookie[] cookies = httpRequest.getCookies();
        if (cookies != null) {
            for (final Cookie cookie : cookies) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("COOKIE Name: [" + cookie.getName() + "] Path: [" + cookie.getPath()
                            + "] Value: [" + cookie.getValue() + "]");
                }//from w  ww.  j  a  v  a2 s . c  o  m
            }
        }
    }
}

From source file:com.itude.mobile.mobbl.server.http.HttpDelegate.java

private void prepareConnection(HttpMethod method, String userAgent, ArrayList<Cookie> cookies,
        Header[] requestHeaders, boolean acceptXml, boolean followRedirects) {
    logger.debug("HttpDelegate.prepareConnection()");

    if (logger.isDebugEnabled())
        HeaderUtil.printRequestHeaders(logger, method);

    if (acceptXml)
        method.addRequestHeader("Accept", "application/xml, */*");

    if (cookies != null) {
        for (Cookie cookie : cookies)
            method.addRequestHeader("Cookie", cookie.getName() + "=" + cookie.getValue());
    }/*from  w  ww  . j a v a  2  s.c  o m*/

    if (userAgent != null)
        method.addRequestHeader(Constants.USER_AGENT, userAgent);

    method.setFollowRedirects(followRedirects);

    if (requestHeaders != null)
        for (Header h : requestHeaders)
            method.addRequestHeader(h);

}

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

private String getRememberMeCookieValue() {
    final Cookie cookie = getRememberMeCookie();
    if (cookie == null) {
        return null;
    }//from w  w w  .  j a  va 2s. c  om
    final String rememberMeToken = cookie.getValue();
    return rememberMeToken;
}

From source file:com.mitre.storefront.interceptors.beforecontroller.RequireHardLoginBeforeControllerHandler.java

@Override
public boolean beforeController(final HttpServletRequest request, final HttpServletResponse response,
        final HandlerMethod handler) throws Exception {
    // We only care if the request is secure
    if (request.isSecure()) {
        // Check if the handler has our annotation
        final RequireHardLogIn annotation = findAnnotation(handler, RequireHardLogIn.class);
        if (annotation != null) {
            boolean redirect = true;
            final String guid = (String) request.getSession().getAttribute(SECURE_GUID_SESSION_KEY);
            final boolean anonymousUser = getUserService().isAnonymousUser(getUserService().getCurrentUser());
            if (!anonymousUser && guid != null && request.getCookies() != null) {
                final String guidCookieName = getCookieGenerator().getCookieName();
                if (guidCookieName != null) {
                    for (final Cookie cookie : request.getCookies()) {
                        if (guidCookieName.equals(cookie.getName())) {
                            if (guid.equals(cookie.getValue())) {
                                redirect = false;
                                break;
                            } else {
                                LOG.info("Found secure cookie with invalid value. expected [" + guid
                                        + "] actual [" + cookie.getValue() + "]. removing.");
                                getCookieGenerator().removeCookie(response);
                            }//from   ww  w . j  a va  2  s.  c  o  m
                        }
                    }
                }
            }

            if (redirect) {
                final String ajaxHeader = request.getHeader(ajaxRequestHeaderKey);
                LOG.warn((guid == null ? "missing secure token in session" : "no matching guid cookie")
                        + ", redirecting");
                if (ajaxRequestHeaderValue.equals(ajaxHeader)) {
                    response.addHeader("redirectUrl", request.getContextPath() + getRedirectUrl(request));
                    response.sendError(Integer.parseInt(ajaxRedirectErrorCode));
                } else {
                    getRedirectStrategy().sendRedirect(request, response, getRedirectUrl(request));
                }
                return false;
            }
        }
    }

    return true;
}

From source file:com.foilen.smalltools.spring.security.CookiesGeneratedCsrfTokenRepository.java

@Override
public CsrfToken generateToken(HttpServletRequest request) {
    AssertTools.assertNotNull(salt, "You must set the salt");
    AssertTools.assertFalse(cookieNames.isEmpty(), "You must set at least one cookie");

    // Search all the cookies
    Map<String, String> valuesByName = new HashMap<>();
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookieNames.contains(cookie.getName())) {
                String previousValue = valuesByName.put(cookie.getName(), cookie.getValue());
                if (previousValue != null) {
                    throw new SmallToolsException(
                            "The cookie with name " + cookie.getName() + " contains more than one value");
                }/*from  www  . j  av a2 s  .com*/
            }
        }
    }

    // Generate the token
    StringBuilder allValues = new StringBuilder(salt);
    for (String cookieName : cookieNames) {
        String cookieValue = valuesByName.get(cookieName);
        logger.debug("Adding cookie {} with value {}", cookieName, cookieValue);
        allValues.append(cookieName).append(cookieValue);
    }

    String token = HashSha256.hashString(allValues.toString());
    logger.debug("Token is {}", token);
    return new DefaultCsrfToken(HEADER_NAME, PARAMETER_NAME, token);
}

From source file:cec.easyshop.storefront.filters.CartRestorationFilter.java

@Override
public void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response,
        final FilterChain filterChain) throws IOException, ServletException {
    if (getUserService().isAnonymousUser(getUserService().getCurrentUser())) {
        if (getCartService().hasSessionCart() && getBaseSiteService().getCurrentBaseSite().equals(
                getBaseSiteService().getBaseSiteForUID(getCartService().getSessionCart().getSite().getUid()))) {
            final String guid = getCartService().getSessionCart().getGuid();

            if (!StringUtils.isEmpty(guid)) {
                getCartRestoreCookieGenerator().addCookie(response, guid);
            }//from   w ww  .  j a v a 2  s. c  o m
        } else if (request.getSession().isNew() || (getCartService().hasSessionCart()
                && !getBaseSiteService().getCurrentBaseSite().equals(getBaseSiteService()
                        .getBaseSiteForUID(getCartService().getSessionCart().getSite().getUid())))) {
            String cartGuid = null;

            if (request.getCookies() != null) {
                final String anonymousCartCookieName = getCartRestoreCookieGenerator().getCookieName();

                for (final Cookie cookie : request.getCookies()) {
                    if (anonymousCartCookieName.equals(cookie.getName())) {
                        cartGuid = cookie.getValue();
                        break;
                    }
                }
            }

            if (!StringUtils.isEmpty(cartGuid)) {
                getSessionService().setAttribute(WebConstants.CART_RESTORATION_SHOW_MESSAGE, Boolean.TRUE);
                try {
                    getSessionService().setAttribute(WebConstants.CART_RESTORATION,
                            getCartFacade().restoreSavedCart(cartGuid));
                } catch (final CommerceCartRestorationException e) {
                    getSessionService().setAttribute(WebConstants.CART_RESTORATION_ERROR_STATUS,
                            WebConstants.CART_RESTORATION_ERROR_STATUS);
                }
            }
        }

    } else {
        if ((!getCartService().hasSessionCart()
                && getSessionService().getAttribute(WebConstants.CART_RESTORATION) == null)
                || (getCartService().hasSessionCart()
                        && !getBaseSiteService().getCurrentBaseSite().equals(getBaseSiteService()
                                .getBaseSiteForUID(getCartService().getSessionCart().getSite().getUid())))) {
            getSessionService().setAttribute(WebConstants.CART_RESTORATION_SHOW_MESSAGE, Boolean.TRUE);
            try {
                getSessionService().setAttribute(WebConstants.CART_RESTORATION,
                        getCartFacade().restoreSavedCart(null));
            } catch (final CommerceCartRestorationException e) {
                getSessionService().setAttribute(WebConstants.CART_RESTORATION,
                        WebConstants.CART_RESTORATION_ERROR_STATUS);
            }
        }
    }

    filterChain.doFilter(request, response);
}

From source file:spring.travel.site.controllers.HomeControllerTest.java

@Test
public void shouldReturnOffersForUserWithNoAddress() throws Exception {
    stubGet("/user?id=123", new User("123", "Fred", "Flintstone", "freddyf", Optional.<Address>empty()));

    stubWeather("/weather?id=2643741&cnt=5&mode=json");

    stubGet("/profile/user/123", new Profile(LifeCycle.Family, Spending.Economy, Gender.Male));

    stubGet("/loyalty/user/123", new Loyalty(Group.Bronze, 100));

    List<Offer> offers = Arrays.asList(new Offer("Offer 1", "Blah blah", "offer1.jpg"),
            new Offer("Offer 2", "Blah blah", "offer2.jpg"), new Offer("Offer 3", "Blah blah", "offer3.jpg"),
            new Offer("Offer 4", "Blah blah", "offer4.jpg"));

    stubGet("/offers?lifecycle=family&spending=economy&gender=male&loyalty=bronze", offers);

    List<Advert> adverts = Arrays.asList(new Advert("Advert 1", "advert1.jpg", "Blah blah"),
            new Advert("Advert 2", "advert2.jpg", "Blah blah"),
            new Advert("Advert 3", "advert3.jpg", "Blah blah"),
            new Advert("Advert 4", "advert4.jpg", "Blah blah"),
            new Advert("Advert 5", "advert5.jpg", "Blah blah"));

    stubGet("/adverts?count=5&target=low", adverts);

    String signature = "0923023985092384";
    String cookieName = "GETAWAY_SESSION";
    String encoded = "id=123";
    String cookieValue = signature + "-" + encoded;

    Cookie cookie = Mockito.mock(Cookie.class);
    when(cookie.getName()).thenReturn(cookieName);
    when(cookie.getValue()).thenReturn(cookieValue);

    when(mockVerifier.verify(encoded, signature)).thenReturn(true);

    MvcResult mvcResult = this.mockMvc
            .perform(get("/").accept(MediaType.parseMediaType("application/json;charset=UTF-8"))
                    .header("Cookie", cookieName + "=" + cookieValue))
            .andExpect(status().isOk()).andExpect(request().asyncStarted())
            .andExpect(request().asyncResult(isA(ModelAndView.class))).andReturn();

    this.mockMvc.perform(asyncDispatch(mvcResult)).andExpect(status().isOk());

    ModelAndView modelAndView = (ModelAndView) mvcResult.getAsyncResult(1000);

    Map<String, Object> model = modelAndView.getModel();

    User user = (User) model.get("user");
    assertEquals("Fred", user.getFirstName());

    OffersView modelOffers = (OffersView) model.get("offers");
    assertNotNull(modelOffers);/*from   w  ww. j  a  v a 2  s.co  m*/
    assertEquals("Offer 1", modelOffers.getOffers().get(0).getTitle());

    AdvertsView modelAdverts = (AdvertsView) model.get("adverts");
    assertNotNull(modelAdverts);
    assertEquals("Advert 1", modelAdverts.getAdverts().get(0).getTitle());

    DailyForecastView modelForecast = (DailyForecastView) model.get("weather");
    assertEquals("Colnbrook", modelForecast.getCity());
}