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:org.codemucker.testserver.capturing.CapturedRequest.java

public CapturedRequest(final HttpServletRequest req) {
    scheme = req.getScheme();/* w w  w  . jav  a 2s. c  o m*/
    host = req.getServerName();
    port = req.getServerPort();
    contextPath = req.getContextPath();
    servletPath = req.getServletPath();
    pathInfo = req.getPathInfo();
    characterEncoding = req.getCharacterEncoding();
    method = req.getMethod();
    final Cookie[] cookies = req.getCookies();

    // cookies
    if (cookies != null) {
        for (final Cookie cookie : cookies) {
            this.cookies.add(new CapturedCookie(cookie));
        }
    }
    // headers
    for (@SuppressWarnings("unchecked")
    final Enumeration<String> names = req.getHeaderNames(); names.hasMoreElements();) {
        final String name = names.nextElement();
        @SuppressWarnings("unchecked")
        final Enumeration<String> values = req.getHeaders(name);
        if (values != null) {
            for (; values.hasMoreElements();) {
                this.addHeader(new CapturedHeader(name, values.nextElement()));
            }
        }
    }
    // if we use the normal 'toString' on maps, and arrays, we get pretty
    // poor results
    // Use ArrayLists instead to get a nice output
    @SuppressWarnings("unchecked")
    final Map<String, String[]> paramMap = req.getParameterMap();
    if (paramMap != null) {
        for (final String key : paramMap.keySet()) {
            final String[] vals = paramMap.get(key);
            this.parameters.put(key, new ArrayList<String>(Arrays.asList(vals)));
        }
    }
    // handle multipart posts
    if (ServletFileUpload.isMultipartContent(req)) {
        // Create a factory for disk-based file items
        final FileItemFactory factory = new DiskFileItemFactory();

        // Create a new file upload handler
        final ServletFileUpload upload = new ServletFileUpload(factory);

        try {
            @SuppressWarnings("unchecked")
            final List<FileItem> items = upload.parseRequest(req);
            for (final FileItem item : items) {
                fileItems.add(new CapturedFileItem(item));
            }
        } catch (final FileUploadException e) {
            throw new RuntimeException("Error handling multipart content", e);
        }
    }

}

From source file:com.google.identitytoolkit.GitkitClient.java

/**
 * Verifies Gitkit token in http request.
 *
 * @param request http request//  w w  w. j a  va 2  s .  co  m
 * @return Gitkit user if valid token is found in the request.
 * @throws GitkitClientException if there is token but signature is invalid
 */
public GitkitUser validateTokenInRequest(HttpServletRequest request) throws GitkitClientException {
    Cookie[] cookies = request.getCookies();
    if (cookieName == null || cookies == null) {
        return null;
    }

    for (Cookie cookie : cookies) {
        if (cookieName.equals(cookie.getName())) {
            return validateToken(cookie.getValue());
        }
    }
    return null;
}

From source file:es.pode.soporte.seguridad.openId.ui.openid.PreviousProcessingFilter.java

/**
 * Devuelve el valor de la cookie de OpenId
 * @param ServletRequest //from  w ww  . j av  a2s  .  c  o  m
 * @param ServletResponse
 * @param nombreCookie
*/
private String getCookieValor(HttpServletRequest request, String nombreCookie) {
    Cookie cookie = null;
    String valor = null;

    if (log.isDebugEnabled())
        log.debug("Se coge la cookie " + nombreCookie);
    cookie = getCookie(nombreCookie, request.getCookies());
    valor = cookie.getValue();
    if (log.isDebugEnabled())
        log.debug("Valor cookie:" + valor);
    return valor;
}

From source file:grails.plugin.cookielayout.CookiePageLayoutFinder.java

private String getLayoutFromCookie(HttpServletRequest request, String cookieName) {
    if (checkRequest) {
        final Object requestLayout = request.getAttribute(cookieName);
        if (requestLayout != null) {
            return requestLayout.toString();
        }/*  w  ww . j av a2  s .c  o m*/
    }
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie c : cookies) {
            if (c.getName().equals(cookieName)) {
                return c.getValue();
            }
        }
    }
    return "";
}

From source file:eu.trentorise.smartcampus.permissionprovider.controller.CookieCleaner.java

