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:MyServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    out.println("<HTML>");
    out.println("<HEAD>");
    out.println("<TITLE>");
    out.println("A Web Page");
    out.println("</TITLE>");
    out.println("</HEAD>");
    out.println("<BODY");

    Cookie[] cookies = request.getCookies();
    boolean foundCookie = false;

    for (int i = 0; i < cookies.length; i++) {
        Cookie cookie1 = cookies[i];//from   w ww .  j av  a  2 s . c o  m
        if (cookie1.getName().equals("color")) {
            out.println("bgcolor = " + cookie1.getValue());
            foundCookie = true;
        }
    }

    if (!foundCookie) {
        Cookie cookie1 = new Cookie("color", "cyan");
        cookie1.setMaxAge(24 * 60 * 60);
        response.addCookie(cookie1);
    }

    out.println(">");
    out.println("<H1>Setting and Reading Cookies</H1>");
    out.println("This page will set its background color using a cookie when reloaded.");
    out.println("</BODY>");
    out.println("</HTML>");
}

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

/**
 * Actualiza el timeout de la cookie de OpenId
 * @param ServletRequest /*  w w  w .  j  a va2  s . c o m*/
 * @param ServletResponse
 * @param nombreCookie
 * @throws IOException
*/
private void actualizaCookie(HttpServletRequest request, HttpServletResponse response, String nombreCookie)
        throws IOException {
    Cookie cookie = null;
    if (log.isDebugEnabled())
        log.debug("Se coge la cookie " + nombreCookie);
    cookie = getCookie(nombreCookie, request.getCookies());
    int caducidadCookie = (new Integer(this.getAgregaPropertyValue(AgregaProperties.TIMEOUTCOOKIEOPENID)))
            .intValue();
    if (log.isDebugEnabled())
        log.debug("caducidadCookie " + caducidadCookie);
    cookie.setMaxAge(caducidadCookie);
    cookie.setPath("/");
    response.addCookie(cookie);
}

From source file:org.ajax4jsf.webapp.BaseXMLFilter.java

/**
 * @param response//from ww w . ja v  a  2 s. c o  m
 * @param servletResponseWrapper
 * @param ajaxResponseType
 * @return
 * @throws IOException
 * @throws UnsupportedEncodingException
 */
private Writer resetResponse(final HttpServletResponse response,
        FilterServletResponseWrapper servletResponseWrapper, String ajaxResponseType)
        throws IOException, UnsupportedEncodingException {
    Writer output;
    response.reset();
    // Keep cookies.
    for (Iterator<Cookie> iter = servletResponseWrapper.getCookies().iterator(); iter.hasNext();) {
        Cookie cookie = (Cookie) iter.next();
        response.addCookie(cookie);
    }
    // Copy response headers
    Map<String, Object> headers = servletResponseWrapper.getHeaders();
    for (Iterator<Map.Entry<String, Object>> iter = headers.entrySet().iterator(); iter.hasNext();) {
        Map.Entry<String, Object> header = iter.next();
        response.setHeader((String) header.getKey(), (String) header.getValue());
    }
    response.setHeader(AjaxContainerRenderer.AJAX_FLAG_HEADER, ajaxResponseType);
    // Not caching AJAX request
    response.setHeader("Cache-Control", "no-cache, must-revalidate, max_age=0, no-store");
    response.setHeader("Expires", "0");
    response.setHeader("Pragma", "no-cache");
    response.setContentType(getMimetype() + ";charset=UTF-8");
    output = createOutputWriter(response, "UTF-8");
    return output;
}

From source file:org.b3log.latke.util.Requests.java

