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.acc.storefront.security.cookie.EnhancedCookieGeneratorTest.java

@Test
public void testClientSideCookieDefaultPath() {
    cookieGenerator.setCookieName(JSESSIONID);
    cookieGenerator.setHttpOnly(false);//client side

    cookieGenerator.addCookie(response, "cookie_monster");

    final Cookie expectedCookie = new Cookie(JSESSIONID, "cookie_monster");
    expectedCookie.setPath("/");
    expectedCookie.setSecure(false);/*from  www  .  j  ava2s . c  o m*/
    expectedCookie.setMaxAge(NEVER_EXPIRES);
    expectedCookie.setDomain("what a domain");

    Mockito.verify(response).addCookie(Mockito.argThat(new CookieArgumentMatcher(expectedCookie)));
    assertNoHeaderAdjustments();

}

From source file:au.gov.dto.springframework.security.web.csrf.CookieCsrfTokenRepository.java

@Override
public void saveToken(CsrfToken token, HttpServletRequest request, HttpServletResponse response) {
    Cookie csrfCookie;/*  w  w w.ja  va2s  . c  om*/
    if (token == null) {
        csrfCookie = new Cookie(csrfCookieName, "");
        csrfCookie.setMaxAge(0);
    } else {
        csrfCookie = new Cookie(csrfCookieName, token.getToken());
        csrfCookie.setMaxAge(csrfCookieMaxAgeSeconds);
    }
    csrfCookie.setHttpOnly(true);
    csrfCookie.setSecure(request.isSecure());
    csrfCookie.setPath(csrfCookiePath);
    response.addCookie(csrfCookie);
}

From source file:hudson.plugins.codeviation.JavaFileIterableView.java

public static void updateGraphType(StaplerRequest req, StaplerResponse rsp) {
    chartType = req.getParameter(CHART_TYPE_PARAM);
    Enumeration en = req.getParameterNames();
    while (en.hasMoreElements()) {
        System.out.println(en.nextElement());
    }/*from  w  w w.  j av  a2 s  . c om*/
    if (chartType != null) {
        rsp.addCookie(new Cookie(CHART_TYPE_PARAM, chartType));
    }

}

From source file:com.woonoz.proxy.servlet.CookieFormatterTest.java

@Test
public void testCookieNoPath() throws InvalidCookieException {
    String sessionId = "JJJ2234312421";
    Cookie cookie = new Cookie("JSESSIONID", sessionId);
    CookieFormatter formatter = CookieFormatter.createFromServletCookie(cookie);
    Assert.assertEquals("JSESSIONID=JJJ2234312421;", formatter.asString());
}

From source file:com.codename1.corsproxy.CORSProxy.java

@Override
protected void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
        Header header) {//from   ww w  .  j a v  a2  s .c  o  m
    List<HttpCookie> cookies = HttpCookie.parse(header.getValue());
    String path = servletRequest.getContextPath(); // path starts with / or is empty string
    path += servletRequest.getServletPath(); // servlet path starts with / or is empty string

    for (HttpCookie cookie : cookies) {
        //set cookie name prefixed w/ a proxy value so it won't collide w/ other cookies
        String proxyCookieName = getCookieNamePrefix() + cookie.getName();
        Cookie servletCookie = new Cookie(proxyCookieName, cookie.getValue());
        servletCookie.setComment(cookie.getComment());
        servletCookie.setMaxAge((int) cookie.getMaxAge());
        servletCookie.setPath(path); //set to the path of the proxy servlet
        // don't set cookie domain
        //servletCookie.setSecure(cookie.getSecure());
        servletCookie.setSecure(false);
        servletCookie.setVersion(cookie.getVersion());
        servletResponse.addCookie(servletCookie);
    }
}

From source file:com.redhat.rhn.frontend.servlets.PxtCookieManager.java

/**
 * Creates a new pxt cookie with the specified session id and timeout.
 *
 * @param pxtSessionId The id of the pxt session for which the cookie is being created.
 *
 * @param request The current request./*  w ww .ja  v a  2  s  .c o m*/
 *
 * @param timeout The max age of the cookie in seconds.
 *
 * @return a new pxt cookie.
 */
public Cookie createPxtCookie(Long pxtSessionId, HttpServletRequest request, int timeout) {

    String cookieName = getCookieName(request);
    String cookieValue = pxtSessionId + "x" + SessionManager.generateSessionKey(pxtSessionId.toString());

    Cookie pxtCookie = new Cookie(cookieName, cookieValue);
    // BZ #454876
    // when not using setDomain, default "Host" will be set for the cookie
    // there's no need to use domain and besides that it causes trouble,
    //  when accessing the server within the local network (without FQDN)
    // pxtCookie.setDomain(request.getServerName());
    pxtCookie.setMaxAge(timeout);
    pxtCookie.setPath(DEFAULT_PATH);
    pxtCookie.setSecure(ConfigDefaults.get().isSSLAvailable());

    return pxtCookie;
}

