Example usage for javax.servlet.http Cookie getName

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

Introduction

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

Prototype

public String getName() 

Source Link

Document

Returns the name of the cookie.

Usage

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  w  w . jav  a 2  s.c o 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());
}

From source file:eu.europeana.core.util.web.ClickStreamLoggerImpl.java

private String printLogAffix(HttpServletRequest request) {
    String ip = request.getRemoteAddr();
    String reqUrl = getRequestUrl(request);
    final User user = ControllerUtil.getUser();
    String userId;/*  w  w w . j a v  a2 s  .c  om*/
    if (user != null) {
        userId = user.getEmail(); // todo: is this desirable?  was id.toString()
    } else {
        userId = "";
    }
    String language = ControllerUtil.getLocale(request).toString();
    String userAgent = request.getHeader("User-Agent");
    String referer = request.getHeader("referer");
    Cookie[] cookies = request.getCookies();
    String utma = "";
    String utmb = "";
    String utmc = "";
    String utmz = "";
    String languageCookie = "";
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equalsIgnoreCase("__utma")) {
                utma = cookie.getValue();
            } else if (cookie.getName().equalsIgnoreCase("__utmb")) {
                utmb = cookie.getValue();
            } else if (cookie.getName().equalsIgnoreCase("__utmc")) {
                utmc = cookie.getValue();
            } else if (cookie.getName().equalsIgnoreCase("__utmz")) {
                utmz = cookie.getValue();
            } else if (cookie.getName()
                    .equalsIgnoreCase("org.springframework.web.servlet.i18n.CookieLocaleResolver.LOCALE")) {
                languageCookie = cookie.getValue();
            }
        }
    }
    PortalTheme theme = themeHandler.getByRequest(request);
    return MessageFormat.format(
            "userId={0}, lang={1}, req={4}, date={2}, ip={3}, user-agent={5}, referer={6}, utma={8}, "
                    + "utmb={9}, utmc={10}, utmz={13}, v={7}, duration={11}, langCookie={12}, defaultLanguage={14}",
            userId, language, new DateTime(), ip, reqUrl, userAgent, referer, VERSION, utma, utmb, utmc,
            ClickStreamLoggerInterceptor.getTimeElapsed(), languageCookie, utmz, theme.getDefaultLanguage());
}

From source file:fedroot.dacs.http.DacsCookie.java

/** 
 * Creates a new instance of DacsCookie from a javax.servlet.http.net.Cookie
 */// ww w. j ava2s  . c  om
public DacsCookie(String domain, javax.servlet.http.Cookie cookie) throws DacsRuntimeException {
    //        super(federationDomain, jcookie.getName(),jcookie.getValue(),"/", jcookie.getMaxAge(),jcookie.getSecure());
    super(cookie.getName(), cookie.getValue());

    if (!isDacsCookie(cookie)) {
        throw new DacsRuntimeException("invalid DACS cookie: " + cookie.getName());
    }

    // the domain of a DACS federation never refers to a single host
    // if there is no leading dot we add one to the domain,
    // so a cookie with domain "foo.com" becomes a DACS
    // cookie with domain ".foo.com" causing user agents to send the cookie
    // to hosts foo.com, bar.foo.com, baz.foo.com etc

    setVersion(1);
    if (domain.startsWith(".")) {
        setDomain(domain);
    } else {
        setDomain("." + domain);
    }
    setPath("/");

    if (cookie.getMaxAge() == -1) {
    } else {
        Date expires = new Date();
        expires.setTime(expires.getTime() + cookie.getMaxAge());
        setExpiryDate(expires);
    }

    setSecure(cookie.getSecure());
}

From source file:iddb.web.security.service.CommonUserService.java

private String getCookie(Cookie[] cookies, String key) {
    if (cookies == null || cookies.length == 0) {
        log.trace("No cookies sent");
        return null;
    }/*from  w  w w.  j  a v  a2  s. c  o m*/
    for (Cookie c : cookies) {
        log.trace("List cookie {} with value {}", c.getName(), c.getValue());
        if (key.equals(c.getName())) {
            return c.getValue();
        }
    }
    return null;
}

From source file:net.ymate.platform.webmvc.util.CookieHelper.java

