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:cn.vlabs.duckling.vwb.CPSFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    int advSiteId = Integer.parseInt(StringUtils.defaultIfEmpty(request.getParameter("as"), "-1"));

    if (advSiteId <= 0) {
        chain.doFilter(request, response);
        return;//from   w w w  .j a  v  a 2 s .  com
    }

    HttpServletResponse rep = (HttpServletResponse) response;
    HttpServletRequest req = (HttpServletRequest) request;
    request.setAttribute("cps", advSiteId);

    Cookie[] cookies = req.getCookies();

    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (StringUtils.equals(CPS_ADV, cookie.getName())) {
                cookie.setPath(req.getContextPath());
                cookie.setMaxAge(0);
            }
        }
    }

    Cookie myCookie = new Cookie(CPS_ADV, advSiteId + "");
    myCookie.setMaxAge(60 * 60 * 24);//
    myCookie.setPath(req.getContextPath());
    rep.addCookie(myCookie);
    chain.doFilter(request, response);
}

From source file:org.slc.sli.dashboard.web.unit.interceptor.SessionCheckInterceptorTest.java

@Test
public void testPreHandle() throws Exception {
    SessionCheckInterceptor scInterceptor = new SessionCheckInterceptor();
    PowerMockito.mockStatic(SecurityUtil.class);
    PowerMockito.when(SecurityUtil.getToken()).thenReturn("sravan");
    MockHttpServletRequest request = new MockHttpServletRequest() {
        public HttpSession getSession() {
            return new MockHttpSession();
        }/*from   w  ww .j a va2 s .  c  o  m*/

        public Cookie[] getCookies() {
            Cookie c = new Cookie(SLIAuthenticationEntryPoint.DASHBOARD_COOKIE, "fake");
            return new Cookie[] { c };
        }

        public String getRequestURI() {
            return "fake_uri";
        }

    };

    MockHttpServletResponse response = new MockHttpServletResponse() {

        public void sendRedirect(String url) {
            assertEquals(url, "fake_uri");
        }
    };

    RESTClient restClient = new RESTClient() {
        public JsonObject sessionCheck(String token) {
            JsonObject json = new JsonObject();
            json.addProperty("authenticated", false);
            return json;
        }
    };

    scInterceptor.setRestClient(restClient);

    assertEquals(scInterceptor.preHandle(request, response, null), false);
}

From source file:com.baron.bm.controller.MemberController.java

@RequestMapping("/login")
public ModelAndView login(HttpServletResponse response, MemberModel model) {

    ModelAndView mav = new ModelAndView("loginResult");
    model = joinService.login(model);/*from  w ww.  j a  v  a 2  s.  c  o m*/
    if (model != null) {
        System.out.println(model.getId() + model.getPermission());
        response.addCookie(new Cookie("bm_id", model.getId()));
        response.addCookie(new Cookie("bm_permission", model.getPermission()));
        mav.addObject("result", true);
    } else {
        mav.addObject("result", false);
    }
    return mav;
}

From source file:com.orangeleap.webtools.controller.json.LogoutController.java

@RequestMapping("/logout.json")
public void logout(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    final String guid = request.getParameter("guid");

    final String sessionId = request.getParameter("sessionId");

    if (StringUtils.isNotBlank(sessionId)) {
        final Cookie sessionCookies[] = request.getCookies();
        Cookie sessionCookie = null;/*w w w  .  java  2s .c  o  m*/

        for (final Cookie aCookie : sessionCookies) {
            if (aCookie.getName().equals("sessionId")) {
                aCookie.setMaxAge(0);
                aCookie.setValue("");
                sessionCookie = aCookie;
                break;
            }
        }
        if (sessionCookie == null) {
            sessionCookie = new Cookie("sessionId", "");
        }
        response.addCookie(sessionCookie);
        sessionCache.remove(sessionId);
    }

    final Widget widget = widgetService.getWidget(guid);
    final String authenticationUrl = widget.getWidgetAuthenticationURL();

    response.sendRedirect(authenticationUrl);
}

