Example usage for javax.servlet.http HttpServletResponse addCookie

List of usage examples for javax.servlet.http HttpServletResponse addCookie

Introduction

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

Prototype

public void addCookie(Cookie cookie);

Source Link

Document

Adds the specified cookie to the response.

Usage

From source file:com.persistent.cloudninja.controller.LogoutFilter.java

private void removeCookie(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
        String authCookieName) {/*from ww w .j a  v  a 2  s  .  co  m*/

    Cookie[] cookies = httpServletRequest.getCookies();
    Cookie currentCookie = null;

    if (cookies != null && cookies.length > 0) {
        for (Cookie c : cookies) {
            if (authCookieName.equals(c.getName())) {
                currentCookie = c;
                currentCookie.setMaxAge(0);
                currentCookie.setValue("");
                currentCookie.setPath("/");

                httpServletResponse.addCookie(currentCookie);
            }

        }
    }

}

From source file:com.ctc.storefront.controllers.misc.AddToCartController.java

private void setCookie(final HttpServletResponse response, final CartData cartData) {
    final Cookie cookie = new Cookie("cartQuantity", String.valueOf(cartData.getTotalUnitCount()));
    cookie.setMaxAge(60 * 60);/*from   ww w  .j a va2  s . c  o m*/
    cookie.setPath("/");
    cookie.setDomain(siteConfigService.getString(CART_COUNT_COOKIE_DOMAIN_NAME, ".ctc.com"));
    response.addCookie(cookie);
}

From source file:net.longfalcon.web.BaseController.java

protected void setCookies(User user, HttpServletResponse httpServletResponse) {
    long userId = user.getId();
    String idh = EncodingUtil.sha1Hash(user.getUserseed() + String.valueOf(userId));
    Cookie uidCookie = new Cookie("uid", String.valueOf(userId));
    uidCookie.setMaxAge(2592000);// w ww  .j ava 2  s .c om
    Cookie idhCookie = new Cookie("idh", idh);
    idhCookie.setMaxAge(2592000);
    httpServletResponse.addCookie(uidCookie);
    httpServletResponse.addCookie(idhCookie);
}

From source file:org.mascherl.session.MascherlSessionStorage.java

public void saveSession(MascherlSession session, HttpServletResponse response) {
    if (!session.wasModified()) {
        return; // no need to update an unmodified session
    }//from w  ww .j a va  2  s  .c om

    String data = session.serialize();
    if (data.length() > MAX_DATA_SIZE) {
        throw new IllegalStateException("Session data exceeds limit");
    }

    String encryptedValue = cryptoHelper.encryptAES(data);

    Cookie cookie = new Cookie(cookieName, encryptedValue);
    cookie.setMaxAge(EXPIRE_ON_BROWSER_CLOSE);
    response.addCookie(cookie);
}

From source file:com.googlesource.gerrit.plugins.github.oauth.GitHubLogin.java

private String getScopesKey(HttpServletRequest request, HttpServletResponse response) {
    String scopeRequested = request.getParameter("scope");
    if (scopeRequested == null) {
        scopeRequested = getScopesKeyFromCookie(request);
    }/*  ww w  .j  a v a  2  s .  c  o m*/

    if (scopeRequested != null) {
        Cookie scopeCookie = new Cookie("scope", scopeRequested);
        scopeCookie.setPath("/");
        scopeCookie.setMaxAge((int) SCOPE_COOKIE_NEVER_EXPIRES);
        response.addCookie(scopeCookie);
    }

    return Objects.firstNonNull(scopeRequested, "scopes");
}

From source file:com.nominanuda.web.http.ServletHelper.java

public void copyResponse(HttpResponse response, HttpServletResponse servletResponse) throws IOException {
    servletResponse.setStatus(response.getStatusLine().getStatusCode());
    for (Header h : response.getAllHeaders()) {
        if ("Set-Cookie".equals(h.getName()) || "Set-Cookie2".equals(h.getName())) {
            for (HttpCookie c : HttpCookie.parse(h.getValue())) {
                servletResponse.addCookie(servletCookie(c));
            }/*w w w . j a va 2  s .c o  m*/
        } else {
            servletResponse.setHeader(h.getName(), h.getValue());
        }
    }
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        Header ct = entity.getContentType();
        if (ct != null) {
            servletResponse.setContentType(ct.getValue());
        }
        Header ce = entity.getContentEncoding();
        if (ce != null) {
            servletResponse.setHeader(ce.getName(), ce.getValue());
        }
        long len = entity.getContentLength();
        if (len >= 0) {
            servletResponse.setContentLength((int) len);
        }
        ioHelper.pipe(entity.getContent(), servletResponse.getOutputStream(), true, false);
    }
}

