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.adito.core.CoreUtil.java

/**
 * Store the provided user interface state name / value pair in a cookie
 * // ww w . j a v a  2s . c o  m
 * @param name ui state cookie name
 * @param value ui state cookie value
 * @param request request
 * @param response response
 */
public static void storeUIState(String name, String value, HttpServletRequest request,
        HttpServletResponse response) {
    Cookie c = getCookie(name, request);
    if (c != null) {
        c.setValue(value);
    } else {
        c = new Cookie(name, value);
    }
    c.setMaxAge(-1);
    response.addCookie(c);
}

From source file:de.knightsoftnet.validators.server.security.CsrfCookieHandler.java

/**
 * set csrf/xsrf cookie.//w w w. jav a  2  s .  c o m
 */
public void setCookie(final HttpServletRequest prequest, final HttpServletResponse presponse)
        throws IOException {
    final CsrfToken csrf = (CsrfToken) prequest.getAttribute(CsrfToken.class.getName());
    if (csrf != null) {
        Cookie cookie = WebUtils.getCookie(prequest, ResourcePaths.XSRF_COOKIE);
        final String token = csrf.getToken();
        if (cookie == null || token != null && !token.equals(cookie.getValue())) {
            cookie = new Cookie(ResourcePaths.XSRF_COOKIE, token);
            cookie.setPath(StringUtils.defaultString(StringUtils.trimToNull(prequest.getContextPath()), "/"));
            presponse.addCookie(cookie);
        }
    }
}

From source file:org.tonguetied.web.MainController.java

/**
 * Handler method that acts as an HTTP interface to the 
 * {@linkplain KeywordService#getKeywords()} method.
 * //from w w w.jav a2s .c  o  m
 * @param request the current HTTP request.
 * @param response the current HTTP response.
 * @return a ModelAndView to render.
 * @throws Exception in case of errors.
 */
public ModelAndView keywords(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Cookie cookie = CookieUtils.getCookie(request, "menuSelected");
    if (cookie == null) {
        cookie = CookieUtils.createCookie(request, "menuSelected", "1");
        response.addCookie(cookie);
    }

    Boolean showAll = RequestUtils.getBooleanParameter(request, SHOW_ALL_KEYWORDS);
    if (showAll == null) {
        showAll = (Boolean) request.getSession().getAttribute(SHOW_ALL_KEYWORDS);
    }

    final int firstResult = PaginationUtils.calculateFirstResult(TABLE_ID_KEYWORD,
            viewPreferences.getMaxResults(), request);
    final KeyValue<String, Order> keyValue = PaginationUtils.getOrder(TABLE_ID_KEYWORD, request);
    Order order = null;
    if (keyValue != null)
        order = keyValue.getValue();

    PaginatedList<Keyword> keywords;
    if (showAll) {
        keywords = keywordService.getKeywords(firstResult, viewPreferences.getMaxResults(), order);
        searchParameters.initialize();
    } else {
        Keyword keyword = searchParameters.getKeyword();
        if (new Translation().equals(keyword.getTranslations().first())) {
            keyword.setTranslations(SetUtils.EMPTY_SORTED_SET);
        }
        keywords = keywordService.findKeywords(keyword, searchParameters.getIgnoreCase(), order, firstResult,
                viewPreferences.getMaxResults());
    }

    keywords = applyViewPreferences(keywords);
    searchParameters.getKeyword();

    Map<String, Object> model = new HashMap<String, Object>();
    model.put(KEYWORDS, keywords);
    model.put(LANGUAGES, keywordService.getLanguages());
    model.put(BUNDLES, keywordService.getBundles());
    model.put(COUNTRIES, keywordService.getCountries());
    model.put(STATES, TranslationState.values());
    model.put(SEARCH_PARAMETERS, searchParameters);
    model.put(VIEW_PREFERENCES, viewPreferences);
    model.put(MAX_LIST_SIZE, keywords.getMaxListSize());
    model.put(PAGE_SIZES, KEYWORD_PAGE_SIZE_OPTIONS);
    return new ModelAndView("keyword/keywords", model);
}

From source file:net.sf.ehcache.constructs.web.filter.CachingFilter.java

/**
 * Set the serializableCookies//  w  ww .j  a va 2  s.c o  m
 *
 * @param pageInfo
 * @param response
 */
protected void setCookies(final PageInfo pageInfo, final HttpServletResponse response) {

    final Collection cookies = pageInfo.getSerializableCookies();
    for (Iterator iterator = cookies.iterator(); iterator.hasNext();) {
        final Cookie cookie = ((SerializableCookie) iterator.next()).toCookie();
        response.addCookie(cookie);
    }
}

From source file:ch.unifr.pai.twice.widgets.mpproxy.server.SimpleHttpUrlConnectionServletFilter.java

/**
 * Apply the filter logic/*from www. j  a  va 2 s  .c  o  m*/
 * 
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
 */
