Example usage for javax.servlet.http Cookie setMaxAge

List of usage examples for javax.servlet.http Cookie setMaxAge

Introduction

In this page you can find the example usage for javax.servlet.http Cookie setMaxAge.

Prototype

public void setMaxAge(int expiry) 

Source Link

Document

Sets the maximum age in seconds for this Cookie.

Usage

From source file:org.apache.oodt.security.sso.OpenSSOImpl.java

private void addCookie(String name, String val) {
    Cookie userCookie = new Cookie(name, val);
    userCookie.setPath("/");
    userCookie.setMaxAge((int) (System.currentTimeMillis() + (60 * 15)));
    this.res.addCookie(userCookie);
}

From source file:net.sourceforge.vulcan.web.struts.actions.ManagePreferencesAction.java

public ActionForward save(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    final PreferencesForm form = (PreferencesForm) actionForm;

    request.removeAttribute(Keys.PREFERENCES);
    request.getSession().setAttribute(Keys.PREFERENCES, form.getConfig());

    final Cookie cookie = new Cookie(Keys.PREFERENCES, preferencesStore.convertToString(form.getConfig()));
    cookie.setPath(request.getContextPath());
    cookie.setMaxAge(60 * 60 * 24 * 365);

    response.addCookie(cookie);/*from   w  w  w  . j  ava 2s.  co m*/
    return mapping.findForward("dashboard");
}

From source file:com.paperfood.controller.Authenticate.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 *///from  w  w  w.  j a va 2 s  . c om
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    HttpSession session = request.getSession(true);
    JSONObject resp = new JSONObject();
    MD5Hash md5;
    String status = "";
    try {
        md5 = new MD5Hash();
        String req_type = request.getParameter("type");
        if (req_type.equalsIgnoreCase("login")) //Request of Login
        {
            String loginEmail = request.getParameter("loginEmail");
            String loginPass = md5.getStringHash(request.getParameter("loginPass"));
            boolean loginRemember = request.getParameter("loginRemember").equalsIgnoreCase("true");

            DatabaseManager dm = new DatabaseManager();
            dm.open();
            PaperFoodUser user = new PaperFoodUser();
            user = (PaperFoodUser) dm.getLoggedUser(loginEmail, loginPass);
            dm.close();
            if (user != null) //Credentials are valid, create session.
            {
                session.setAttribute("paperfooduseremail", user.getEmail());
                if (loginRemember) {
                    int time = 60 * 60 * 24 * 30;
                    Cookie c = new Cookie("paperfood", user.getEmail());
                    c.setMaxAge(time);
                    response.addCookie(c);
                }
                status = "success";
            } else
                status = "invalid";
        } else if (req_type.equalsIgnoreCase("cookielogin")) //Request for Cookie-based Login.
        {
            String loginEmail = request.getParameter("loginEmail");
            session.setAttribute("paperfooduseremail", loginEmail);
            status = "success";
        } else if (req_type.equalsIgnoreCase("sessionlogin")) //Request for Session-based Login.
        {
            String useremail = (String) session.getAttribute("paperfooduseremail");
            if (useremail != null)
                status = "success";
        } else if (req_type.equalsIgnoreCase("logout")) //Request for Logout.
        {
            session.invalidate();
            Cookie[] c = request.getCookies();
            if (c != null) {
                for (int i = 0; i < c.length; i++) {
                    Cookie curr = c[i];
                    String cnm = curr.getName();
                    if (cnm.equalsIgnoreCase("paperfood")) {
                        curr.setMaxAge(0);
                        response.addCookie(curr);
                    }
                }
            }
            status = "success";
        }
    } catch (CommunicationsException e) {
        status = "unavailable";
    } catch (Exception e) {
        status = "fail";
        e.printStackTrace();
    }

    try {
        resp.put("status", status);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    out.println(resp);
}

From source file:org.apache.oodt.security.sso.OpenSSOImpl.java

private void clearCookie(String name) {
    Cookie userCookie = new Cookie(name, "blank");
    userCookie.setPath("/");
    userCookie.setMaxAge(0);
    this.res.addCookie(userCookie);
}

From source file:edu.ucmerced.cas.web.support.CasShibCookieRetrievingCookieGenerator.java

public void addCookie(final HttpServletRequest request, final HttpServletResponse response,
        final String cookieValue) {
    // instantiate a new CookieGenerator upon every request because the
    // cookie name and path are possibly going to be different for each
    // request/*from w w w.j a  v  a 2s  .  c o m*/
    LocalCookieGenerator cookieGenerator = newCookieGeneratorInstance(request);

    if (!StringUtils.hasText(request.getParameter(RememberMeCredentials.REQUEST_PARAMETER_REMEMBER_ME))) {
        cookieGenerator.addCookie(response, cookieValue);
    } else {
        final Cookie cookie = cookieGenerator.createCookie(cookieValue);
        cookie.setMaxAge(this.rememberMeMaxAge);
        if (cookieGenerator.isCookieSecure()) {
            cookie.setSecure(true);
        }
        response.addCookie(cookie);
    }
}

