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.sse.abtester.VariantSelectionFilter.java

/**
 * Attach variant selection and publishing to the request processing.
 *
 * @param request the request/*  w ww .j  a  va 2  s  .  c  o m*/
 * @param response the response
 * @param chain the chain
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws ServletException the servlet exception
 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest hReq = (HttpServletRequest) request;
    HttpServletResponse hRes = (HttpServletResponse) response;
    IVariant<VariantBean> theVariant = null;
    IVariationStrategy variationStrategy = null;

    HttpSession session = hReq.getSession();

    if (VM != null) {
        String vsKey = getCookieValue(hReq);
        if (vsKey != "") {
            // has a key, so is enrolled, just update
            // (and get the variant control)
            theVariant = VM.updateVariant(vsKey);
        } else {
            // give opportunity to enroll, map key into a Cookie
            theVariant = VM.enrollRequest(hReq);
            if (theVariant != null)
                vsKey = "" + theVariant.getKey();
            if (vsKey != null && vsKey != "") {
                Cookie cookie = new Cookie(VSKEY, vsKey);
                hRes.addCookie(cookie);
            }
        }
        if (theVariant != null && session != null) {
            variationStrategy = theVariant.getVariationStrategy();
            session.setAttribute(VSKEY, variationStrategy);
        }
    }
    if (variationStrategy == null) {
        variationStrategy = new Default();
        // chain.doFilter(hReq, hRes);
    }
    // attach the variation properties to the HttpSession

    variationStrategy.execute(filterConfig, chain, hReq, hRes);

    // we always offer up the response for pub,
    // even if it wasn't varied
    if (VM != null)
        VM.publishVariationResponse(hRes);
}

From source file:com.spshop.web.ShoppingController.java

@RequestMapping(value = "/logout")
public String logout(Model model, HttpServletRequest request, HttpServletResponse response) {
    request.getSession().invalidate();//from  w ww  .  ja v  a 2 s  .co  m
    model.addAttribute(LOGOUT_ACTION, Boolean.TRUE.toString());
    Cookie[] cookies = request.getCookies();
    if (null != cookies) {
        for (Cookie cookie : cookies) {
            if (COOKIE_ACCOUNT.equals(cookie.getName())) {
                cookie = new Cookie(COOKIE_ACCOUNT, EMPTY_STR);
                cookie.setPath("/");
                cookie.setMaxAge(30 * 24 * 60 * 60);
                response.addCookie(cookie);
            }
        }
    }
    return "redirect:" + getSiteView().getHost();
}

From source file:de.escidoc.core.aa.servlet.Login.java

/**
 * Handles the failure case of a deactivated user account<br> An error page is presented to the user.
 *
 *
 * @param response The http response./* w  w w  . j a  v a2  s.co m*/
 * @throws IOException              Thrown in case of an I/O error.
 * @throws WebserverSystemException Thrown if cookie creation fails due to an internal error.
 */
private void sendDeactivatedUserAccount(final HttpServletResponse response)
        throws IOException, WebserverSystemException {

    response.reset();
    response.setContentType("text/html");

    // delete the session cookie of spring security to allow restarting the
    // login process
    response.addCookie(deleteSpringSecurityCookie());

    sendResponse(response, getDeactivatedUserAccountErrorPage());
}

From source file:com.wavemaker.spinup.web.SpinupController.java

/**
 * Postback method from the login form. Will either re-direct back to the form (in the case of errors) or redirect
 * to start the spinup process./*from  w ww . j  a v  a  2  s .c  o  m*/
 * 
 * @param credentials User credentials
 * @param bindingResult the binding result from the form
 * @param request the HTTP request
 * @param response the HTTP response
 * @return the response (either a redirect to the form or a redirect to the spinup process)
 */
@RequestMapping(value = "/login", method = RequestMethod.POST)
public ModelAndView processLogin(@Valid LoginCredentialsBean credentials, BindingResult bindingResult,
        HttpServletRequest request, HttpServletResponse response) {

    Assert.state(isAjaxRequest(request), "Unable to handle non AJAX post");

    // If we have binding errors, re-render the page
    if (bindingResult.hasErrors()) {
        return new ModelAndView();
    }

    try {
        // Login, add the cookie and redirect to start the spinup process
        this.logger.debug("Starting WaveMaker spinup");
        SharedSecret secret = getSecret(request);
        TransportToken transportToken = this.spinupService.login(secret, credentials);
        this.logger.debug("Login complete");
        String url = performSpinup(credentials, secret, transportToken, response);
        this.logger.debug("Perform spinup complete");
        Cookie cookie = new Cookie(COOKIE_NAME, transportToken.encode());
        cookie.setMaxAge(COOKIE_MAX_AGE);
        cookie.setDomain(this.spinupService.getDomain());
        response.addCookie(cookie);
        response.setHeader("X-Ajax-Redirect", url);
        response.setStatus(HttpStatus.NO_CONTENT.value());
        this.logger.debug("Wavemake spinup complete");
        return null;
    } catch (InvalidLoginCredentialsException e) {
        // On invalid login redirect with a message in flash scope
        return new ModelAndView().addObject("message", "Unable to login, please check your credentials");
    }

}

From source file:iddb.web.security.service.CommonUserService.java

