Example usage for javax.servlet.http Cookie Cookie

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

Introduction

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

Prototype

public Cookie(String name, String value) 

Source Link

Document

Constructs a cookie with the specified name and value.

Usage

From source file:com.sinosoft.one.mvc.web.var.FlashImpl.java

protected synchronized void readLastMessages() {
    if (lastRead) {
        return;/* w  w  w .  ja va 2  s . com*/
    }
    lastRead = true;
    if (logger.isDebugEnabled()) {
        logger.debug("readLastMessages");
    }
    Cookie[] cookies = invocation.getRequest().getCookies();
    for (int i = 0; cookies != null && i < cookies.length; i++) {
        if (logger.isDebugEnabled()) {
            logger.debug("cookie " + cookies[i].getName() + "=" + cookies[i].getValue() + "; age="
                    + cookies[i].getMaxAge());
        }
        if (cookies[i].getValue() == null) {
            if (logger.isDebugEnabled()) {
                logger.debug("ignore cookie: " + cookies[i].getName());
            }
            continue;
        }
        if (cookies[i].getName().startsWith(cookiePrefix)) {
            StringTokenizer st = new StringTokenizer(cookies[i].getName(), DELIM);
            String[] splits = new String[st.countTokens()];
            for (int j = 0; j < splits.length; j++) {
                splits[j] = st.nextToken();
            }
            if (splits.length < 2) {
                if (logger.isInfoEnabled()) {
                    logger.info("ignore flash cookie: " + cookies[i].getName());
                }
                continue;
            }
            String name = splits[1];
            String cookieValue = cookies[i].getValue();
            String flashMessage;
            if (cookieValue.length() == 0) {
                flashMessage = "";
            } else {
                try {
                    flashMessage = new String(base64.decodeFromString(cookieValue), "UTF-8");
                } catch (Exception e) {
                    logger.error("failed to decode '" + cookieValue + "' as" + " a base64 string", e);
                    flashMessage = cookieValue;
                }
            }
            if (last.size() == 0) {
                last = new LinkedHashMap<String, String>();
            }
            this.last.put(name, flashMessage);
            Cookie cookie = new Cookie(cookies[i].getName(), "");
            cookie.setPath("/");
            cookie.setMaxAge(0);
            invocation.getResponse().addCookie(cookie);
            if (logger.isDebugEnabled()) {
                logger.debug("found flash message:" + name + "=" + flashMessage);
            }
        }
    }
}

From source file:com.openthinks.webscheduler.service.WebSecurityService.java

public Cookie createRememberMeCookie() {
    Cookie cookie = new Cookie(StaticDict.COOKIE_REMEMBER_ME, DigestUtils.sha1Hex(StaticUtils.UUID()));
    cookie.setMaxAge(StaticDict.COOKIE_REMEMBER_ME_EXPIRE_TIME);
    cookie.setPath(StaticUtils.getRootContext());
    return cookie;
}

From source file:com.braintree.cscockpit.widgets.renderers.impl.customer.CustomerPaymentMethodAddWidgetRenderer.java

private void preparedClientCookie() {
    final String clientToken = getCsBrainTreeFacade().generateClientToken();
    final HttpServletResponse response = (HttpServletResponse) Executions.getCurrent().getNativeResponse();
    response.addCookie(new Cookie(COOKIE_CLIENT_TOKEN, clientToken));
}

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

@Test
public void testGetAuthenticationProfileLastModifiedChanged() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    RequestContext context = new RequestContext(request, response);
    RequestSecurityProcessorChain chain = mock(RequestSecurityProcessorChain.class);
    Date profileLastModified = new Date();
    Cookie ticketCookie = new Cookie(SecurityUtils.TICKET_COOKIE_NAME, TICKET);
    Cookie profileLastModifiedCookie = new Cookie(SecurityUtils.PROFILE_LAST_MODIFIED_COOKIE_NAME,
            String.valueOf(profileLastModified.getTime() + 60000));

    request.setCookies(ticketCookie, profileLastModifiedCookie);

    Profile profile = new Profile();
    profile.setLastModified(profileLastModified);

    Profile modifiedProfile = new Profile();
    modifiedProfile.setLastModified(new Date(profileLastModified.getTime() + 60000));

    Authentication auth = new DefaultAuthentication(TICKET, profile);
    Authentication modifiedAuth = new DefaultAuthentication(TICKET, modifiedProfile);

    when(authenticationManager.getAuthentication(TICKET, false)).thenReturn(auth);
    when(authenticationManager.getAuthentication(TICKET, true)).thenReturn(modifiedAuth);

    processor.processRequest(context, chain);

    verify(chain).processRequest(context);

    Authentication newAuth = SecurityUtils.getAuthentication(request);

    assertNotNull(newAuth);//  w w w  .j a  v  a  2 s  . c  o  m
    assertEquals(modifiedAuth.getTicket(), newAuth.getTicket());
    assertEquals(modifiedAuth.getProfile().getLastModified(), newAuth.getProfile().getLastModified());
}

