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:org.piraso.web.base.PirasoFilterTest.java

@Before
public void setUp() throws Exception {
    registry = spy(new DefaultUserRegistryImpl());
    request = CommonMockObjects.mockRequest(MONITORED_ADDR);
    response = spy(new MockHttpServletResponse());
    chain = spy(new MockFilterChain());

    request.setCookies(new Cookie("name", "value"));
    request.addParameter("name", "value");
    request.addHeader("name", "value");

    filter = new PirasoFilter();
    LoggerRegistrySingleton.INSTANCE.setRegistry(registry);
}

From source file:org.alfresco.web.app.servlet.LanguageCookieFilter.java

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {

    String lang = null;/*ww w . ja va 2  s . c  o  m*/
    // check if parameter "mllang" is there
    String mlLang = servletRequest.getParameter("mllang");
    String mlLangContent = servletRequest.getParameter("mllangcontent");
    dumpCookies(servletRequest);
    String locale = positionCookie(servletRequest, servletResponse, mlLang, MLPREF, false);

    if (mlLangContent != null && mlLangContent.equals("reset")) {
        Cookie mlpref = new Cookie(MLPREFCONTENT, ""); // Set expiry date after 24 Hrs forboth the cookies. 
        mlpref.setMaxAge(0);
        ((HttpServletResponse) servletResponse).addCookie(mlpref);
        I18NUtil.setContentLocale(null);
    } else {
        positionCookie(servletRequest, servletResponse, mlLangContent, MLPREFCONTENT, true);
    }
    // create the NullFakeHeaderRequest so WebscriptServlet does not modify
    // the request again.
    // recuperate the lang
    if (locale == null) {
        // default it to "en"
        locale = "en";
    }
    NullFakeHeaderRequest request = new NullFakeHeaderRequest((HttpServletRequest) servletRequest, locale);
    filterChain.doFilter(request, servletResponse);

    return;
}

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

@Test
public void testCookieNoValue() throws InvalidCookieException {
    Cookie cookie = new Cookie("JSESSIONID", "");
    cookie.setPath("/");
    CookieFormatter formatter = CookieFormatter.createFromServletCookie(cookie);
    Assert.assertEquals("JSESSIONID=; path=/;", formatter.asString());
}

From source file:com.balero.controllers.LogoutController.java

/**
 * Simple. Set cookie's content to 'init'
 * init equals to empty or null/*from w  w  w.  j a v  a 2 s.  c  o  m*/
 *
 * @param response HTTP headers
 * @param redirectAttributes Show in message center
 * @return View
 */
@RequestMapping(method = RequestMethod.GET)
public String logout(HttpServletResponse response, RedirectAttributes redirectAttributes) {

    // create cookie and set it in response
    Cookie cookie = new Cookie("baleroAdmin", "init");
    response.addCookie(cookie);

    /**
     * Base on:
     * stackoverflow.com/questions/19249049/
     * how-to-pass-parameters-
     * to-redirect-page-in-spring-mvc
     */
    ResourceBundle bundle = ResourceBundle.getBundle("messages");
    redirectAttributes.addFlashAttribute("message", bundle.getString("label.login.logout"));

    return "redirect:/";

}

From source file:Controladores.ControladorLogin.java

@RequestMapping("efetua-login")
public ModelAndView efetuaLogin(String usuario, String senha, boolean ckSalvaLogin, HttpSession sessao,
        HttpServletResponse response) {/*  ww w.  ja va  2 s.  co m*/

    ModelAndView mv;

    Funcionario f = DAO.Model.FuncionarioDAO.autenticacaoLogin(usuario, senha);

    if (f != null) {

        if (ckSalvaLogin) {
            Cookie c = new Cookie("loginCookie", usuario);
            c.setMaxAge(60); // em segundos
            response.addCookie(c);

            c = new Cookie("senhaCookie", senha);
            c.setMaxAge(60); // em segundos
            response.addCookie(c);
        }

        sessao.setAttribute("logado", true);
        sessao.setAttribute("funcionario", f);

        if (sessao.getAttribute("endereco") == null) {
            mv = new ModelAndView("redirect:index");
        } else {
            String endereco = sessao.getAttribute("endereco").toString();
            endereco = endereco.substring(endereco.lastIndexOf("/") + 1);
            mv = new ModelAndView("redirect:" + endereco);
        }

        sessao.removeAttribute("endereco");
    } else {
        sessao.setAttribute("logado", false);
        mv = new ModelAndView("redirect:exibe-login");
    }
    return mv;
}

From source file:uk.co.caprica.bootlace.security.web.filter.AngularJsCsrfHeaderFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {
    logger.debug("doFilterInternal()");
    CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
    if (csrf != null) {
        Cookie cookie = WebUtils.getCookie(request, CSRF_COOKIE_NAME);
        String token = csrf.getToken();
        if (cookie == null || token != null && !token.equals(cookie.getValue())) {
            logger.debug("Setting new CSRF cookie");
            cookie = new Cookie(CSRF_COOKIE_NAME, token);
            cookie.setPath(request.getServletContext().getContextPath() + "/");
            response.addCookie(cookie);//from w  w w . j a  va2 s  .c  om
        }
    }
    filterChain.doFilter(request, response);
}

