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.test.servlet.LoginController.java

@Override
public void setResponse(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter writer = response.getWriter();
    String email = getParam(RequestParam.email.toString());
    String password = getParam(RequestParam.password.toString());
    if (Utility.isStringEmpty(email)) {
        writer.print(/*w ww .  j  a  v  a2  s  .  com*/
                Utility.generalErrorMessage(ResponseCode.email_not_provided.toString(), "Email is required!"));
        return;
    }
    if (Utility.isStringEmpty(password)) {
        writer.print(Utility.generalErrorMessage(ResponseCode.password_not_provided.toString(),
                "Password is required!"));
        return;
    }

    DBUtility dbUtil = new DBUtility(servlet);
    User user = dbUtil.getUser(email, password);
    if (user != null) {
        HttpSession session = request.getSession();
        session.setAttribute("user_id", user.getId());
        String sessionKey = SessionGenerator.getInstance().nextSessionId();
        Cookie cookie = new Cookie("auth_key", sessionKey);
        cookie.setMaxAge(Constants.COOKIE_AGE);
        response.addCookie(cookie);

        dbUtil.insertSession(sessionKey, user.getId());

        JSONObject jResponse = new JSONObject();
        jResponse.put(JSONKey.status.toString(), 0);
        //jResponse.put(JSONKey.auth_key.toString(), sessionKey);
        jResponse.put(JSONKey.user_info.toString(), user.toJSONObject());

        writer.print(jResponse.toString());
    } else {
        writer.print(Utility.generalErrorMessage(ResponseCode.email_doesnt_exist.toString(),
                "Email address not found"));
    }
}

From source file:architecture.ee.web.util.CookieUtils.java

public static void setCookie(HttpServletRequest request, HttpServletResponse response, String name,
        String value, int maxAge) {
    if (value == null)
        value = "";
    String path = request.getContextPath() != null ? request.getContextPath() : "/";
    if ("".equals(path))
        path = "/";
    Cookie cookie = new Cookie(name, value);
    cookie.setMaxAge(maxAge);/*from  ww  w  .ja  v  a 2  s  .  com*/
    cookie.setPath(path);
    response.addCookie(cookie);
}

From source file:es.logongas.ix3.web.security.impl.WebSessionSidStorageImplAbstractJws.java

@Override
public void setSid(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
        Serializable sid) {/*from  w  w w  .  j a  v  a2 s.  c o  m*/
    String payload = serialize(sid);

    String jwsCompact = jws.getJwsCompactSerialization(payload, getSecretKey(sid));
    Cookie cookie = new Cookie(jwsCookieName, jwsCompact);
    cookie.setHttpOnly(false);
    cookie.setPath(httpServletRequest.getContextPath() + "/");
    httpServletResponse.addCookie(cookie);
}

From source file:au.gov.dto.dibp.appointments.security.csrf.CookieBasedCsrfTokenRepository.java

@Override
public void saveToken(CsrfToken token, HttpServletRequest request, HttpServletResponse response) {
    Cookie csrfCookie;/*from   w w w  .  j av  a  2  s  .c om*/
    if (token == null) {
        csrfCookie = new Cookie(CSRF_COOKIE_AND_PARAMETER_NAME, "");
        csrfCookie.setMaxAge(0);
    } else {
        csrfCookie = new Cookie(token.getParameterName(), token.getToken());
        csrfCookie.setMaxAge(COOKIE_MAX_AGE_SECONDS);
    }
    csrfCookie.setHttpOnly(true);
    csrfCookie.setSecure(request.isSecure());
    response.addCookie(csrfCookie);
}

From source file:org.osmsurround.ae.oauth.OauthCookieService.java

private Cookie createOneYearCookie(String name, String value) {
    Cookie cookie = new Cookie(name, value);
    cookie.setMaxAge(60 * 60 * 24 * 365);
    return cookie;
}

From source file:net.prasenjit.auth.config.CsrfCookieGeneratorFilter.java

/**
 * {@inheritDoc}/*from www . java 2s  . c  om*/
 */
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {
    // Spring put the CSRF token in session attribute "_csrf"
    CsrfToken csrfToken = (CsrfToken) request.getAttribute("_csrf");

    // Send the cookie only if the token has changed
    String actualToken = request.getHeader("X-XSRF-TOKEN");
    if (actualToken == null || !actualToken.equals(csrfToken.getToken())) {
        // Session cookie that will be used by AngularJS
        String pCookieName = "XSRF-TOKEN";
        Cookie cookie = new Cookie(pCookieName, csrfToken.getToken());
        cookie.setMaxAge(-1);
        cookie.setHttpOnly(false);
        cookie.setPath("/");
        response.addCookie(cookie);
    }
    filterChain.doFilter(request, response);
}

From source file:CookieUtils.java

/**
 * Adds a cookie with the specified name, value and expiry.
 *
 * @param response    the HttpServletResponse to add the cookie to
 * @param name        the name of the cookie
 * @param value       the value of the cookie
 * @param maxAge      the maxAge of the cookie (in seconds)
 *//* w  ww . j av  a2s. com*/
public static void addCookie(HttpServletResponse response, String name, String value, int maxAge) {
    Cookie cookie = new Cookie(name, value);
    cookie.setMaxAge(maxAge);
    response.addCookie(cookie);
}

From source file:com.google.youtube.captions.AuthSubLogout.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String username = Util.getCookie(req, Util.CURRENT_USERNAME);

    if (!Util.isEmptyOrNull(username)) {
        try {/*ww w  .ja va 2s  .  c o  m*/
            String authSubCookie = Util.getCookie(req, Util.AUTH_SUB_COOKIE);
            JSONObject cookieAsJSON = new JSONObject(authSubCookie);

            if (cookieAsJSON.has(username)) {
                String authSubToken = cookieAsJSON.getString(username);

                AuthSubUtil.revokeToken(authSubToken, null);

                cookieAsJSON.remove(username);

                Cookie cookie = new Cookie(Util.AUTH_SUB_COOKIE, cookieAsJSON.toString());
                cookie.setMaxAge(Util.COOKIE_LIFETIME);
                resp.addCookie(cookie);

                cookie = new Cookie(Util.CURRENT_AUTHSUB_TOKEN, "");
                cookie.setMaxAge(Util.COOKIE_LIFETIME);
                resp.addCookie(cookie);

                cookie = new Cookie(Util.CURRENT_USERNAME, "");
                cookie.setMaxAge(Util.COOKIE_LIFETIME);
                resp.addCookie(cookie);
            }
        } catch (AuthenticationException e) {
            LOG.log(Level.WARNING, "", e);
        } catch (GeneralSecurityException e) {
            LOG.log(Level.WARNING, "", e);
        } catch (JSONException e) {
            LOG.log(Level.WARNING, "", e);
        }
    }

    resp.sendRedirect("/");
}

From source file:cec.easyshop.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  w w  w . 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)));
    assertNoHeaderAdjustments();
}

From source file:csns.web.controller.IndexController.java

@RequestMapping({ "/department/{dept}/", "/department/{dept}" })
public String index(@PathVariable String dept, ModelMap models, HttpServletResponse response) {
    Department department = departmentDao.getDepartment(dept);
    if (department == null)
        return "redirect:/";

    Cookie cookie = new Cookie("default-dept", dept);
    cookie.setPath("/");
    cookie.setMaxAge(100000000);//from ww  w .j  a v  a2s .  c  o  m
    response.addCookie(cookie);

    models.addAttribute("department", department);
    models.addAttribute("newses", newsDao.getNews(department));
    return "department/index";
}