public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws IOException, ServletException {
    for (String s : cookieNames) {
        Cookie cookie = new Cookie(s, null);
        cookie.setPath("/");
        cookie.setMaxAge(0);/*from www  .ja v a 2s .  com*/
        response.addCookie(cookie);

        cookie = new Cookie(s, null);
        cookie.setPath(request.getContextPath() + "/eauth/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }

    if (request.getCookies() != null) {
        for (int i = 0; i < request.getCookies().length; i++) {
            Cookie cookie = request.getCookies()[i];
            for (String s : cookieNames) {
                if (cookie.getName().startsWith(s)) {
                    cookie = new Cookie(cookie.getName(), null);
                    cookie.setPath("/");
                    cookie.setMaxAge(0);
                    response.addCookie(cookie);

                    cookie = new Cookie(cookie.getName(), null);
                    cookie.setPath(request.getContextPath() + "/eauth/");
                    cookie.setMaxAge(0);
                    response.addCookie(cookie);
                }
            }
        }
    }
    request.getSession().invalidate();
    if (authentication != null)
        authentication.setAuthenticated(false);
    response.sendRedirect(request.getContextPath() + redirect);
}

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

public Authentication autoLogin(HttpServletRequest request, HttpServletResponse response) {
    Cookie[] cookies = request.getCookies();

    if ((cookies == null) || (cookies.length == 0)) {
        return null;
    }/*www .ja v  a 2 s .  c  o  m*/

    for (int i = 0; i < cookies.length; i++) {
        if (cookieName.equals(cookies[i].getName())) {
            String cookieValue = cookies[i].getValue();

            for (int j = 0; j < cookieValue.length() % 4; j++) {
                cookieValue = cookieValue + "=";
            }

            if (Base64.isArrayByteBase64(cookieValue.getBytes())) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Remember-me cookie detected");
                }

                // Decode token from Base64
                // format of token is:
                // username + ":" + expiryTime + ":" +
                // Md5Hex(username + ":" + expiryTime + ":" + password + ":"
                // + key)
                String cookieAsPlainText = new String(Base64.decodeBase64(cookieValue.getBytes()));
                String[] cookieTokens = StringUtils.delimitedListToStringArray(cookieAsPlainText, ":");

                if (cookieTokens.length == 3) {

                    long tokenExpiryTime;

                    try {
                        tokenExpiryTime = new Long(cookieTokens[1]).longValue();
                    } catch (NumberFormatException nfe) {
                        cancelCookie(request, response,
                                "Cookie token[1] did not contain a valid number (contained '" + cookieTokens[1]
                                        + "')");

                        return null;
                    }

                    if (isTokenExpired(tokenExpiryTime)) {
                        cancelCookie(request, response, "Cookie token[1] has expired (expired on '"
                                + new Date(tokenExpiryTime) + "'; current time is '" + new Date() + "')");

                        return null;
                    }

                    // Check the user exists
                    // Defer lookup until after expiry time checked, to
                    // possibly avoid expensive lookup
                    UserDetails userDetails = loadUserDetails(request, response, cookieTokens);

                    if (userDetails == null) {
                        cancelCookie(request, response, "Cookie token[0] contained username '" + cookieTokens[0]
                                + "' but was not found");
                        return null;
                    }

                    if (!isValidUserDetails(request, response, userDetails, cookieTokens)) {
                        return null;
                    }

                    // Check signature of token matches remaining details
                    // Must do this after user lookup, as we need the
                    // DAO-derived password
                    // If efficiency was a major issue, just add in a
                    // UserCache implementation,
                    // but recall this method is usually only called one per
                    // HttpSession
                    // (as if the token is valid, it will cause
                    // SecurityContextHolder population, whilst
                    // if invalid, will cause the cookie to be cancelled)
                    String expectedTokenSignature = makeTokenSignature(tokenExpiryTime, userDetails);

                    if (!expectedTokenSignature.equals(cookieTokens[2])) {
                        cancelCookie(request, response, "Cookie token[2] contained signature '"
                                + cookieTokens[2] + "' but expected '" + expectedTokenSignature + "'");

                        return null;
                    }

                    // By this stage we have a valid token
                    if (logger.isDebugEnabled()) {
                        logger.debug("Remember-me cookie accepted");
                    }

                    RememberMeAuthenticationToken auth = new RememberMeAuthenticationToken(this.key,
                            userDetails, userDetails.getAuthorities());
                    auth.setDetails(authenticationDetailsSource.buildDetails((HttpServletRequest) request));

                    return auth;
                } else {
                    cancelCookie(request, response, "Cookie token did not contain 3 tokens; decoded value was '"
                            + cookieAsPlainText + "'");

                    return null;
                }
            } else {
                cancelCookie(request, response,
                        "Cookie token was not Base64 encoded; value was '" + cookieValue + "'");

                return null;
            }
        }
    }

    return null;
}

