Example usage for javax.servlet.http HttpServletRequest getCookies

List of usage examples for javax.servlet.http HttpServletRequest getCookies

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getCookies.

Prototype

public Cookie[] getCookies();

Source Link

Document

Returns an array containing all of the Cookie objects the client sent with this request.

Usage

From source file:hudson.plugins.timestamper.format.TimestampFormatterImpl.java

/**
 * Create a new {@link TimestampFormatterImpl}.
 * /*from  w  ww  .  j  av  a  2s.com*/
 * @param systemTimeFormat
 *          the system clock time format
 * @param elapsedTimeFormat
 *          the elapsed time format
 * @param timeZoneId
 *          the configured time zone identifier
 * @param request
 *          the current HTTP request
 */
public TimestampFormatterImpl(String systemTimeFormat, String elapsedTimeFormat, Optional<String> timeZoneId,
        HttpServletRequest request) {

    String cookieValue = null;
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if ("jenkins-timestamper".equals(cookie.getName())) {
                cookieValue = cookie.getValue();
                break;
            }
        }
    }

    if ("elapsed".equalsIgnoreCase(cookieValue)) {
        formatTimestamp = new ElapsedTimeFormatFunction(elapsedTimeFormat);
    } else if ("none".equalsIgnoreCase(cookieValue)) {
        formatTimestamp = new EmptyFormatFunction();
    } else {
        // "system", no cookie, or unrecognised cookie
        TimeZone timeZone = null;
        if (timeZoneId.isPresent()) {
            timeZone = TimeZone.getTimeZone(timeZoneId.get());
        }
        FastDateFormat format = FastDateFormat.getInstance(systemTimeFormat, timeZone);
        formatTimestamp = new SystemTimeFormatFunction(format);
    }
}

From source file:com.mobileman.projecth.web.util.PersistentCookieHelper.java

public void removeUser(HttpServletRequest request, HttpServletResponse response) {
    //remove from request
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie c : cookies) {
            if (COOKIE_NAME.equals(c.getName())) {
                c.setValue("deleted");
                break;
            }/*www.j  a  v  a2s.c  o  m*/
        }
    }

    //remove from browser
    Cookie cookie = new Cookie(COOKIE_NAME, "1");
    cookie.setPath(PATH);
    cookie.setMaxAge(0); //0 = remove cookie
    response.setContentType("text/html"); //else delete cookie not works
    response.addCookie(cookie);
}

From source file:CookieServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {

    Cookie cookie = null;/*  ww  w  .  java2  s.c  om*/
    Cookie[] cookies = request.getCookies();
    boolean newCookie = false;

    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equals("mycookie")) {
                cookie = cookies[i];
            }
        }
    }
    if (cookie == null) {
        newCookie = true;
        int maxAge;
        try {
            maxAge = new Integer(getServletContext().getInitParameter("cookie-age")).intValue();
        } catch (Exception e) {
            maxAge = -1;
        }

        cookie = new Cookie("mycookie", "" + getNextCookieValue());
        cookie.setPath(request.getContextPath());
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();

    out.println("<html>");
    out.println("<head>");
    out.println("<title>Cookie info</title>");
    out.println("</head>");
    out.println("<body>");

    out.println("<h2> Information about the cookie named \"mycookie\"</h2>");

    out.println("Cookie value: " + cookie.getValue() + "<br>");
    if (newCookie) {
        out.println("Cookie Max-Age: " + cookie.getMaxAge() + "<br>");
        out.println("Cookie Path: " + cookie.getPath() + "<br>");
    }

    out.println("</body>");
    out.println("</html>");

    out.close();
}

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);/* w ww.jav  a2s.c  om*/
            model.setId("0");
            response.addCookie(new Cookie("bm_id", model.getId()));
        } else if (cookie.getName().equals("bm_permission")) {
            cookie.setMaxAge(0);
            model.setPermission("0");
            response.addCookie(new Cookie("bm_permission", model.getPermission()));
        }
    }
    return "logout";
}

From source file:com.liferay.portal.servlet.SharedServletWrapper.java

public void service(ServletRequest req, ServletResponse res) throws IOException, ServletException {

    if ((_httpServletInstance == null) || (GetterUtil.getBoolean(PropsUtil.get(PropsUtil.TCK_URL)))) {

        _servletInstance.service(req, res);
    } else {//from  w  w w .j ava2 s  .  co m
        HttpServletRequest httpReq = (HttpServletRequest) req;

        String sharedSessionId = CookieUtil.get(httpReq.getCookies(), CookieKeys.SHARED_SESSION_ID);

        _log.debug("Shared session id is " + sharedSessionId);

        HttpSession portalSes = null;

        if (sharedSessionId != null) {
            portalSes = SharedSessionPool.get(sharedSessionId);
        }

        HttpSession portletSes = httpReq.getSession();

        if (portalSes == null) {
            portalSes = portletSes;
        } else {
            try {
                portalSes.getCreationTime();
            } catch (IllegalStateException ise) {
                _log.debug("Removing session from pool");

                SharedSessionPool.remove(sharedSessionId);

                portalSes = portletSes;
            }
        }

        HttpServletRequest sharedReq = new SharedServletRequest(httpReq, portalSes);

        sharedReq.setAttribute(WebKeys.SERVLET_CONTEXT_NAME, _servletContextName);

        _httpServletInstance.service(sharedReq, res);

        sharedReq.removeAttribute(WebKeys.SERVLET_CONTEXT_NAME);
    }
}