From source file:com.lti.system.MyLogoutFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (!(request instanceof HttpServletRequest)) {
        throw new ServletException("Can only process HttpServletRequest");
    }/*www. j  a va 2  s  . c o  m*/

    if (!(response instanceof HttpServletResponse)) {
        throw new ServletException("Can only process HttpServletResponse");
    }

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    if (requiresLogout(httpRequest, httpResponse)) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();

        if (logger.isDebugEnabled()) {
            logger.debug("Logging out user '" + auth + "' and redirecting to logout page");
        }

        for (int i = 0; i < handlers.length; i++) {
            handlers[i].logout(httpRequest, httpResponse, auth);
        }

        Cookie cookie = new Cookie("jforumSSOCookie", null);
        cookie.setMaxAge(0);
        cookie.setPath("/jforum");
        httpResponse.addCookie(cookie);

        cookie = new Cookie("jforumSSOGroupCookie", null);
        cookie.setMaxAge(0);
        cookie.setPath("/jforum");
        httpResponse.addCookie(cookie);

        request.removeAttribute("legalDate");

        sendRedirect(httpRequest, httpResponse, logoutSuccessUrl);

        return;
    }

    chain.doFilter(request, response);
}

From source file:de.voolk.marbles.web.app.IdentSession.java

@Override
public void invalidate() {
    super.invalidate();
    ((WebResponse) RequestCycle.get().getResponse()).addCookie(new Cookie(IdentSession.IDENT_COOKIE, null));
}

From source file:org.codice.ddf.security.servlet.logout.LocalLogoutServlet.java

private void deleteJSessionId(HttpServletResponse response) {
    Cookie cookie = new Cookie("JSESSIONID", "");
    cookie.setMaxAge(0);//from w  w  w  .j a v a2  s. c  om
    cookie.setPath("/");
    cookie.setComment("EXPIRING COOKIE at " + System.currentTimeMillis());
    response.addCookie(cookie);
}

From source file:com.epam.cme.storefront.security.cookie.EnhancedCookieGeneratorTest.java

@Test
public void testServerSideCookieDynamicPath() {
    cookieGenerator.setCookieName(JSESSIONID);
    cookieGenerator.setHttpOnly(true);// server side
    cookieGenerator.setUseDefaultPath(false);

    BDDMockito.given(request.getContextPath()).willReturn("/some_path");

    cookieGenerator.addCookie(request, response, "cookie_monster");

    final Cookie expectedCookie = new Cookie(JSESSIONID, "cookie_monster");
    expectedCookie.setPath("/some_path");
    expectedCookie.setSecure(false);/*from  w  w w. j a v  a  2s. com*/
    expectedCookie.setMaxAge(NEVER_EXPIRES);
    expectedCookie.setDomain("what a domain");

    Mockito.verify(response).addCookie(Mockito.argThat(new CookieArgumentMatcher(expectedCookie)));
    Mockito.verify(response).addHeader(EnhancedCookieGenerator.HEADER_COOKIE,
            "JSESSIONID=cookie_monster; Domain=\"what a domain\"; Path=/; HttpOnly");

}

From source file:com.anjz.util.CookieUtils.java

private static void setCookie(String key, String value, int maxAge, String path, String domainName,
        final boolean httpOnly, final boolean secure, HttpServletResponse response) {
    if (response != null) {
        Cookie cookie = new Cookie(key, value);
        cookie.setMaxAge(maxAge);//w  w  w .ja va 2s  .  co  m
        if (StringUtils.isNotBlank(path)) {
            cookie.setPath(path);
        } else {
            cookie.setPath(PATH);
        }
        if (StringUtils.isNotBlank(domainName)) {
            cookie.setDomain(domainName);
        }
        cookie.setVersion(0);
        cookie.setSecure(secure);
        if (httpOnly) {
            final StringBuffer buf = new StringBuffer();
            getCookieHeaderValue(cookie, buf, httpOnly);
            response.addHeader(getCookieHeaderName(cookie), buf.toString());
        } else {
            response.addCookie(cookie);
        }
    }
}

From source file:de.hybris.platform.ytelcoacceleratorstorefront.security.cookie.EnhancedCookieGeneratorTest.java

@Test
public void testServerSideCookieDynamicPath() {
    cookieGenerator.setCookieName(JSESSIONID);
    cookieGenerator.setHttpOnly(true);//server side
    cookieGenerator.setUseDefaultPath(false);

    BDDMockito.given(request.getContextPath()).willReturn("/some_path");

    cookieGenerator.addCookie(request, response, "cookie_monster");

    final Cookie expectedCookie = new Cookie(JSESSIONID, "cookie_monster");
    expectedCookie.setPath("/some_path");
    expectedCookie.setSecure(false);//from  w ww . j a v  a  2  s  . c  o  m
    expectedCookie.setMaxAge(NEVER_EXPIRES);
    expectedCookie.setDomain("what a domain");

    Mockito.verify(response).addCookie(Mockito.argThat(new CookieArgumentMatcher(expectedCookie)));
    Mockito.verify(response).addHeader(EnhancedCookieGenerator.HEADER_COOKIE,
            "JSESSIONID=cookie_monster; Domain=\"what a domain\"; Path=/; HttpOnly");

}