From source file:es.pode.soporte.seguridad.openId.ui.openid.PreviousProcessingFilter.java

/**
 * Actualiza el timeout de la cookie de OpenId
 * @param ServletRequest /*from   w  w w.j  ava 2  s. co m*/
 * @param ServletResponse
 * @param nombreCookie
 * @throws IOException
*/
private void actualizaCookie(HttpServletRequest request, HttpServletResponse response, String nombreCookie)
        throws IOException {
    Cookie cookie = null;
    if (log.isDebugEnabled())
        log.debug("Se coge la cookie " + nombreCookie);
    cookie = getCookie(nombreCookie, request.getCookies());
    int caducidadCookie = (new Integer(this.getAgregaPropertyValue(AgregaProperties.TIMEOUTCOOKIEOPENID)))
            .intValue();
    if (log.isDebugEnabled())
        log.debug("caducidadCookie " + caducidadCookie);
    cookie.setMaxAge(caducidadCookie);
    cookie.setPath("/");
    response.addCookie(cookie);
}

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

@Override
public Subject findUserSession(HttpServletRequest request) {
    HttpSession session = request.getSession(false);
    Subject s = null;/*from   w w w .  jav a  2s . c o  m*/
    if (session != null) {
        s = (Subject) session.getAttribute(SUBJECT);
    }
    if (s == null) {
        log.trace("Lookup cookie trace");
        String sessionKey = null;
        String sessionUser = null;
        sessionKey = getCookie(request.getCookies(), "iddb-k");
        if (sessionKey != null) {
            sessionUser = getCookie(request.getCookies(), "iddb-u");
        }
        if (sessionKey != null && sessionUser != null) {
            log.trace("Found cookie trace");
            Session localSession = null;
            try {
                localSession = findSession(sessionKey, Long.parseLong(sessionUser), request.getRemoteAddr());
            } catch (NumberFormatException e) {
                log.error(e.getMessage());
            }
            if (localSession != null) {
                if (localSession.getCreated().before(DateUtils.addDays(new Date(), SESSION_LIFE))) {
                    log.trace("Found valid session");
                    s = findUser(localSession.getUserId());
                    if (s != null) {
                        session = request.getSession(true);
                        session.setAttribute(SUBJECT, s);
                        session.setAttribute(SESSION_KEY, localSession.getKey());
                    }
                } else {
                    log.trace("Session expired");
                }
            }
        }
    } else {
        log.trace("Using subject from session");
    }
    if (s != null)
        saveLocal(s);
    return s;
}

From source file:com.google.ie.web.controller.UserController.java

/**
 * Retrieve the value of friend connect authorization cookie from the
 * request.//from   www.  jav  a 2  s .  co m
 * 
 * @param request
 * @return
 */
private String getAuthToken(HttpServletRequest request) {
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            Cookie cookie = cookies[i];
            if (cookie != null && cookie.getName().equals(getFcauthCookieName())) {
                return cookie.getValue();
            }
        }
    }
    if (isDebugEnabled) {
        LOGGER.debug("The cookie " + getFcauthCookieName() + " was not found ");
    }
    return null;
}

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

public String getTimeoutReturnToCookie(HttpServletRequest request, HttpServletResponse response) {
    String queryStr = "";
    if (ub == null || StringUtils.isEmpty(ub.getName()))
        return queryStr;

    Cookie[] cookies = request.getCookies();
    for (Cookie cookie : cookies) {
        if (cookie.getName().equalsIgnoreCase("bridgeTimeoutReturn-" + ub.getName())) {
            try {
                queryStr = URLDecoder.decode(cookie.getValue(), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                logger.error("Error decoding redirect URL from queryStr cookie:" + e.getMessage());
            }//from w w  w  . ja  va 2s .c om
            cookie.setValue(null);
            cookie.setMaxAge(0);
            cookie.setPath("/");
            if (response != null)
                response.addCookie(cookie);
            break;
        }
    }
    return queryStr;
}