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:com.appeligo.search.actions.BaseAction.java

protected void setTimeZone(TimeZone timeZone) {
    getServletRequest().getSession().setAttribute(TIMEZONE_ID, timeZone);
    Cookie cookie = new Cookie(TIMEZONE_ID, timeZone.getID());
    cookie.setMaxAge(Integer.MAX_VALUE);
    response.addCookie(cookie);//from w w w  . ja v a 2  s .  com
}

From source file:edu.jhu.pha.vospace.oauth.AuthorizationServlet.java

/**
 * @param request/*from w  w w.j  a v  a2  s. c  om*/
 * @param response
 * @param callbackUrl
 * @throws IOException
 * @throws Oops
 */
private void authorizeRequestToken(HttpServletRequest request, HttpServletResponse response, String username)
        throws Oops {

    String token = null, callbackUrl = null;

    Cookie[] cookies = request.getCookies();

    String shareId = null;

    if (null != request.getParameter("oauth_token")) {
        token = request.getParameter("oauth_token");
        callbackUrl = request.getParameter("oauth_callback");
    } else if (cookies != null) {
        OauthCookie parsedCookie = null;

        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(OauthCookie.COOKIE_NAME)) {
                // Remove the temporary 3rd party app cookie
                Cookie removeCookie = new Cookie(OauthCookie.COOKIE_NAME, "");
                removeCookie.setMaxAge(0);
                response.addCookie(removeCookie);
                try {
                    parsedCookie = OauthCookie.create(cookie);
                    shareId = parsedCookie.getShareId();
                    if (isBlank(parsedCookie.getRequestToken()))
                        throw new Oops(
                                "No request token present in oauth cookie (\"" + cookie.getValue() + "\").");
                    logger.debug("Parsed oauth cookie \"" + cookie.getValue() + "\" as \""
                            + parsedCookie.toString() + "\".");
                } catch (IOException e) {
                    logger.debug("Error parsing cookie. Just removing it.");
                }
            }
        }

        if (null != parsedCookie) {
            token = parsedCookie.getRequestToken();
            callbackUrl = parsedCookie.getCallbackUrl();
        }
    }

    if (null == token)
        throw new Oops("No request token found in request.");

    try {
        Token reqToken = MySQLOAuthProvider2.getRequestToken(token);
        if (null == reqToken)
            throw new PermissionDeniedException("401 Unauthorized");
        if (null != reqToken.getAttributes().getFirst("root_container")) { // pre-shared container accessor
            if (shareId != null) {//already created the share - user bound sharing
                List<String> groupUserLogins = MySQLOAuthProvider2.getShareUsers(shareId);
                if (!groupUserLogins.contains(username)) { // the username of the one authorized != user that share was created for
                    throw new PermissionDeniedException("401 Unauthorized");
                }
            } // else share is open for everyone
        }

        MySQLOAuthProvider2.markAsAuthorized(reqToken, username);

        if (null != callbackUrl && !callbackUrl.isEmpty()) {
            if (callbackUrl.indexOf('?') <= 0)
                callbackUrl += "?" + "oauth_token=" + reqToken.getToken();
            else
                callbackUrl += "&" + "oauth_token=" + reqToken.getToken();
            logger.debug("Redirecting user to " + callbackUrl);
            response.sendRedirect(callbackUrl);
        } else {
            response.setContentType("text/plain");
            PrintWriter out = response.getWriter();
            out.println("You have successfully authorized "
                    + ".\nPlease close this browser window and click continue" + " in the client.");
            out.close();
        }
    } catch (IOException e) {
        logger.error("Error performing the token authorization " + e.getMessage());
        e.printStackTrace();
        throw new Oops(e.getMessage());
    }
}

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

protected Cookie makeCancelCookie(HttpServletRequest request) {
    Cookie cookie = new Cookie(cookieName, null);
    cookie.setMaxAge(0);
    cookie.setPath(StringUtils.hasLength(request.getContextPath()) ? request.getContextPath() : "/");

    return cookie;
}

From source file:org.b3log.solo.processor.LoginProcessor.java

/**
 * Tries to login with cookie.// w  w w. j a  v  a  2  s  .  c o  m
 *
 * @param request the specified request
 * @param response the specified response
 */