From source file:fr.gael.dhus.spring.security.handler.LoginSuccessHandler.java

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) {
    String name = authentication.getName();
    try {/*from ww w  . ja  v a 2s  . c om*/
        ValidityAuthentication auth = (ValidityAuthentication) authentication;

        name = EncryptPassword.encrypt(name, PasswordEncryption.MD5);
        Cookie authCookie = new Cookie(CookieKey.AUTHENTICATION_COOKIE_NAME, name);
        authCookie.setPath("/");
        authCookie.setHttpOnly(true);
        authCookie.setMaxAge(-1);

        String validity = auth.getValidity();
        //         Cookie validityCookie = new Cookie (CookieKey.VALIDITY_COOKIE_NAME,
        //             validity);
        //         validityCookie.setPath ("/");
        //         validityCookie.setHttpOnly (true);

        String integrity = EncryptPassword.encrypt(name + validity, PasswordEncryption.SHA1);
        Cookie integrityCookie = new Cookie(CookieKey.INTEGRITY_COOKIE_NAME, integrity);
        integrityCookie.setPath("/");
        integrityCookie.setHttpOnly(true);
        integrityCookie.setMaxAge(-1);

        response.addCookie(authCookie);
        //         response.addCookie (validityCookie);
        response.addCookie(integrityCookie);
        request.getSession().setAttribute("integrity", integrity);
        SecurityContextProvider.saveSecurityContext(integrity, SecurityContextHolder.getContext());
    } catch (Exception e) {
        LOGGER.warn("Authentication process failed ! No cookie was generated", e);
    }
}

From source file:com.leixl.easyframework.web.CookieUtils.java

/**
 * ?cookie/*w w w .ja  va2  s  . c o m*/
 * 
 * @param request
 * @param response
 * @param name
 * @param domain
 */
public static void cancleCookie(HttpServletRequest request, HttpServletResponse response, String name,
        String domain) {
    Cookie cookie = new Cookie(name, "");
    cookie.setMaxAge(0);
    String ctx = request.getContextPath();
    cookie.setPath(StringUtils.isBlank(ctx) ? "/" : ctx);
    if (StringUtils.isNotBlank(domain)) {
        cookie.setDomain(domain);
    }
    response.addCookie(cookie);
}

From source file:com.pureinfo.tgirls.sns.servlet.TestSNSEntryServlet.java

@Override
protected void doPost(HttpServletRequest _req, HttpServletResponse _resp) throws ServletException, IOException {
    System.out.println("==================test entry=====POST==============");

    try {//ww w  . j a v a  2  s.  com
        String userId = _req.getParameter("id");
        if (StringUtils.isEmpty(userId)) {
            userId = "1";
        }

        System.out.println("----user id----" + userId);

        IUserMgr mgr = (IUserMgr) ArkContentHelper.getContentMgrOf(User.class);
        User u = mgr.getUserByTaobaoId(userId);

        System.out.println("user:::;" + u);

        addCookie(u, _req, _resp);

        Cookie[] cookies = _req.getCookies();

        if (cookies == null) {
            System.out.println("=====cookie is null=======");
        } else {
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                System.out.println("cookie[" + i + "]:[" + cookie.getName() + ":" + cookie.getValue() + "("
                        + cookie.getMaxAge() + ")]");
            }

        }

        int i = new Random().nextInt();
        Cookie c = new Cookie("topsessionid", "abc" + i);

        _resp.addCookie(c);

        System.out.println("========================");

        //            Cookie[] cs = _req.getCookies();
        //             for (int ii = 0; ii < cs.length; ii++) {
        //                 Cookie cc = cs[ii];
        //                 System.out.println("cookie[" + cc.getName() + "]:" + cc.getValue());
        //             }

        //_resp.sendRedirect(_req.getContextPath() + "/index.html");

        RequestDispatcher rd = _req.getRequestDispatcher("/index.html");
        rd.forward(_req, _resp);

        //_req.getSession().setAttribute(ArkHelper.ATTR_LOGIN_USER, u);
        // _resp.sendRedirect(_req.getContextPath());
        //            _req.getCookies()[0].
    } catch (PureException e) {
        // TODO Auto-generated catch block
        e.printStackTrace(System.err);
    }

}

From source file:com.aurel.track.master.ModuleBL.java

public static Cookie sendPOSTRequest(String urlString) {
    Cookie responseCookie = null;//from   w  w w. j  a  v  a 2s  .com
    try {
        HttpClient httpclient = new DefaultHttpClient();//HttpClients.createDefault();
        HttpPost httppost = new HttpPost(urlString);
        // Request parameters and other properties.
        //Execute and get the response.
        HttpContext localContext = new BasicHttpContext();
        CookieStore cookieStore = new BasicCookieStore();
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
        HttpResponse response = httpclient.execute(httppost, localContext);

        if (cookieStore.getCookies().size() > 0) {
            List<org.apache.http.cookie.Cookie> cookies = cookieStore.getCookies();
            for (org.apache.http.cookie.Cookie cookie : cookies) {
                if (cookie.getName().equals("JSESSIONID")) {
                    responseCookie = new Cookie(cookie.getName(), cookie.getValue());
                    responseCookie.setPath(cookie.getPath());
                    responseCookie.setDomain(cookie.getDomain());
                }
            }
        }
        if (response.getEntity() != null) {
            response.getEntity().consumeContent();
        }

    } catch (Exception ex) {
        LOGGER.debug(ExceptionUtils.getStackTrace(ex));
    }
    return responseCookie;
}