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.third.rent.user.controller.LoginController.java

@RequestMapping(value = "/user/login.do", method = RequestMethod.POST)
public String login_post(@RequestParam String userId, @RequestParam String userPwd,
        @RequestParam(required = false) String chkSaveId, HttpServletRequest request,
        HttpServletResponse response, Model model) {
    // 1/*from  w  ww . ja  v  a 2s .  c o m*/
    logger.info("? , ? userId={} userPwd={}", userId, userPwd);
    logger.info("? chkSaveId={}", chkSaveId);

    // 2
    int result = userService.loginCheck(userId, userPwd);
    logger.info("?  , ? result={}", result);

    String msg = "", url = "/user/login.do";
    if (result == userService.LOGIN_OK) {
        UserVO vo = userService.selectByUserid(userId);

        msg = vo.getUserName() + " ? ?.";
        url = "/user/index.do";

        // ? 
        HttpSession session = request.getSession();
        session.setAttribute("userId", userId);
        session.setAttribute("userName", vo.getUserName());
        session.setAttribute("userLicense", vo.getUserLicense());

        // ? 
        Cookie ck = new Cookie("ck_userId", userId);
        ck.setPath("/");
        // ?  ? 
        if (chkSaveId != null) {
            ck.setMaxAge(1000 * 24 * 60 * 60); // 1000?
            response.addCookie(ck);
        } else {
            ck.setMaxAge(0); //  
            response.addCookie(ck);
        }

    } else if (result == userService.ID_NONE) {
        msg = " ?  .";
    } else if (result == userService.PWD_DISAGREE) {
        msg = " ? ";
    } else {
        msg = "? ? ";
    }
    // 3
    model.addAttribute("msg", msg);
    model.addAttribute("url", url);

    return "common/message";
}

From source file:com.google.gsa.valve.rootAuth.RootAuthorizationProcess.java

/**
 * Deletes all cookies that start with "gsa"
 * // ww  w.  j a  v  a2 s.c o  m
 * @param request HTTP request
 * @param response HTTP response
 */
public void deleteCookies(HttpServletRequest request, HttpServletResponse response) {

    // Retrieve cookies
    Cookie[] allCookies = request.getCookies();
    try {
        // Protection
        if (allCookies != null) {

            // Look for the authentication cookie
            for (int i = 0; i < allCookies.length; i++) {

                logger.debug("Cookie: " + allCookies[i].getName());

                //look for all the cookies start with "gsa" and delete them
                if ((allCookies[i].getName()).startsWith("gsa")) {

                    Cookie gsaCookie = new Cookie(allCookies[i].getName(), allCookies[i].getValue());

                    gsaCookie.setMaxAge(0);

                    response.addCookie(gsaCookie);

                    // Debug
                    if (logger.isDebugEnabled())
                        logger.debug("GSA cookie: [" + gsaCookie.getName() + " has been deleted ]");

                }

            }

        }
    } catch (Exception e) {
        logger.error("Error when deleting cookies: " + e.getMessage(), e);
    }
}

From source file:com.persistent.cloudninja.web.security.CNAuthenticationProcessingFilter.java