protected void createUserSession(HttpServletRequest request, HttpServletResponse response, Subject subject,
        boolean persistent) {
    HttpSession session = request.getSession(true);
    session.setAttribute(UserService.SUBJECT, subject);
    saveLocal(subject);// w  ww .  j a v a2 s .  co m
    String sessionKey = HashUtils.generate(subject.getLoginId());
    session.setAttribute(UserService.SESSION_KEY, sessionKey);
    Cookie cookieKey = new Cookie("iddb-k", sessionKey);
    Cookie cookieUser = new Cookie("iddb-u", subject.getKey().toString());
    cookieKey.setPath(request.getContextPath() + "/");
    cookieUser.setPath(request.getContextPath() + "/");
    if (persistent) {
        cookieKey.setMaxAge(COOKIE_EXPIRE_REMEMBER);
        cookieUser.setMaxAge(COOKIE_EXPIRE_REMEMBER);
    } else {
        cookieKey.setMaxAge(-1);
        cookieUser.setMaxAge(-1);
    }
    response.addCookie(cookieKey);
    response.addCookie(cookieUser);

    log.trace("Create new session {}, {}, {}",
            new String[] { sessionKey, subject.getKey().toString(), request.getRemoteAddr() });
    createSession(sessionKey, subject.getKey(), request.getRemoteAddr());

}

From source file:org.akaza.openclinica.control.MainMenuServlet.java

public String getQueryStrCookie(HttpServletRequest request, HttpServletResponse response) {
    String queryStr = "";
    Cookie[] cookies = request.getCookies();
    for (Cookie cookie : cookies) {
        if (cookie.getName().equalsIgnoreCase("queryStr")) {
            try {
                queryStr = URLDecoder.decode(cookie.getValue(), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                logger.error("Error decoding redirect URL from queryStr cookie:" + e.getMessage());
            }/*from  w  ww. j  av  a 2s .  co m*/
            cookie.setValue(null);
            cookie.setMaxAge(0);
            cookie.setPath("/");
            if (response != null)
                response.addCookie(cookie);
            break;
        }
    }
    return queryStr;
}

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractHomeController.java

@RequestMapping(value = "/forum", method = RequestMethod.GET)
public String forum(HttpServletResponse response, ModelMap map) {
    logger.debug("###Entering in forum(response,map) method @POST");
    Cookie cookie = new Cookie("JforumSSO", "User" + getCurrentUser().getId());
    cookie.setMaxAge(-1);/*  w w  w.  ja  v a2s. c o  m*/
    cookie.setPath("/");
    response.addCookie(cookie);
    map.addAttribute("forumContext", config.getForumContextPath());
    logger.debug("###Exiting forum(response,map) method @POST");
    return "forum.show";
}

From source file:controllers.UrlController.java

@RequestMapping(value = "/login", method = RequestMethod.POST)
private void logins(HttpServletRequest request, HttpServletResponse response)
        throws SQLException, IOException, Exception {
    User_Manager.User_TblJDBCTemplate user = new User_TblJDBCTemplate();
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    user_detail = user.authenticate(username, password, 1);
    if (user_detail != null) {

        System.out.println("Adding cookie handle" + user_detail.getHandle());
        Cookie cookie = set_Cookie("handle", user_detail.getHandle(), 24);
        response.addCookie(cookie);
        System.out.println("Adding cookie uid" + user_detail.getUid());
        cookie = set_Cookie("uid", String.valueOf(user_detail.getUid()), 24);
        response.addCookie(cookie);/*from  ww  w . ja v  a 2 s .  c  o m*/

        response.sendRedirect("dashboard");

    } else {
        System.out.println("login error");
        response.sendRedirect("index");

    }
}

From source file:com.parleys.server.frontend.web.ipad.filters.LoginFilter.java

@Override
public void doFilter(final ServletRequest req, final ServletResponse response, final FilterChain chain)
        throws IOException {
    final HttpServletResponse res = (HttpServletResponse) response;
    final PrintWriter writer = res.getWriter();
    res.setStatus(HttpServletResponse.SC_OK);
    res.setHeader("Cache-Control", "must-revalidate");
    res.setHeader("Expires", "Fri, 30 Oct 1998 14:19:41 GMT");
    try {//  w  w  w.j a v  a2s. c  o m
        final String username = req.getParameter("username");
        final String password = req.getParameter("password");
        if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) {
            final ParleysService bean = applicationContext.getBean(ParleysService.class);
            final Long userId = bean.getUserId(username, password);

            final String usernameAndPassword = username + ";" + password;
            final String encrypted = AESEncrypter.INSTANCE.encrypt(usernameAndPassword);
            final Cookie rememberMeCookie = new Cookie(PARLEYS_REMEMBER_ME_IPAD, encrypted);
            rememberMeCookie.setMaxAge(3600 * 24 * 7 * 26); // A half year
            res.addCookie(rememberMeCookie);

            writeUserId(writer, userId);
        } else {
            writeError(writer);
        }
    } catch (Exception e) {
        writeError(writer);
    }
}

From source file:org.apache.sling.osgi.obr.OSGiBundleRepositoryServlet.java

private void setCookie(HttpServletResponse res, String name, String value) {
    // make the value URL safe
    try {//from www .  ja  v a 2s  . c o  m
        value = URLEncoder.encode(value, "UTF-8");
    } catch (UnsupportedEncodingException uee) {
        // not really !!
    }

    Cookie cookie = new Cookie(name, value);
    cookie.setMaxAge(-1);
    res.addCookie(cookie);
}