From source file:org.tonguetied.web.CookieUtilsTest.java

/**
 * Test method for {@link org.tonguetied.web.CookieUtils#getCookie(HttpServletRequest, String)}.
 *///w ww  . java2  s . c o m
@Test
public final void testGetCookieWhenCookieDoesNotExist() {
    Cookie[] cookies = new Cookie[] { new Cookie("name", "value") };
    request.setCookies(cookies);
    Cookie cookie = CookieUtils.getCookie(request, "name2");
    assertNull(cookie);
}

From source file:io.cfp.auth.MainCtrl.java

@RequestMapping("/")
public String main(HttpServletResponse response, @CookieValue(required = false) String token,
        @RequestParam(required = false, value = "target") String targetParam,
        @CookieValue(required = false) String returnTo,
        @RequestHeader(required = false, value = REFERER) String referer) {
    response.setHeader(CACHE_CONTROL, "no-cache,no-store,must-revalidate");
    response.setHeader(PRAGMA, "no-cache");
    response.setDateHeader(EXPIRES, 0);/*  w  w w .  j a va  2s . com*/

    String target = "http://www.cfp.io";
    if (targetParam != null) {
        target = targetParam;
    } else if (returnTo != null) {
        target = returnTo;
    } else if (referer != null) {
        target = referer;
    }

    response.addCookie(new Cookie("returnTo", target));

    if (token == null || !tokenSrv.isValid(token)) {
        return "login";
    }

    // token is valid
    return "redirect:" + target;
}

From source file:com.usefullc.platform.common.utils.CookieUtils.java

/**
 * cookie/*from   w  w  w .  j ava  2 s. co m*/
 * 
 * @param request
 * @param response
 * @param name
 */
public static void remove(String name, String domain) {
    Cookie cookie = new Cookie(name, "");
    cookie.setPath("/");
    cookie.setMaxAge(0);
    cookie.setDomain(domain);
    HttpServletResponse response = ServeltContextManager.getResponse();
    response.addCookie(cookie);
}

From source file:ke.alphacba.cms.core.util.NoSessionIdUtils.java

private static void writeCookie(HttpServletResponse response, String loginCookieName, String domain,
        int cookieTime, String jsessionId, boolean httpOnly) {

    String cookieValue = new String(Base64.encodeBase64(new StringBuilder().append(loginCookieName)
            .append(new Date().getTime()).append(jsessionId).toString().getBytes()));
    Cookie cookie1 = new Cookie(loginCookieName, cookieValue);
    cookie1.setHttpOnly(true);// ww w .  ja  va2 s  . co  m
    cookie1.setMaxAge(cookieTime);
    cookie1.setPath("/");
    cookie1.setDomain(domain);
    response.addCookie(cookie1);
}

From source file:com.xwiki.authentication.sts.XWikiSTSAuthenticatorTest.java