/**
 * Determines whether the specified request has been served.
 * //from w w  w.j a v  a2 s  . co m
 * <p>
 * A "served request" is a request a URI as former one. For example, if a client is request "/test", all requests from the client 
 * subsequent in 24 hours will be treated as served requests, requested URIs save in client cookie (name: "visited").
 * </p>
 * 
 * <p>
 * If the specified request has not been served, appends the request URI in client cookie. 
 * </p>
 * 
 * <p>
 * Sees this issue (https://github.com/b3log/b3log-solo/issues/44) for more details.
 * </p>
 * 
 * @param request the specified request
 * @param response the specified response
 * @return {@code true} if the specified request has been served, returns {@code false} otherwise
 */
public static boolean hasBeenServed(final HttpServletRequest request, final HttpServletResponse response) {
    final Cookie[] cookies = request.getCookies();

    if (null == cookies || 0 == cookies.length) {
        return false;
    }

    Cookie cookie;
    boolean needToCreate = true;
    boolean needToAppend = true;
    JSONArray cookieJSONArray = null;

    try {
        for (int i = 0; i < cookies.length; i++) {
            cookie = cookies[i];

            if (!"visited".equals(cookie.getName())) {
                continue;
            }

            cookieJSONArray = new JSONArray(cookie.getValue());
            if (null == cookieJSONArray || 0 == cookieJSONArray.length()) {
                return false;
            }

            needToCreate = false;

            for (int j = 0; j < cookieJSONArray.length(); j++) {
                final String visitedURL = cookieJSONArray.optString(j);

                if (request.getRequestURI().equals(visitedURL)) {
                    needToAppend = false;
                    return true;
                }
            }
        }

        if (needToCreate) {
            final StringBuilder builder = new StringBuilder("[").append("\"").append(request.getRequestURI())
                    .append("\"]");

            final Cookie c = new Cookie("visited", builder.toString());

            c.setMaxAge(COOKIE_EXPIRY);
            c.setPath("/");
            response.addCookie(c);
        } else if (needToAppend) {
            cookieJSONArray.put(request.getRequestURI());

            final Cookie c = new Cookie("visited", cookieJSONArray.toString());

            c.setMaxAge(COOKIE_EXPIRY);
            c.setPath("/");
            response.addCookie(c);
        }
    } catch (final Exception e) {
        LOGGER.log(Level.WARNING, "Parses cookie failed, clears the cookie[name=visited]", e);

        final Cookie c = new Cookie("visited", null);

        c.setMaxAge(0);
        c.setPath("/");

        response.addCookie(c);
    }

    return false;
}

From source file:org.sharetask.controller.UserController.java

@RequestMapping(value = "/login", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public void performLogin(@RequestBody final UserPassword login, final HttpServletRequest request,
        final HttpServletResponse response) {
    final UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
            login.getUsername(), login.getPassword());
    try {/*from   ww  w  .j  a  v  a  2s . co  m*/
        final Authentication auth = authenticationManager.authenticate(token);
        SecurityContextHolder.getContext().setAuthentication(auth);
        repository.saveContext(SecurityContextHolder.getContext(), request, response);
        rememberMeServices.loginSuccess(request, response, auth);
        // language cookie
        final UserInfoDTO user = userService.read(SecurityUtil.getCurrentSignedInUsername());
        final Cookie locale = new Cookie(RequestUltil.LOCALE, user.getLanguage());
        locale.setMaxAge(-1);
        locale.setPath("/");
        response.addCookie(locale);
        response.setStatus(HttpStatus.OK.value());
    } catch (final BadCredentialsException ex) {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
    }
}

From source file:csns.web.filter.DepartmentFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {
    String contextPath = request.getContextPath();
    String path = request.getRequestURI().substring(contextPath.length());
    Cookie cookie = WebUtils.getCookie(request, "default-dept");

    if (path.startsWith("/department/")) {
        int beginIndex = "/department/".length();
        int endIndex = path.indexOf("/", beginIndex);
        if (endIndex < 0)
            endIndex = path.length();/* w  w w  . ja  v  a  2  s . c  om*/
        String dept = path.substring(beginIndex, endIndex);
        request.setAttribute("dept", dept);

        logger.debug(path + " -> " + dept);

        if (cookie == null) {
            cookie = new Cookie("default-dept", dept);
            cookie.setPath("/");
            cookie.setMaxAge(100000000);
            response.addCookie(cookie);
        }
    } else {
        if (cookie != null)
            request.setAttribute("dept", cookie.getValue());
    }

    filterChain.doFilter(request, response);
}