private Cookie __doGetCookie(String cookieName) {
    Cookie _cookies[] = WebContext.getRequest().getCookies();
    if (_cookies == null) {
        return null;
    } else {//w  w  w .ja v  a  2  s  . com
        for (Cookie _cookie : _cookies) {
            String name = _cookie.getName();
            if (name.equals(cookieName)) {
                return _cookie;
            }
        }
        return null;
    }
}

From source file:com.junly.service.helper.TicketHelper.java

/** <p class="detail">
* ???ticket//from   ww  w .  j  av a  2s .  c  om
* </p>
* @author junly
* @date 2017324 
* @param request
* @param httpChannelType
* @return    
*/
public String getTicket(HttpServletRequest request, HttpChannelType httpChannelType) {

    Cookie cookies[] = request.getCookies();

    String ticket = null;

    if (null != cookies) {
        for (Cookie cookie : cookies) {
            if (StringUtils.equals(ViewContants.LOGIN_TICKET_KEY, cookie.getName())) {

                ticket = StringUtils.trim(cookie.getValue());

                StringBuilder builder = new StringBuilder(httpChannelType.name());
                builder.append("?cookieticket=").append(ticket);
                builder.append("?=").append(request.getServerName()).append("====");
                builder.append(cookie.getDomain());
                logger.info(builder.toString());

                break;
            }
        }
    }

    // java??cookieheader???,
    // ???cookie? ??
    if (StringUtils.isBlank(ticket)) {
        ticket = customHeadTicket(request, httpChannelType);
    }

    if (StringUtils.isBlank(ticket)) {
        ticket = StringUtils.trim(request.getParameter(ViewContants.LOGIN_TICKET_KEY));
    }

    return ticket;
}

From source file:net.ymate.platform.webmvc.util.CookieHelper.java

/**
 * @return ?Cookie//from   www.  j a va2 s  .  c  om
 */
public Map<String, BlurObject> getCookies() {
    Map<String, BlurObject> _returnValue = new HashMap<String, BlurObject>();
    Cookie[] _cookies = WebContext.getRequest().getCookies();
    if (_cookies != null) {
        String _cookiePre = __owner.getModuleCfg().getCookiePrefix();
        int _preLength = StringUtils.length(_cookiePre);
        for (Cookie _cookie : _cookies) {
            String _name = _cookie.getName();
            if (_name.startsWith(_cookiePre)) {
                String _v = decodeValue(_cookie.getValue());
                _returnValue.put(_name.substring(_preLength), new BlurObject(_v));
            }
        }
    }
    return _returnValue;
}

From source file:com.mobilehelix.appserver.session.SessionManager.java

private String getSessIDFromRequest(HttpServletRequest req) throws AppserverSystemException {
    String sessIDB64 = req.getHeader(HTTPHeaderConstants.MH_SESSION_ID_HEADER);
    if ((sessIDB64 == null) && (req.getCookies() != null)) {
        for (Cookie c : req.getCookies()) {
            if (HTTPHeaderConstants.MH_SESSION_ID_HEADER.equalsIgnoreCase(c.getName())) {
                sessIDB64 = c.getValue();
                break;
            }//w  w w .j  a  v  a2s  .co m
        }
    }
    // Decode the B64-encoded key.
    if (sessIDB64 != null) {
        byte[] sessID = Base64.decodeBase64(sessIDB64);
        return this.hashSessionID(sessID);
    }
    return null;
}

From source file:com.alfaariss.oa.util.web.CookieTool.java

/**
 * Returns the cookie value.//from   www  .j av  a 2 s.c o  m
 * @param sCookie The cookie name.
 * @param oRequest The servlet request.
 * @return The cookie value or NULL if not available.
 */
public String getCookieValue(String sCookie, HttpServletRequest oRequest) {
    assert oRequest != null : "Supplied request == null";

    String sValue = null;
    Cookie[] cookies = oRequest.getCookies();
    if (cookies != null) //Cookies found
    {
        for (Cookie cookie : cookies) //For all cookies
        {
            if (cookie.getName().equals(sCookie)) //cookie found
            {
                sValue = cookie.getValue();
                //remove '"' surrounding cookie value if applicable
                int iLength = sValue.length();
                if (sValue.charAt(0) == '"' && sValue.charAt(iLength - 1) == '"') {
                    sValue = sValue.substring(1, iLength - 1);
                }
            }
        }
    }
    return sValue;
}

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

/**
 * Tries to create an SSOToken based on the HTTP request
 * /*www. ja va  2  s.com*/
 * @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;
}