@SuppressWarnings("deprecation")
@Before//from   www .j a v  a2  s  .  co  m
public void setUp() throws Exception {
    Utils.setComponentManager(getComponentManager());
    Cookie cookie = new Cookie("username", "student");
    wiki = mock(XWiki.class);
    context = mock(XWikiContext.class);
    XWikiRequest request = mock(XWikiRequest.class);
    HttpSession session = mock(HttpSession.class);
    XWikiDocument doc = mock(XWikiDocument.class);
    BaseObject baseObj = mock(BaseObject.class);
    BaseProperty baseProp = mock(BaseProperty.class);

    XWikiSTSAuthenticatorProperties props = new XWikiSTSAuthenticatorProperties();
    auth = new XWikiSTSAuthenticator();

    when(context.getRequest()).thenReturn(request);
    when(request.getCookie(any(String.class))).thenReturn(cookie);
    when(request.getHttpServletRequest()).thenReturn(request);
    when(request.getSession(true)).thenReturn(session);
    when(request.getSession()).thenReturn(session);

    XWikiResponse response = mock(XWikiResponse.class);
    when(context.getResponse()).thenReturn(response);

    when(session.getAttribute("sts_user")).thenReturn("123123-12345");
    when(context.getWiki()).thenReturn(wiki);
    when(wiki.Param("xwiki.authentication.sts.auth_field")).thenReturn("sts_user");
    when(wiki.Param("xwiki.authentication.sts.stsauthclass_id_field")).thenReturn("nameid");
    when(wiki.exists(anyString(), (XWikiContext) anyObject())).thenReturn(false, true);
    List<Object> xwikilist0 = new ArrayList<Object>(0);
    List<Object> xwikilist1 = new ArrayList<Object>(1);
    // xwikilist1.add("ValdisVitolins");

    when(wiki.search(anyString(), (XWikiContext) anyObject())).thenReturn(xwikilist0, xwikilist1);

    when(wiki.getDocument(anyString(), (XWikiContext) anyObject())).thenReturn(doc);

    when(wiki.Param("xwiki.authentication.sts.wreply_host")).thenReturn("aha");
    when(wiki.Param("xwiki.authentication.sts.wreply_page")).thenReturn("1");
    // when(
    // wiki.Param(matches("(.*id.*|subject|issuer|entity|reply|url|uri)")))
    // .thenReturn("0");

    when(doc.getObject(anyString(), anyInt())).thenReturn(baseObj);
    when(doc.getObject(anyString())).thenReturn(baseObj);
    when(doc.newObject(anyString(), (XWikiContext) anyObject())).thenReturn(baseObj);

    when(baseObj.get(anyString())).thenReturn(baseProp);
    when(baseProp.getValue()).thenReturn("propValue");

    when(wiki.getUniquePageName(anyString(), anyString(), (XWikiContext) anyObject()))
            .thenReturn("ValdisVitolins");

    File testFile = new File("testToken.xml");
    String testToken = FileUtils.readFileToString(testFile);
    when(request.getParameter("wresult")).thenReturn(testToken);
    when(request.getParameter(anyString())).thenReturn("1");
    when(props.getFieldMapping(context)).thenReturn("first_name=givenname,last_name=surname");
    when(props.getUsernameRule(context)).thenReturn("first_name,last_name");
    when(props.getWct(context)).thenReturn("1", "0");
    when(props.getWctx(context)).thenReturn("1", "0");
    when(props.getWfresh(context)).thenReturn("1");

}

From source file:org.apache.oltu.oauth2.client.demo.controller.AuthzController.java

@RequestMapping("/authorize")
public ModelAndView authorize(@ModelAttribute("oauthParams") OAuthParams oauthParams, HttpServletRequest req,
        HttpServletResponse res) throws OAuthSystemException, IOException {

    try {//from   w ww  .  j a  va 2s  . c  o m
        Utils.validateAuthorizationParams(oauthParams);

        res.addCookie(new Cookie("clientId", oauthParams.getClientId()));
        res.addCookie(new Cookie("clientSecret", oauthParams.getClientSecret()));
        res.addCookie(new Cookie("authzEndpoint", oauthParams.getAuthzEndpoint()));
        res.addCookie(new Cookie("tokenEndpoint", oauthParams.getTokenEndpoint()));
        res.addCookie(new Cookie("redirectUri", oauthParams.getRedirectUri()));
        res.addCookie(new Cookie("scope", oauthParams.getScope()));
        res.addCookie(new Cookie("state", oauthParams.getState()));
        res.addCookie(new Cookie("app", oauthParams.getApplication()));

        OAuthClientRequest request = OAuthClientRequest.authorizationLocation(oauthParams.getAuthzEndpoint())
                .setClientId(oauthParams.getClientId()).setRedirectURI(oauthParams.getRedirectUri())
                .setResponseType(ResponseType.CODE.toString()).setScope(oauthParams.getScope())
                .setState(oauthParams.getState()).buildQueryMessage();

        return new ModelAndView(new RedirectView(request.getLocationUri()));
    } catch (ApplicationException e) {
        oauthParams.setErrorMessage(e.getMessage());
        return new ModelAndView("get_authz");
    }
}