From source file:fr.gael.dhus.spring.security.handler.LoginSuccessHandler.java

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) {
    String name = authentication.getName();
    try {//from w  w  w .j  ava  2s.co  m
        ValidityAuthentication auth = (ValidityAuthentication) authentication;

        name = EncryptPassword.encrypt(name, PasswordEncryption.MD5);
        Cookie authCookie = new Cookie(CookieKey.AUTHENTICATION_COOKIE_NAME, name);
        authCookie.setPath("/");
        authCookie.setHttpOnly(true);
        authCookie.setMaxAge(-1);

        String validity = auth.getValidity();
        //         Cookie validityCookie = new Cookie (CookieKey.VALIDITY_COOKIE_NAME,
        //             validity);
        //         validityCookie.setPath ("/");
        //         validityCookie.setHttpOnly (true);

        String integrity = EncryptPassword.encrypt(name + validity, PasswordEncryption.SHA1);
        Cookie integrityCookie = new Cookie(CookieKey.INTEGRITY_COOKIE_NAME, integrity);
        integrityCookie.setPath("/");
        integrityCookie.setHttpOnly(true);
        integrityCookie.setMaxAge(-1);

        response.addCookie(authCookie);
        //         response.addCookie (validityCookie);
        response.addCookie(integrityCookie);
        request.getSession().setAttribute("integrity", integrity);
        SecurityContextProvider.saveSecurityContext(integrity, SecurityContextHolder.getContext());
    } catch (Exception e) {
        LOGGER.warn("Authentication process failed ! No cookie was generated", 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  a  v a2s . com
    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);
}

From source file:org.gss_project.gss.server.rest.UserHandler.java

/**
 * Handle POST requests in the users namespace.
 *
  * @param req The servlet request we are processing
  * @param resp The servlet response we are processing
  * @throws IOException if an input/output error occurs
 *//*w ww .  j a v  a  2  s  .  c  o  m*/
void postUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    try {
        final User user = getUser(req);
        User owner = getOwner(req);
        if (!owner.equals(user))
            throw new InsufficientPermissionsException("User " + user.getUsername()
                    + " does not have permission to modify " + owner.getUsername());
        boolean hasResetWebDAVParam = req.getParameterMap().containsKey(RESET_WEBDAV_PARAMETER);
        if (hasResetWebDAVParam) {
            String newPassword = new TransactionHelper<String>().tryExecute(new Callable<String>() {
                @Override
                public String call() throws Exception {
                    return getService().resetWebDAVPassword(user.getId());
                }
            });

            // Set the cookie again to send new value
            Cookie cookie = new Cookie(Login.WEBDAV_COOKIE, newPassword);
            cookie.setMaxAge(-1);
            String domain = req.getRemoteHost();
            String path = req.getContextPath();
            cookie.setDomain(domain);
            cookie.setPath(path);
            resp.addCookie(cookie);
        }
        // Workaround for IE's broken caching behavior.
        resp.setHeader("Expires", "-1");
    } catch (ObjectNotFoundException e) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
    } catch (RpcException e) {
        logger.error("", e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (InsufficientPermissionsException e) {
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, e.getMessage());
    } catch (Exception e) {
        logger.error("", e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:cn.vlabs.duckling.vwb.CPSFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    int advSiteId = Integer.parseInt(StringUtils.defaultIfEmpty(request.getParameter("as"), "-1"));

    if (advSiteId <= 0) {
        chain.doFilter(request, response);
        return;//from  w w w.  jav a 2  s  . c  o  m
    }

    HttpServletResponse rep = (HttpServletResponse) response;
    HttpServletRequest req = (HttpServletRequest) request;
    request.setAttribute("cps", advSiteId);

    Cookie[] cookies = req.getCookies();

    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (StringUtils.equals(CPS_ADV, cookie.getName())) {
                cookie.setPath(req.getContextPath());
                cookie.setMaxAge(0);
            }
        }
    }

    Cookie myCookie = new Cookie(CPS_ADV, advSiteId + "");
    myCookie.setMaxAge(60 * 60 * 24);//
    myCookie.setPath(req.getContextPath());
    rep.addCookie(myCookie);
    chain.doFilter(request, response);
}

From source file:com.baron.bm.controller.MemberController.java

@RequestMapping("/logout") // 
public String logout(HttpServletRequest request, MemberModel model, HttpServletResponse response) {

    for (Cookie cookie : request.getCookies()) {
        if (cookie.getName().equals("bm_id")) {
            cookie.setMaxAge(0);
            model.setId("0");
            response.addCookie(new Cookie("bm_id", model.getId()));
        } else if (cookie.getName().equals("bm_permission")) {
            cookie.setMaxAge(0);/*from  w  ww  . j a va  2 s  .c om*/
            model.setPermission("0");
            response.addCookie(new Cookie("bm_permission", model.getPermission()));
        }
    }
    return "logout";
}