@Override
public void doFilter(ServletRequest genericRequest, ServletResponse genericResponse, FilterChain chain)
        throws IOException, ServletException {
    if (genericRequest instanceof HttpServletRequest && genericResponse instanceof HttpServletResponse) {
        HttpServletRequest request = (HttpServletRequest) genericRequest;
        HttpServletResponse response = (HttpServletResponse) genericResponse;

        if (request.getSession().getAttribute(Constants.uuidCookie) == null) {
            request.getSession().setAttribute(Constants.uuidCookie, UUID.randomUUID().toString());
        }
        response.addCookie(new Cookie(Constants.uuidCookie,
                request.getSession().getAttribute(Constants.uuidCookie).toString()));
        String fullUrl = getFullRequestString(request);

        fullUrl.replace("gwt.codesvr=127.0.0.1:9997&", "");
        String servletPath = getServletPath(request);
        if (!servletPath.endsWith("/"))
            servletPath += "/";

        URLParser parser = new URLParser(fullUrl, servletPath);
        String url = parser.getFullProxyPath();

        // Prevent the managing resources to be filtered.
        if (request.getRequestURL().toString().startsWith(servletPath + Constants.nonFilterPrefix)
                || (url != null && url.equals(fullUrl))) {
            chain.doFilter(genericRequest, genericResponse);
            return;
        }

        // The read only screen
        if (request.getRequestURL().toString().contains("miceScreenShot")) {

            String result = ReadOnlyPresentation.getScreenshotForUUID(request.getParameter("uuid"));
            PrintWriter w = response.getWriter();
            if (result == null) {
                w.println("No screenshot available");
            } else {
                w.print(result);
            }
            w.flush();
            w.close();
            return;
        }
        // ProxyURLParser parser = new ProxyURLParser(fullUrl);
        // String url = parser.writeRequestUrl();
        if (url == null || url.isEmpty() || !url.startsWith("http")) {
            // We've lost context - lets try to re-establish it from
            // other
            // sources...
            String newProxyBase = null;

            // ... a referer is the best hint
            String referer = request.getHeader("Referer");
            if (referer != null && !referer.isEmpty()) {
                URLParser refererParser = new URLParser(referer, Rewriter.getServletPath(referer));
                if (refererParser.getProxyBasePath() != null && !refererParser.getProxyBasePath().isEmpty()) {
                    newProxyBase = refererParser.getProxyBasePath();
                }
            }
            // ... otherwise use the last used proxy (since it probably
            // is a
            // redirection we might have success with this)
            if (newProxyBase == null) {
                newProxyBase = (String) request.getSession().getAttribute("lastProxy");
            }

            // Now redirect the client to the new url
            if (newProxyBase != null) {
                url = newProxyBase + (url != null && !url.isEmpty() ? '/' + url : "/");
                response.sendRedirect(servletPath + url);

            } else {
                response.sendError(404);
            }
            return;

        }
        url = url.replace("\\|", "&#124;");

        ProcessResult result = null;
        try {
            result = servlet.loadFromProxy(request, response, url, servletPath, parser.getProxyBasePath());

        } catch (UnknownHostException e) {
            // If we get a unknown host exception, we try it with the
            // referer
            String referer = request.getHeader("Referer");
            if (parser.getRefererRelative() != null && referer != null && !referer.isEmpty()) {
                URLParser refererParser = new URLParser(referer, Rewriter.getServletPath(referer));
                if (refererParser.getProxyBasePath() != null && !refererParser.getProxyBasePath().isEmpty()) {
                    String newUrl = refererParser.getProxyBasePath() + parser.getRefererRelative();
                    try {
                        result = servlet.loadFromProxy(request, response, newUrl, servletPath,
                                refererParser.getProxyBasePath());
                    } catch (UnknownHostException e1) {
                        result = null;
                        response.sendError(404);
                    }
                } else {
                    result = null;
                    response.sendError(404);
                }
            } else {
                result = null;
                response.sendError(404);
            }

        }

        if (result != null) {
            // If an error is returned, we don't need to process the
            // inputstream
            InputStream input;
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            OutputStream output = outputStream;
            if (result.isGzipped()) {
                output = new GZIPOutputStream(outputStream, 100000);
            }
            String s = URLRewriterServer.process(result.getContent(), fullUrl);
            s = URLRewriterServer.removeTopHref(s);
            if (request.getSession().getAttribute(Constants.miceManaged) == null
                    || !request.getSession().getAttribute(Constants.miceManaged).equals("true")) {
                s = s.replace("<head>",
                        "<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1\">");
                // Pattern p = Pattern.compile("<body.*?>");
                // Matcher m = p.matcher(s);
                // StringBuffer sb = new StringBuffer();
                // while (m.find()) {
                // m.appendReplacement(
                // sb,
                // m.group()
                // + "<link href=\""
                // + servletPath
                // +
                // "miceproxy/navigation.css\" rel=\"stylesheet\" type=\"text/css\"/><div id=\"miceNavigation\"><input id=\"miceUrlBox\" type=\"text\" value=\""
                // + parser.getFullProxyPath()
                // +
                // "\"/></div><div id=\"contentWrapper\">");
                // }
                // s = m.appendTail(sb).toString();
                // s = s.replace("</body>",
                // "</div></body>");
            }

            // The page shall only be injected if it is a
            // html page and if it really has html content
            // (prevent e.g. blank.html to be injected)
            if (result.getContentType() != null && result.getContentType().contains("text/html")
                    && (s.contains("body") || s.contains("BODY")))
                s += "<script type=\"text/javascript\" language=\"javascript\" src=\"" + servletPath
                        + "miceproxy/miceproxy.nocache.js\"></script>";
            IOUtils.write(s, output, result.getCharset());
            output.flush();
            if (output instanceof GZIPOutputStream)
                ((GZIPOutputStream) output).finish();
            outputStream.writeTo(response.getOutputStream());
        }

    }
}