From source file:com.swdouglass.joid.consumer.OpenIdFilter.java

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
    // basically just check for openId parameters
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    if (servletRequest.getParameter(OPENID_ATTRIBUTE) != null && !ignored(request)) {
        try {/*from   w ww .ja  va2 s  .c  o  m*/
            @SuppressWarnings("unchecked")
            AuthenticationResult result = joid
                    .authenticate(convertToStringValueMap(servletRequest.getParameterMap()));
            String identity = result.getIdentity();
            if (identity != null) {
                HttpServletRequest req = (HttpServletRequest) servletRequest;
                req.getSession(true).setAttribute(OpenIdFilter.OPENID_ATTRIBUTE, identity);
                HttpServletResponse resp = (HttpServletResponse) servletResponse; // could check this before setting
                Cookie cookie = new Cookie(OPENID_ATTRIBUTE, identity);
                if (cookieDomain != null) {
                    cookie.setDomain(cookieDomain);
                }
                if (cookieMaxAge != null) {
                    cookie.setMaxAge(cookieMaxAge);
                }
                resp.addCookie(cookie);
                // redirect to get rid of the long url
                resp.sendRedirect(result.getResponse().getReturnTo());
                return;
            }
        } catch (AuthenticationException e) {
            e.printStackTrace();
            log.info("auth failed: " + e.getMessage());
            // should this be handled differently?
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    filterChain.doFilter(servletRequest, servletResponse);
}

From source file:het.springapp.security.CsrfTokenGeneratorFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {
    //Create CSRF Token from request param
    CsrfToken token = (CsrfToken) request.getAttribute("_csrf");
    //Set up CSRF Response Headers for: HEADER, TOKEN & PARAM
    //response.setHeader("X-CSRF-HEADER", token.getHeaderName());
    //response.setHeader("X-CSRF-PARAM", token.getParameterName());
    // response.setHeader("X-CSRF-TOKEN", token.getToken());

    Cookie cookie = new Cookie("X-CSRF-TOKEN", token.getToken());
    cookie.setPath("/");
    response.addCookie(cookie);
    //Filter// w w w  . ja v  a  2s. c  o  m
    filterChain.doFilter(request, response);
}

From source file:cn.designthougths.sample.axon.sfav.webui.UIApplication.java

private Filter csrfHeaderFilter() {
    return new OncePerRequestFilter() {
        @Override/*from   w w w .  j  av  a  2 s.c o  m*/
        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                FilterChain filterChain) throws ServletException, IOException {
            CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
            if (csrf != null) {
                Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
                String token = csrf.getToken();
                if (cookie == null || token != null && !token.equals(cookie.getValue())) {
                    cookie = new Cookie("XSRF-TOKEN", token);
                    cookie.setPath("/");
                    response.addCookie(cookie);
                }
            }
            filterChain.doFilter(request, response);
        }
    };
}

From source file:nl.strohalm.cyclos.controls.access.LogoutAction.java

@Override
public ActionForward execute(final ActionMapping mapping, final ActionForm form,
        final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    request.getSession().invalidate();/*  w  ww. ja  va 2  s .  co m*/

    // When there is an 'afterLogout' cookie, it means we will redirect back to another site after logout
    final Cookie afterLogout = RequestHelper.getCookie(request, "afterLogout");
    if (afterLogout != null && StringUtils.isNotEmpty(afterLogout.getValue())) {
        String url = afterLogout.getValue();
        // Clear the cookie value
        afterLogout.setValue("");
        response.addCookie(afterLogout);
        try {
            final LocalSettings settings = settingsService.getLocalSettings();
            url = URLDecoder.decode(url, settings.getCharset());
        } catch (final UnsupportedEncodingException e) {
        }
        response.sendRedirect(url);
        return null;
    }

    ActionForward forward = mapping.findForward("success");

    // It may have a queryString to be passed again to the login page (ie: in case of customized login pages)...
    String queryString = RequestHelper.getCookieValue(request, "loginQueryString");
    if (StringUtils.isNotEmpty(queryString)) {
        queryString = StringHelper.decodeUrl(queryString);

        // Remove some variables we want to clear after a logout
        queryString = StringHelper.removeQueryStringVariable(queryString, "returnTo");

        // Remove a trailing &
        if (queryString.endsWith("&")) {
            queryString = queryString.substring(0, queryString.length() - 1);
        }

        // Apply the queryString
        String path = forward.getPath();
        if (StringUtils.isNotEmpty(queryString)) {
            path += "?" + queryString;
        }

        // Then set the forward
        forward = new ActionForward(path, true);
    }
    return forward;
}