@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
        Authentication authResult) throws ServletException, IOException {
    User user = userDetailsService.getCurrentUser();
    String currentCookie = getCookie(request);
    Cookie newCookie = createCookie(user, currentCookie);

    String[] cookievalArray = newCookie.getValue().split("!");
    // get the tenant id
    String tenantId = cookievalArray[1];

    synchronized (userActivityQueue) {
        try {/*from  w  ww . j  av  a2s  . co  m*/
            Calendar calendar = Calendar.getInstance();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S z");
            dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
            String date = dateFormat.format(calendar.getTime());

            UserActivityQueueMessage message;

            message = new UserActivityQueueMessage(cookievalArray[1], cookievalArray[0],
                    dateFormat.parse(date));

            userActivityQueue.add(message);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    // create Cookie containing logo url
    Cookie logoCookie = createLogoCookie(tenantId);

    response.addCookie(newCookie);
    response.addCookie(logoCookie);
    super.successfulAuthentication(request, response, authResult);
}

From source file:com.vmware.identity.samlservice.LogoutState.java

private void removeSessionCookie(String cookieName, HttpServletResponse response) {
    Validate.notNull(response);/*from  w w  w.  j a  v  a 2s  .c om*/
    if (cookieName == null || cookieName.isEmpty()) {
        log.warn("Cookie name is null or empty. Ignoring.");
        return;
    }
    log.debug("Removing cookie " + cookieName);
    Cookie sessionCookie = new Cookie(cookieName, "");
    sessionCookie.setPath("/");
    sessionCookie.setSecure(true);
    sessionCookie.setHttpOnly(true);
    sessionCookie.setMaxAge(0);
    response.addCookie(sessionCookie);
}

From source file:de.kp.ames.web.core.service.ServiceImpl.java

public void sendImageDownloadResponse(ImageUtil image, HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    if (image == null)
        return;// w w  w.j  a  v a2  s  .com

    String clientPath = request.getParameter("clientpath");
    if (clientPath == null)
        return;

    /*
     * Distinguish between secure and non-secure download requests
     */
    if (request.isSecure()) {

        response.addHeader("Cache-Control", "no-cache");
        response.addHeader("Pragma", "no-cache");

        response.addHeader("Expires", "-1");

    } else {

        response.addHeader("Cache-Control", "private");
        response.addHeader("Pragma", "public");

    }

    /*
     * Signal download ready with cookie
     */
    Cookie cookie = new Cookie("DOWNLOAD_READY", "END");
    cookie.setPath(clientPath);
    response.addCookie(cookie);

    /*
     * Determine user agent
     */
    String ua = request.getHeader("User-Agent").toLowerCase();
    boolean isIE = ((ua.indexOf("msie 6.0") != -1) || (ua.indexOf("msie 7.0") != -1)) ? true : false;

    /*
     * Encode file name
     */
    String encFileName = URLEncoder.encode(image.getFilename(), "UTF-8");

    if (isIE) {

        response.addHeader("Content-Disposition", "attachment;  filename=\"" + encFileName + "\"");
        response.addHeader("Connection", "close");

        response.setContentType("application/force-download;  name=\"" + encFileName + "\"");

    } else {

        response.addHeader("Content-Disposition", "attachment; filename=\"" + encFileName + "\"");

        response.setContentType("application/octet-stream; name=\"" + encFileName + "\"");
        response.setContentLength(image.getLength());

    }

    // finally set http status
    response.setStatus(HttpServletResponse.SC_OK);

    OutputStream os = response.getOutputStream();

    os.write(image.getBytes());
    os.close();
}

From source file:edu.hm.muse.controller.Logincontroller.java

@RequestMapping(value = "/adminlogin.secu", method = RequestMethod.POST)
public ModelAndView doAdminLogin(@RequestParam(value = "mpwd", required = false) String mpwd,
        @RequestParam(value = "csrftoken", required = false) String csrfParam, HttpServletResponse response,
        HttpSession session) {/*from  w w  w. ja va 2 s .c om*/
    if (null == mpwd || mpwd.isEmpty()) {
        throw new SuperFatalAndReallyAnnoyingException(
                "I can not process, because the requestparam mpwd is empty or null or something like this");
    }

    String sql = "select count (*) from M_ADMIN where mpwd = ?";

    try {
        String digest = calculateSHA256(new ByteArrayInputStream(mpwd.getBytes("UTF8")));

        int res = 0;

        res = jdbcTemplate.queryForInt(sql, new Object[] { digest }, new int[] { Types.VARCHAR });

        Integer csrfTokenSess = (Integer) session.getAttribute("csrftoken");
        if (res != 0 && csrfParam != null && !csrfParam.isEmpty() && csrfTokenSess != null) {
            Integer csrfParamToken = Integer.parseInt(csrfParam);
            if (csrfParamToken.intValue() == csrfTokenSess.intValue()) {
                SecureRandom random = new SecureRandom();
                int token = random.nextInt();
                session.setAttribute("user", "admin");
                session.setAttribute("login", true);
                session.setAttribute("admintoken", token);
                response.addCookie(new Cookie("admintoken", String.valueOf(token)));
                session.removeAttribute("csrftoken");
                return new ModelAndView("redirect:adminintern.secu");
            }
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    } catch (ClassCastException ccastEx) {
        ccastEx.printStackTrace();
    } catch (NumberFormatException nfoEx) {
        nfoEx.printStackTrace();
    } catch (DataAccessException e) {
        throw new SuperFatalAndReallyAnnoyingException(
                String.format("Sorry but %sis a bad grammar or has following problem %s", sql, e.getMessage()));
    }
    ModelAndView mv = returnToAdminLogin(session);
    return mv;
}

From source file:Controller.login.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from  w  w  w  .  jav a2 s  .c  o  m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    String email = request.getParameter("inputEmail");
    String password = request.getParameter("inputPassword");
    String remember = request.getParameter("remember");

    System.out.println("remember ne mnow " + email);

    LoginImplementation loginCheckObject = new LoginImplementation();

    JSONObject userData = (loginCheckObject.loginNow(email, password, remember));
    System.out.println(userData);
    if (userData.has("error")) {
        RequestDispatcher rd = request.getRequestDispatcher("login.jsp");
        request.setAttribute("loginError", "error");
        rd.include(request, response);

    } else {

        if ("yes".equals(remember)) {
            System.out.println("apples");
            HttpSession session = request.getSession();
            session.setAttribute("user", userData);
            //setting session to expiry in 30 mins
            session.setMaxInactiveInterval(30 * 60);
            Cookie userName = new Cookie("user", email);
            userName.setMaxAge(30 * 60);
            response.addCookie(userName);
        }
        request.setAttribute("userData", userData);
        RequestDispatcher rd = request.getRequestDispatcher("views/home.jsp");
        rd.forward(request, response);
        return;
    }

    out.close();
}

From source file:org.eclipse.userstorage.tests.util.USSServer.java

protected void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
    Map<String, Object> requestObject = JSONUtil.parse(request.getInputStream(), null);

    String username = (String) requestObject.get("username");
    String password = (String) requestObject.get("password");

    User user = users.get(username);/* w ww. j a va2  s  .  co  m*/
    if (user == null || password == null || !password.equals(user.getPassword())) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    }

    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType("application/json");

    Session session = addSession(user);
    Cookie cookie = new Cookie("SESSION", session.getID());
    cookie.setPath("/");
    response.addCookie(cookie);

    Map<String, Object> responseObject = new LinkedHashMap<String, Object>();
    responseObject.put("sessid", session.getID());
    responseObject.put("token", session.getCSRFToken());
    InputStream body = JSONUtil.build(responseObject);

    try {
        ServletOutputStream out = response.getOutputStream();
        IOUtil.copy(body, out);
        out.flush();
    } finally {
        IOUtil.closeSilent(body);
    }
}

