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:org.dspace.webmvc.theme.ThemeChangeInterceptor.java

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
        ModelAndView modelAndView) throws Exception {
    ThemeResolver themeResolver = RequestContextUtils.getThemeResolver(request);
    if (themeResolver == null) {
        throw new IllegalStateException("No ThemeResolver found: not in a DispatcherServlet request?");
    }// w w  w. j a  v  a  2s .c  o m

    String newTheme = request.getParameter(this.paramName);
    if (newTheme != null) {
        themeResolver.setThemeName(request, response, newTheme);
        response.addCookie(new Cookie("themeName", newTheme));
    } else {
        ThemeMapEntry bestMatch = null;

        for (ThemeMapEntry entry : themeMappings) {

            if (entry.mapType == MapType.VIEW || entry.mapType == MapType.ANY) {
                if (modelAndView != null && pathMatcher.match(entry.path, modelAndView.getViewName())) {
                    if (entry.isBestMatch(bestMatch)) {
                        bestMatch = entry;
                    }
                }
            }

            if (entry.mapType == MapType.URL || entry.mapType == MapType.ANY) {
                String path = urlPathHelper.getLookupPathForRequest(request);
                if (pathMatcher.match(entry.path, path)) {
                    if (entry.isBestMatch(bestMatch)) {
                        bestMatch = entry;
                    }
                }
            }

            if (entry.mapType == MapType.CONTROLLER || entry.mapType == MapType.ANY) {

            }
        }

        if (bestMatch != null) {
            themeResolver.setThemeName(request, response, bestMatch.themeName);
        } else if (request.getCookies() != null) {
            for (Cookie cookie : request.getCookies()) {
                if ("themeName".equals(cookie.getName())) {
                    themeResolver.setThemeName(request, response, cookie.getValue());
                }
            }
        }
    }

    super.postHandle(request, response, handler, modelAndView);
}

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

@RequestMapping(value = "/logout.htm")
public ModelAndView logout(HttpServletRequest request, HttpServletResponse response,
        @CookieValue(value = "CLOUDNINJAAUTH", required = false) String cookie) throws CloudNinjaException {

    if (cookie != null) {
        cookie = null;//from   ww w  .  j  av  a2s .  c  o  m
        Cookie c = new Cookie("CLOUDNINJAAUTH", null);
        c.setPath("/");
        response.addCookie(c);
        response.setHeader("Cache-Control", "no-cache,no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", -1);
    }
    if (request.getAttribute("cookieNameAttr") != null) {
        request.setAttribute("cookieNameAttr", null);
    }

    return new ModelAndView("logoutsuccess");
}

From source file:com.mxgraph.online.drive.FileServlet.java

protected void endSession(HttpServletRequest request, HttpServletResponse response, CredentialMediator mediator)
        throws NoRefreshTokenException, IOException {
    mediator.deleteActiveCredential();//from w w  w .  ja v  a 2 s.c  om
    request.getSession().invalidate();
    Cookie cookie = new Cookie("drive", "");
    cookie.setMaxAge(0);
    response.addCookie(cookie);
    throw new NoRefreshTokenException();
}

From source file:com.baidu.rigel.biplatform.ma.auth.resource.RandomValidateCode.java

/**
 * //from w  w w.j  a  va 2s.c om
 * @param request
 * @param response
 * @param cacheManagerForResource 
 */
public static void getRandcode(HttpServletRequest request, HttpServletResponse response,
        CacheManagerForResource cacheManagerForResource) {
    // BufferedImageImage,Image????
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
    Graphics g = image.getGraphics(); // ImageGraphics,?????
    g.fillRect(0, 0, width, height);
    g.setFont(new Font("Times New Roman", Font.ROMAN_BASELINE, 18));
    g.setColor(getRandColor(110, 133));
    // 
    for (int i = 0; i <= lineSize; i++) {
        drowLine(g);
    }
    // ?
    String randomString = "";
    for (int i = 1; i <= stringNum; i++) {
        randomString = drowString(g, randomString, i);
    }
    String key = null;
    if (request.getCookies() != null) {
        for (Cookie tmp : request.getCookies()) {
            if (tmp.getName().equals(Constants.RANDOMCODEKEY)) {
                key = tmp.getName();
                cacheManagerForResource.removeFromCache(key);
                break;
            }
        }
    }
    if (StringUtils.isEmpty(key)) {
        key = String.valueOf(System.nanoTime());
    }
    cacheManagerForResource.setToCache(key, randomString);
    final Cookie cookie = new Cookie(Constants.RANDOMCODEKEY, key);
    cookie.setPath(Constants.COOKIE_PATH);
    response.addCookie(cookie);
    g.dispose();
    try {
        ImageIO.write(image, "JPEG", response.getOutputStream()); // ??
    } catch (Exception e) {
        LOG.info(e.getMessage());
    }
}

From source file:org.moserp.infrastructure.gateway.config.OAuthConfiguration.java