From source file:controllers.Parent_Controller.java

public Cookie set_Cookie(String name, String value, int ttl) {
    Cookie cookie = new Cookie(name, value);
    cookie.setMaxAge(ttl * 60 * 60);/*  w  w  w  .j a va 2  s . co  m*/
    return cookie;
    //response.addCookie(cookie); 
}

From source file:net.anthonychaves.bookmarks.web.PersistentLoginFilter.java

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

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    Cookie tokenCookie = getCookieByName(httpRequest.getCookies(), "loginToken");

    HttpSession session = httpRequest.getSession();
    User user = (User) session.getAttribute("user");

    if (user == null && tokenCookie != null) {
        user = tokenService.loginWithToken(tokenCookie.getValue());
        String tokenValue = tokenService.setupNewLoginToken(user);

        httpRequest.getSession().setAttribute("user", user);
        tokenCookie.setMaxAge(0);//from w ww  .  j ava 2s  .  co  m
        httpResponse.addCookie(tokenCookie);

        tokenCookie = new Cookie("loginToken", tokenValue);
        tokenCookie.setPath("/bookmarks");
        tokenCookie.setMaxAge(168 * 60 * 60);
        httpResponse.addCookie(tokenCookie);
    }

    chain.doFilter(httpRequest, httpResponse);
}

From source file:net.smartam.leeloo.controller.AuthzController.java

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

    try {// w  w w.  java  2s  .c om

        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("app", oauthParams.getApplication()));

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

        return new ModelAndView(new RedirectView(request.getLocationUri()));

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

From source file:com.snowy.Login.java

@PostConstruct
void init() {/*  w ww .  j a v a 2  s  .  c  o  m*/
    d = ((MyVaadinUI) UI.getCurrent()).getDataObject();
    //Logger.getLogger(Login.class.getName()).info(d);
    this.setSizeFull();
    this.setSpacing(false);
    this.setMargin(true);
    Label MainL = new Label("<h1>Connect 4</h1?>", ContentMode.HTML);
    //layout.addComponent(MainL);
    MainL.setSizeUndefined();
    VerticalLayout lay = new VerticalLayout();
    lay.setMargin(false);
    lay.addComponent(MainL);
    lay.setComponentAlignment(MainL, Alignment.TOP_CENTER);
    HorizontalLayout hz = new HorizontalLayout();
    hz.setMargin(false);
    hz.setSpacing(false);
    LoginForm lf = new LoginForm();
    lf.addLoginListener((e) -> {
        String token = d.genToken(e.getLoginParameter("username"), e.getLoginParameter("password"));
        //String token="true";
        if (!token.equals("false")) {

            Cookie c = new Cookie("token", token);
            VaadinService.getCurrentResponse().addCookie(c);
            //https://vaadin.com/wiki/-/wiki/Main/Setting+and+reading+Cookies
            //Notification.show(VaadinService.getCurrentRequest().getCookies()[1].getValue(),Notification.Type.ERROR_MESSAGE);
            //this.getNavigator().navigateTo("main");
            //this.getUI().get
            this.getUI().getNavigator().navigateTo("main");
        } else {
            Label l = new Label("<h4 style=\"color:red\">Invalid Username or Password</h4>", ContentMode.HTML);
            l.setId("created");

            if (lay.getComponent(lay.getComponentIndex(lf) + 1).getId() == null) {
                //lay.addComponent(new Label(String.valueOf(lay.getComponentIndex(l))));
                lay.addComponent(l, lay.getComponentIndex(lf) + 1);
                l.setSizeUndefined();
                lay.setComponentAlignment(l, Alignment.TOP_CENTER);
            }

        }

    });

    lay.addComponent(lf);
    Button newUser = new Button("New User");
    newUser.addClickListener((e) -> {

        this.getUI().addWindow(new NewUserSubWindow(d));
    });
    //newUser.setWidth((float)5.5, Unit.EM);
    Button forgotPass = new Button("Forgot Password");
    //temp
    forgotPass.addClickListener((e) -> {
        //Notification.show(, Notification.Type.ERROR_MESSAGE);
    });
    forgotPass.setEnabled(false);
    forgotPass.setDescription("Feature Disabled, Contact Administrator for Assistance");
    //forgotPass.setWidth((float) 8.5,Unit.EM);
    forgotPass.setStyleName(ValoTheme.BUTTON_LINK);
    newUser.setStyleName(ValoTheme.BUTTON_LINK);

    hz.addComponent(newUser);
    hz.addComponent(forgotPass);
    lay.addComponent(hz);
    lay.setComponentAlignment(lf, Alignment.TOP_CENTER);
    lay.setComponentAlignment(hz, Alignment.MIDDLE_CENTER);
    this.addComponent(lay);
    this.setComponentAlignment(lay, Alignment.MIDDLE_CENTER);
}