From source file:org.apache.oltu.oauth2.client.demo.controller.RedirectController.java

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

    try {/*from ww  w  . ja v  a2 s .c  o m*/

        // 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 state = Utils.findCookieValue(request, "state");

        oauthParams.setClientId(clientId);
        oauthParams.setClientSecret(clientSecret);
        oauthParams.setAuthzEndpoint(authzEndpoint);
        oauthParams.setTokenEndpoint(tokenEndpoint);
        oauthParams.setRedirectUri(redirectUri);
        oauthParams.setScope(Utils.isIssued(scope));
        oauthParams.setState(Utils.isIssued(state));

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

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

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

        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("get_authz");
    }

    return new ModelAndView("request_token");

}

From source file:com.codeabovelab.dm.gateway.proxy.common.HttpProxy.java

/**
 * Copy cookie from the proxy to the servlet client.
 * Replaces cookie path to local path and renames cookie to avoid collisions.
 *//*  w w  w . j a v  a 2s .c o  m*/
private void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
        Header header) {
    List<HttpCookie> cookies = HttpCookie.parse(header.getValue());
    String path = servletRequest.getContextPath(); // path starts with / or is empty string
    path += servletRequest.getServletPath(); // servlet path starts with / or is empty string
    for (int i = 0, l = cookies.size(); i < l; i++) {
        HttpCookie cookie = cookies.get(i);
        //set cookie name prefixed w/ a proxy value so it won't collide w/ other cookies
        String proxyCookieName = getCookieNamePrefix() + cookie.getName();
        Cookie servletCookie = new Cookie(proxyCookieName, cookie.getValue());
        servletCookie.setComment(cookie.getComment());
        servletCookie.setMaxAge((int) cookie.getMaxAge());
        servletCookie.setPath(path); //set to the path of the proxy servlet
        // don't set cookie domain
        servletCookie.setSecure(cookie.getSecure());
        servletCookie.setVersion(cookie.getVersion());
        servletResponse.addCookie(servletCookie);
    }
}