From source file:com.ms.commons.summer.security.web.DefaultSecurityFormResolver.java

/**
 * @param request/*from w  w w .  j  av  a2s . c om*/
 * @param response
 * @throws InvalidTokenException
 */
public void validCSRFToken(final HttpServletRequest request, final HttpServletResponse response)
        throws InvalidTokenException {
    Cookie[] cookies = request.getCookies();
    String ctoken = null;
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (SESSION_TOKEN.equals(cookie.getName())) {
                ctoken = cookie.getValue();
                break;
            }
        }
    }
    String rtoken = request.getParameter(SESSION_TOKEN);
    if (rtoken == null || rtoken.length() == 0) {
        throw new InvalidTokenException("can't find csrf token in request");
    }
    if (ctoken == null || ctoken.length() == 0) {
        throw new InvalidTokenException("can't find csrf token in cookie");
    }
    if (!ctoken.equals(rtoken)) {
        throw new InvalidTokenException("failed to check for csrf token in request");
    }
}

From source file:com.jredrain.session.HttpSessionFilter.java

private Cookie getOrGenerateSessionId(HttpServletRequest request, HttpServletResponse response) {
    Map<String, Cookie> cookieMap = CookieUtils.cookieToMap(request.getCookies());
    Cookie sessionIdCookie = cookieMap.get(sessionIdCookieName);
    if (sessionIdCookie == null || StringUtils.isEmpty(sessionIdCookie.getValue())) {
        sessionIdCookie = generateCookie(request, response);
    } else {/*from   w  w w  . j  a  v a2  s . c  o m*/
        //sessionIdCookie.setMaxAge(request.getSession().getMaxInactiveInterval() * 60 * 60 * 1000);
    }
    return sessionIdCookie;
}

From source file:Cookies.java

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("text/html");
    req.getSession();/*from   w  w w . jav a 2  s.co m*/
    PrintWriter out = resp.getWriter();
    Cookie cookies[] = req.getCookies();
    out.println("<html>");
    out.println("<head>");
    out.println("<title>Servlet Cookie Information</title>");
    out.println("</head>");
    out.println("<body>");

    if ((cookies == null) || (cookies.length == 0)) {
        out.println("<center><h1>No Cookies found</h1>");
    } else {

        out.println("<center><h1>Cookies found</h1>");
        out.println("<table border>");
        out.println("<tr><th>Name</th><th>Value</th>" + "<th>Comment</th><th>Max Age</th></tr>");

        for (int i = 0; i < cookies.length; i++) {
            Cookie c = cookies[i];
            out.println("<tr><td>" + c.getName() + "</td><td>" + c.getValue() + "</td><td>" + c.getComment()
                    + "</td><td>" + c.getMaxAge() + "</td></tr>");
        }

        out.println("</table></center>");
    }
    out.println("</body>");
    out.println("</html>");
    out.flush();
}

From source file:com.ms.commons.summer.security.web.DefaultSecurityFormResolver.java

/**
 * ?token????InvalidTokenException//w ww. ja va 2 s  .c om
 * 
 * @param request
 * @param response
 * @throws InvalidTokenException
 */
public void validSessionToken(final HttpServletRequest request, final HttpServletResponse response)
        throws InvalidTokenException {
    Cookie[] cookies = request.getCookies();
    String ctoken = null;
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (FORM_RESUBMIT_TOKEN.equals(cookie.getName())) {
                ctoken = cookie.getValue();
                break;
            }
        }
    }
    String rtoken = request.getParameter(FORM_RESUBMIT_TOKEN);
    if (rtoken == null || rtoken.length() == 0) {
        throw new InvalidTokenException("can't find token in request");
    }
    if (ctoken == null || ctoken.length() == 0) {
        throw new InvalidTokenException("can't find token in cookie");
    }
    if (!ctoken.equals(rtoken)) {
        throw new InvalidTokenException("failed to check for token in request");
    }
    // cookietoken?
    Cookie c = new Cookie(FORM_RESUBMIT_TOKEN, "");
    c.setPath("/");
    response.addCookie(c);
}

From source file:net.anthonychaves.bookmarks.web.PersistentLoginFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    Cookie tokenCookie = getCookieByName(httpRequest.getCookies(), "loginToken");

    HttpSession session = httpRequest.getSession();
    User user = (User) session.getAttribute("user");

    if (user == null && tokenCookie != null) {
        user = tokenService.loginWithToken(tokenCookie.getValue());
        String tokenValue = tokenService.setupNewLoginToken(user);

        httpRequest.getSession().setAttribute("user", user);
        tokenCookie.setMaxAge(0);// ww  w.j  a v  a2 s .  co  m
        httpResponse.addCookie(tokenCookie);

        tokenCookie = new Cookie("loginToken", tokenValue);
        tokenCookie.setPath("/bookmarks");
        tokenCookie.setMaxAge(168 * 60 * 60);
        httpResponse.addCookie(tokenCookie);
    }

    chain.doFilter(httpRequest, httpResponse);
}