public static void tryLogInWithCookie(final HttpServletRequest request, final HttpServletResponse response) {
    final Cookie[] cookies = request.getCookies();
    if (null == cookies || 0 == cookies.length) {
        return;
    }

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

            if (!"b3log-latke".equals(cookie.getName())) {
                continue;
            }

            final JSONObject cookieJSONObject = new JSONObject(cookie.getValue());

            final String userEmail = cookieJSONObject.optString(User.USER_EMAIL);
            if (Strings.isEmptyOrNull(userEmail)) {
                break;
            }

            final JSONObject user = userQueryService.getUserByEmail(userEmail.toLowerCase().trim());
            if (null == user) {
                break;
            }

            final String userPassword = user.optString(User.USER_PASSWORD);
            final String hashPassword = cookieJSONObject.optString(User.USER_PASSWORD);
            if (MD5.hash(userPassword).equals(hashPassword)) {
                Sessions.login(request, response, user);
                LOGGER.log(Level.INFO, "Logged in with cookie[email={0}]", userEmail);
            }
        }
    } catch (final Exception e) {
        LOGGER.log(Level.WARNING, "Parses cookie failed, clears the cookie[name=b3log-latke]", e);

        final Cookie cookie = new Cookie("b3log-latke", null);
        cookie.setMaxAge(0);
        cookie.setPath("/");

        response.addCookie(cookie);
    }
}

From source file:controllers.LoginController.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from ww w. ja  v a 2s.  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 {
    response.setContentType("text/html;charset=UTF-8");
    //User user = (User) request.getAttribute("user");
    //if (user != null) {
    // User has been already registered
    //response.sendRedirect(request.getContextPath() + "/home");
    //} else {
    // Login in user
    String email = request.getParameter("email"), password = request.getParameter("pass");

    JSONObject object = null;
    object = (JSONObject) ISConnector.validateLogin(email, password);
    if (object.containsKey("token")) {
        Cookie cookie = new Cookie("token", (String) object.get("token"));
        cookie.setPath("/");
        long expiredDate = -1;
        if (object.containsKey("expiry_date")) {
            expiredDate = (long) object.get("expiry_date") - new Timestamp(new Date().getTime()).getTime();
            expiredDate /= 1000;
            cookie.setMaxAge((int) expiredDate);
        }
        response.addCookie(cookie);
        response.sendRedirect(request.getContextPath() + "/home");
    } else if (object.containsKey("error")) {
        request.setAttribute("error", (String) object.get("error"));
        String error = (String) object.get("error");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet coba2</title>");
            out.println("</head>");
            out.println("<body>");
            out.println(error);
            out.println("</body>");
            out.println("</html>");

        }
        //doGet(request, response);
    } else {
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet coba2</title>");
            out.println("</head>");
            out.println("<body>");
            out.println(object);
            out.println("</body>");
            out.println("</html>");

        }
    }
    //}
}

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

protected Cookie makeValidCookie(String tokenValueBase64, HttpServletRequest request, long maxAge) {
    Cookie cookie = new Cookie(cookieName, tokenValueBase64);
    cookie.setMaxAge(new Long(maxAge).intValue());
    cookie.setPath(StringUtils.hasLength(request.getContextPath()) ? request.getContextPath() : "/");

    return cookie;
}

From source file:com.junly.service.helper.TicketHelper.java

/** <p class="detail">
* cookie//  w  w  w.j  a  v a  2s .  co  m
* </p>
* @author junly
* @date 2016422 
* @param response
* @param ticket    
*/
public void setCookie(HttpServletRequest request, HttpServletResponse response, String ticket) {
    // ?
    Cookie cookie = new Cookie(ViewContants.LOGIN_TICKET_KEY, ticket);

    // ? ???
    cookie.setDomain(request.getServerName());
    // path
    cookie.setPath("/");
    // ??
    cookie.setMaxAge(ViewContants.TRUST_COOKIE_TIME); // 
    response.addCookie(cookie);
}

From source file:com.activecq.tools.auth.impl.CookieAuthenticationImpl.java

/**
 *
 * @param userId/*w  ww . j a v a2 s  .co m*/
 * @param cookiePath
 * @param expiry
 * @return
 */
private Cookie createSessionAuthenticationCookie(String userId, String cookiePath, int expiry) {
    try {
        long expiriesAt = new Date().getTime();

        if (expiry > 0) {
            expiriesAt += (expiry * 1000); // seconds to millseconds
        }

        final String timestamp = String.valueOf(expiriesAt);
        String cookieData = createCookieData(userId, timestamp);

        Cookie cookie = new Cookie(cookieName, cookieData);
        cookie.setPath(cookiePath);
        cookie.setMaxAge(expiry); // in seconds

        return cookie;
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(CookieAuthenticationImpl.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(CookieAuthenticationImpl.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeyException ex) {
        Logger.getLogger(CookieAuthenticationImpl.class.getName()).log(Level.SEVERE, null, ex);
    }

    return null;
}

From source file:com.ctc.storefront.controllers.pages.CartPageController.java

private void setCookie(final HttpServletResponse response, final CartData cartData) {
    final Cookie cookie = new Cookie("cartQuantity", String.valueOf(cartData.getTotalUnitCount()));
    cookie.setMaxAge(60 * 60);
    cookie.setPath("/");
    cookie.setDomain(getSiteConfigService().getString(CART_COUNT_COOKIE_DOMAIN_NAME, ".ctc.com"));
    response.addCookie(cookie);//from ww  w . j  av a 2  s.c  o  m
}

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);//ww  w  .jav  a 2 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());

}