From source file:azkaban.webapp.servlet.LoginAbstractAzkabanServlet.java

protected void handleAjaxLoginAction(HttpServletRequest req, HttpServletResponse resp, Map<String, Object> ret)
        throws ServletException {
    if (hasParam(req, "username") && hasParam(req, "password")) {
        Session session = null;/* w  ww  . j a  v a2s .  com*/
        try {
            session = createSession(req);
        } catch (UserManagerException e) {
            ret.put("error", "Incorrect Login. " + e.getMessage());
            return;
        }

        Cookie cookie = new Cookie(SESSION_ID_NAME, session.getSessionId());
        cookie.setPath("/");
        resp.addCookie(cookie);
        getApplication().getSessionCache().addSession(session);
        ret.put("status", "success");
        ret.put("session.id", session.getSessionId());
    } else {
        ret.put("error", "Incorrect Login.");
    }
}

From source file:edu.lternet.pasta.gatekeeper.GatekeeperFilter.java

private Cookie doHeader(HttpServletRequest req, HttpServletResponse res) {
    String rawHeader = req.getHeader(HttpHeaders.AUTHORIZATION);
    boolean publicUser = (rawHeader == null || rawHeader.isEmpty());
    AuthToken authToken = makeAuthenticated(rawHeader);

    // Only return authToken (in cookie) if real user
    if (!publicUser) {
        Cookie externalCookie = makeAuthTokenCookie(authToken, CookieUse.EXTERNAL);
        res.addCookie(externalCookie);
    }//w  w w. j a v  a2  s  .  c  o  m

    return makeAuthTokenCookie(authToken, CookieUse.INTERNAL);
}

From source file:net.smartam.leeloo.controller.RedirectController.java

@RequestMapping(method = RequestMethod.GET)
public ModelAndView handleRedirect(@ModelAttribute("oauthParams") OAuthParams oauthParams,
        HttpServletRequest request, HttpServletResponse response) {

    try {/*from www.j  av  a 2s . co m*/

        // Create the response wrapper
        OAuthAuthzResponse oar = null;
        oar = OAuthAuthzResponse.oauthCodeAuthzResponse(request);

        // Get Authorization Code
        String code = oar.getCode();

        // Get OAuth Info
        String clientId = Utils.findCookieValue(request, "clientId");
        String clientSecret = Utils.findCookieValue(request, "clientSecret");
        String authzEndpoint = Utils.findCookieValue(request, "authzEndpoint");
        String tokenEndpoint = Utils.findCookieValue(request, "tokenEndpoint");
        String redirectUri = Utils.findCookieValue(request, "redirectUri");
        String scope = Utils.findCookieValue(request, "scope");

        String app = Utils.findCookieValue(request, "app");
        response.addCookie(new Cookie("app", app));

        oauthParams.setAuthzCode(code);
        oauthParams.setClientId(clientId);
        oauthParams.setClientSecret(clientSecret);
        oauthParams.setAuthzEndpoint(authzEndpoint);
        oauthParams.setTokenEndpoint(tokenEndpoint);
        oauthParams.setRedirectUri(redirectUri);
        oauthParams.setScope(Utils.isIssued(scope));
        oauthParams.setApplication(app);

    } catch (OAuthProblemException e) {
        StringBuffer sb = new StringBuffer();
        sb.append("</br>");
        sb.append("Error code: ").append(e.getError()).append("</br>");
        sb.append("Error description: ").append(e.getDescription()).append("</br>");
        sb.append("Error uri: ").append(e.getUri()).append("</br>");
        sb.append("State: ").append(e.getState()).append("</br>");
        oauthParams.setErrorMessage(sb.toString());
        return new ModelAndView("main");
    }

    return new ModelAndView("request_token");

}