From source file:org.acegisecurity.ui.rememberme.TokenBasedRememberMeServices.java

protected void cancelCookie(HttpServletRequest request, HttpServletResponse response, String reasonForLog) {
    if ((reasonForLog != null) && logger.isDebugEnabled()) {
        logger.debug("Cancelling cookie for reason: " + reasonForLog);
    }/*from   w w  w .  j  av  a 2  s  .c  om*/

    response.addCookie(makeCancelCookie(request));
}

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   ww  w. j  av a 2  s  . 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:au.gov.dto.springframework.security.web.context.CookieSecurityContextRepository.java

/**
 * Obtains the security context for the supplied request. For an unauthenticated user, an empty context
 * implementation should be returned. This method should not return null.
 * <p>/*from   ww w  .  j a va2 s.co m*/
 * The use of the <tt>HttpRequestResponseHolder</tt> parameter allows implementations to return wrapped versions of
 * the request or response (or both), allowing them to access implementation-specific state for the request.
 * The values obtained from the holder will be passed on to the filter chain and also to the <tt>saveContext</tt>
 * method when it is finally called. Implementations may wish to return a subclass of
 * {@link SaveContextOnUpdateOrErrorResponseWrapper} as the response object, which guarantees that the context is
 * persisted when an error or redirect occurs.
 *
 * @param requestResponseHolder holder for the current request and response for which the context should be loaded.
 *
 * @return The security context which should be used for the current request, never null.
 */
@Override
public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) {
    HttpServletRequest request = requestResponseHolder.getRequest();
    HttpServletResponse response = requestResponseHolder.getResponse();
    requestResponseHolder.setResponse(new SaveToCookieResponseWrapper(request, response));
    Cookie authenticationCookie = getAuthenticationCookie(request);
    if (authenticationCookie == null) {
        return SecurityContextHolder.createEmptyContext();
    }
    String serialisedAuthentication = tokenEncryption.decryptAndVerify(authenticationCookie.getValue());
    if (serialisedAuthentication == null) {
        response.addCookie(createExpireAuthenticationCookie(request));
        return SecurityContextHolder.createEmptyContext();
    }
    Authentication authentication = authenticationSerializer.deserialize(serialisedAuthentication);
    SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
    securityContext.setAuthentication(authentication);
    return securityContext;
}

From source file:com.bosch.cr.examples.jwt.auth.GoogleCallbackServlet.java

@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    try {/* w  ww . j  a v a  2 s .c  o m*/
        final String code = OAuthAuthzResponse.oauthCodeAuthzResponse(req).getCode();
        final String idToken = getIdToken(code);

        final boolean secure = configurationProperties
                .getPropertyAsBoolean(ConfigurationProperty.SECURE_COOKIE);
        final int maxAge = -1; // cookie is deleted when browser is closed
        final Cookie cookie = CookieUtil.getJwtAuthenticationCookie(idToken, secure, maxAge);

        resp.addCookie(cookie);
        resp.sendRedirect(REDIRECT_URL);
    } catch (final OAuthProblemException | OAuthSystemException e) {
        resp.setStatus(HttpStatus.SC_UNAUTHORIZED);
        resp.getOutputStream().print(e.getMessage());
        throw new RuntimeException(e);
    }
}

From source file:com.glaf.core.util.RequestUtils.java

public static void setLoginUser(HttpServletRequest request, HttpServletResponse response, String systemName,
        String actorId) {/*from  www. j  av  a2  s  . co  m*/
    String ip = getIPAddress(request);
    ip = DigestUtils.md5Hex(ip);
    String value = encodeValues(ip, systemName, actorId);
    HttpSession session = request.getSession(false);
    if (session != null) {
        session.setAttribute(Constants.LOGIN_INFO, value);
    }
    Cookie cookie = new Cookie(Constants.COOKIE_NAME, value);
    cookie.setPath("/");
    cookie.setMaxAge(-1);
    response.addCookie(cookie);
}