/**
 * Spring security offers in-built protection for cross site request forgery
 * (CSRF) by needing a custom token in the header for any requests that are
 * NOT safe i.e. modify the resources from the server e.g. POST, PUT & PATCH
 * etc.<br>//w w w  . jav  a 2 s  . c  o  m
 * <br>
 *
 * This protection is achieved using cookies that send a custom value (would
 * remain same for the session) in the first request and then the front-end
 * would send back the value as a custom header.<br>
 * <br>
 *
 * In this method we create a filter that is applied to the web security as
 * follows:
 * <ol>
 * <li>Spring security provides the CSRF token value as a request attribute;
 * so we extract it from there.</li>
 * <li>If we have the token, Angular wants the cookie name to be
 * "XSRF-TOKEN". So we add the cookie if it's not there and set the path for
 * the cookie to be "/" which is root. In more complicated cases, this might
 * have to be the context root of the api gateway.</li>
 * <li>We forward the request to the next filter in the chain</li>
 * </ol>
 *
 * The request-to-cookie filter that we add needs to be after the
 * <code>csrf()</code> filter so that the request attribute for CsrfToken
 * has been already added before we start to process it.
 *
 * @return
 */
private Filter createCSRFHeaderFilter() {
    return new OncePerRequestFilter() {
        @Override
        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, CSRF_COOKIE_NAME);
                String token = csrf.getToken();
                if (cookie == null || token != null && !token.equals(cookie.getValue())) {
                    cookie = new Cookie(CSRF_COOKIE_NAME, token);
                    cookie.setPath("/");
                    response.addCookie(cookie);
                }
            }
            filterChain.doFilter(request, response);
        }
    };
}

From source file:com.arya.latihan.config.SecurityConfiguration.java

/**
 * Method untuk menyimpan CSRF TOKEN di cookie browser.
 * Token disimpan dengan nama XSRF-TOKEN karena AngularJS mengenal CSRF sebagai XSRF
 * @return Filter//from   w w w  . ja  v  a2s . c om
 */
private Filter csrfHeaderFilter() {
    return new OncePerRequestFilter() {

        @Override
        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                FilterChain filterChain) throws ServletException, IOException {
            CsrfToken csrfToken = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
            if (csrfToken != null) {
                String token = csrfToken.getToken();
                Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");// angular js menamai CSRF dengan XSRF
                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:testapp.CsrfTokenResponseHeaderBindingFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        javax.servlet.FilterChain filterChain) throws ServletException, IOException {
    CsrfToken token = (CsrfToken) request.getAttribute(REQUEST_ATTRIBUTE_NAME);
    Enumeration<String> e = request.getAttributeNames();

    while (e.hasMoreElements()) {
        String param = (String) e.nextElement();
        System.out.println(param);
    }/*from  w ww .  j  av  a 2 s  . c  o  m*/

    if (token != null) {
        response.setHeader(RESPONSE_HEADER_NAME, token.getHeaderName());
        response.setHeader(RESPONSE_PARAM_NAME, token.getParameterName());
        response.setHeader(RESPONSE_TOKEN_NAME, token.getToken());

        response.addCookie(new Cookie("XSRF-TOKEN", token.getToken()));
    }

    filterChain.doFilter(request, response);
}

From source file:es.pode.soporte.seguridad.openId.ui.openid.OpenIDAuthenticationProcessingFilter.java

/** 
* Invalida la cookie AUTENTICADO//from   ww w  .j ava  2  s. c  om
* @param response
* @param request
*/
private void invalidateCookieAutenticado(HttpServletResponse response) throws IOException {

    Cookie cookieAutenticado = new Cookie("AUTENTICADO", "");
    cookieAutenticado.setPath("/");
    cookieAutenticado.setMaxAge(0);
    response.addCookie(cookieAutenticado);

}

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

@RequestMapping(value = "{tenantId}/showTenantHomePageList.htm")
public ModelAndView preAuthenticate(HttpServletRequest request, HttpServletResponse response,
        @CookieValue(value = "CLOUDNINJAAUTH", required = false) String cookie,
        @PathVariable("tenantId") String tenantId) throws SystemException {

    if (cookie == null) {
        cookie = request.getAttribute("cookieNameAttr").toString();
    }/*  w  w  w .ja va 2 s  . c o  m*/

    response.addCookie(getTenantLogoCookieInResponse(tenantId, cookie));
    String tenentDbString = "tnt_"
            + AuthFilterUtils.getFieldValueFromCookieString(CloudNinjaConstants.COOKIE_TENANTID_PREFIX, cookie);
    String userName = AuthFilterUtils.getFieldValueFromCookieString(CloudNinjaConstants.COOKIE_USERNAME_PREFIX,
            cookie);
    ;

    //Listing the task list
    List<TaskList> viewTaskList = taskListService.showList(tenentDbString);
    TaskListDTO taskListDTO = new TaskListDTO();
    taskListDTO.setTaskList(viewTaskList);
    ModelAndView model = new ModelAndView("showTenantHomePageList", "taskListDTO", taskListDTO);
    model.addObject("userName", userName);
    return model;
}

From source file:com.shenit.commons.utils.HttpUtils.java

/**
 * ?cookie/*from   w  ww  .  j a va 2 s  .  c  o m*/
 * 
 * @param req
 *            
 * @param names
 *            cookie??
 */
public static void purgeCookies(HttpServletRequest req, HttpServletResponse resp, String... names) {
    Set<String> nameSet = ValidationUtils.isEmpty(names) ? null : new HashSet<String>(Arrays.asList(names));
    boolean removeAll = ValidationUtils.isEmpty(nameSet);
    for (Cookie cookie : req.getCookies()) {
        if (removeAll || nameSet.contains(cookie.getName())) {
            cookie.setMaxAge(0);
            cookie.setValue(null);
            resp.addCookie(cookie);
            if (!removeAll)
                nameSet.remove(cookie.getName());
            ;
        }
    }
}