From source file:org.guanxi.idp.service.GenericAuthHandler.java

protected boolean auth(String spEntityID, HttpServletRequest request, HttpServletResponse response) {
    // Look for our cookie. This is after any application cookie handler has authenticated the user
    String cookieName = getCookieName();
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (int c = 0; c < cookies.length; c++) {
            if (cookies[c].getName().equals(cookieName)) {
                // Retrieve the principal from the servlet context
                if (servletContext.getAttribute(cookies[c].getValue()) == null) {
                    // Out of date cookie value, so remove the cookie
                    cookies[c].setMaxAge(0);
                    response.addCookie(cookies[c]);
                } else {
                    // Found the principal from a previously established authentication
                    request.setAttribute(Guanxi.REQUEST_ATTR_IDP_PRINCIPAL,
                            (GuanxiPrincipal) servletContext.getAttribute(cookies[c].getValue()));
                    return true;
                }//from w  w w  .j  ava  2s  .  co  m
            }
        }
    }

    // Are we getting an authentication request from the login page?
    if (request.getParameter("guanxi:mode") != null) {
        if (request.getParameter("guanxi:mode").equalsIgnoreCase("authenticate")) {
            // Get a new GuanxiPrincipal...
            GuanxiPrincipal principal = gxPrincipalFactory.createNewGuanxiPrincipal(request);
            if (authenticator.authenticate(principal, request.getParameter("userid"),
                    request.getParameter("password"))) {
                // ...associate it with a login name...
                if (principal.getName() == null) {
                    //The login name from the authenticator page
                    principal.setName(request.getParameter("userid"));
                }
                // ...store it in the request for the SSO to use...
                request.setAttribute(Guanxi.REQUEST_ATTR_IDP_PRINCIPAL, principal);
                // ...and store it in application scope for the rest of the profile to use
                servletContext.setAttribute(principal.getUniqueId(), principal);

                // Get a new cookie ready to reference the principal in the servlet context
                Cookie cookie = new Cookie(getCookieName(), principal.getUniqueId());
                cookie.setDomain((String) servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_COOKIE_DOMAIN));
                cookie.setPath(idpConfig.getCookie().getPath());
                if (((Integer) (servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_COOKIE_AGE)))
                        .intValue() != -1)
                    cookie.setMaxAge(
                            ((Integer) (servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_COOKIE_AGE)))
                                    .intValue());
                response.addCookie(cookie);

                return true;
            } // if (authenticator.authenticate...
            else {
                logger.error("Authentication error : " + authenticator.getErrorMessage());
                request.setAttribute("message",
                        messageSource.getMessage("authentication.error", null, request.getLocale()));
                try {
                    request.getRequestDispatcher(errorPage).forward(request, response);
                } catch (Exception e) {
                    logger.error("Could not display authentication error page", e);
                }
                return false;
            }
        }
    } // if (request.getParameter("guanxi:mode") != null) {

    // No embedded cookie authentication or local auth, so show the login page
    String authPage = null;
    AuthPage[] authPages = idpConfig.getAuthenticatorPages().getAuthPageArray();
    for (int c = 0; c < authPages.length; c++) {
        // We'll use the default auth page if none is specified for this service provider
        if (authPages[c].getProviderId().equals(Guanxi.DEFAULT_AUTH_PAGE_MARKER)) {
            authPage = authPages[c].getUrl();
        }

        // Customised auth page for this service provider
        if (authPages[c].getProviderId().equals(request.getParameter(spEntityID))) {
            authPage = authPages[c].getUrl();
        }
    }

    addRequiredParamsAsPrefixedAttributes(request);
    try {
        request.getRequestDispatcher(authPage).forward(request, response);
    } catch (Exception e) {
        logger.error("Could not display authentication page", e);
    }

    return false;
}