Example usage for javax.servlet.http Cookie getName

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

Introduction

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

Prototype

public String getName() 

Source Link

Document

Returns the name of the cookie.

Usage

From source file:com.captaindebug.social.facebookposts.implementation.UserCookieGenerator.java

public String readCookieValue(HttpServletRequest request) {
    Cookie[] cookies = request.getCookies();
    if (cookies == null) {
        return null;
    }//  w w w .  ja  v a 2  s . co  m
    for (Cookie cookie : cookies) {
        if (cookie.getName().equals(cookieGenerator.getCookieName())) {
            return cookie.getValue();
        }
    }
    return null;
}

From source file:com.awt.facebook.account.UserCookieGenerator.java

public String readCookieValue(HttpServletRequest request) {
    Cookie[] cookies = request.getCookies();
    if (cookies == null) {
        return null;
    }//from   w w w  .  j a v  a  2  s .  c  o m
    for (Cookie cookie : cookies) {
        if (cookie.getName().equals(userCookieGenerator.getCookieName())) {
            return cookie.getValue();
        }
    }
    return null;
}

From source file:MyServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    out.println("<HTML>");
    out.println("<HEAD>");
    out.println("<TITLE>");
    out.println("A Web Page");
    out.println("</TITLE>");
    out.println("</HEAD>");
    out.println("<BODY");

    Cookie[] cookies = request.getCookies();
    boolean foundCookie = false;

    for (int i = 0; i < cookies.length; i++) {
        Cookie cookie1 = cookies[i];
        if (cookie1.getName().equals("color")) {
            out.println("bgcolor = " + cookie1.getValue());
            foundCookie = true;//from w w w  .  j a  v  a2s.co m
        }
    }

    if (!foundCookie) {
        Cookie cookie1 = new Cookie("color", "cyan");
        cookie1.setMaxAge(24 * 60 * 60);
        response.addCookie(cookie1);
    }

    out.println(">");
    out.println("<H1>Setting and Reading Cookies</H1>");
    out.println("This page will set its background color using a cookie when reloaded.");
    out.println("</BODY>");
    out.println("</HTML>");
}

From source file:org.impalaframework.extension.mvc.annotation.resolver.CookieValueArgumentResolver.java

protected Object getValue(NativeWebRequest webRequest, String attributeName) {
    HttpServletRequest request = ObjectUtils.cast(webRequest.getNativeRequest(), HttpServletRequest.class);
    final Cookie[] cookies = request.getCookies();
    if (cookies == null) {
        return null;
    }// www .  j av  a 2 s. co  m
    for (Cookie cookie : cookies) {
        final String name = cookie.getName();
        if (name.equals(attributeName)) {
            return cookie.getValue();
        }
    }
    return null;
}

From source file:SettingandReadingCookies.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    out.println("<HTML>");
    out.println("<HEAD>");
    out.println("<TITLE>");
    out.println("A Web Page");
    out.println("</TITLE>");
    out.println("</HEAD>");
    out.println("<BODY");

    Cookie[] cookies = request.getCookies();
    boolean foundCookie = false;

    for (int loopIndex = 0; loopIndex < cookies.length; loopIndex++) {
        Cookie cookie1 = cookies[loopIndex];
        if (cookie1.getName().equals("color")) {
            out.println("bgcolor = " + cookie1.getValue());
            foundCookie = true;//  w  ww.j  a  v a 2s . c o m
        }
    }

    if (!foundCookie) {
        Cookie cookie1 = new Cookie("color", "cyan");
        cookie1.setMaxAge(24 * 60 * 60);
        response.addCookie(cookie1);
    }

    out.println(">");
    out.println("<H1>Setting and Reading Cookies</H1>");
    out.println("This page will set its background color using a cookie when reloaded.");
    out.println("</BODY>");
    out.println("</HTML>");
}

From source file:de.adorsys.oauth.authdispatcher.matcher.RememberMeAuthMatcher.java

private Cookie getCookieToken(String clientId, HttpServletRequest request) {
    Cookie[] cookies = request.getCookies();
    if (cookies == null) {
        return null;
    }//from  w w  w. jav  a2 s .co  m
    for (Cookie cookie : cookies) {
        if (cookie.getName().equals("REMEMBER_" + clientId) && StringUtils.isNotEmpty(cookie.getValue())) {
            return cookie;
        }
    }
    return null;
}

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 a2  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:org.codehaus.groovy.grails.plugins.springsecurity.facebook.FacebookLogoutHandler.java

/**
 * {@inheritDoc}/*from  w w w.j  av a2  s. c o  m*/
 * @see org.springframework.security.ui.logout.LogoutHandler#logout(
 *    javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse,
 *    org.springframework.security.Authentication)
 */
public void logout(final HttpServletRequest request, final HttpServletResponse response,
        final Authentication authentication) {

    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        String path = StringUtils.hasLength(request.getContextPath()) ? request.getContextPath() : "/";
        for (Cookie cookie : cookies) {
            if (cookie.getName().startsWith(_apiKey)) {
                cancelCookie(cookie.getName(), path, response);
            }
        }
    }
}

From source file:org.glassmaker.spring.oauth.OAuth2LogoutFilter.java

protected String getCookieValue(HttpServletRequest request, String cookieName) {
    String cookieValue = null;/*from  w ww.j a  v  a  2  s .  com*/
    Cookie[] cookies = request.getCookies();
    if (cookies != null)
        for (Cookie cookie : cookies)
            if (cookie.getName().equals(cookieName)) {
                cookieValue = cookie.getValue();
                break;
            }
    return cookieValue;
}

From source file:org.orbeon.oxf.util.Connection.java

/**
 * Get header names and values to send given:
 *
 * o the incoming request//w  ww  .  jav  a2  s  .co  m
 * o a list of headers names and values to set
 * o credentials information
 * o a list of headers to forward
 *
 * @param externalContext   context
 * @param indentedLogger    logger or null
 * @param credentials       credentials or null
 * @param headerNameValues  LinkedHashMap<String headerName, String[] headerValues> or null
 * @param headersToForward  headers to forward or null
 * @return LinkedHashMap<String headerName, String[] headerValues>
 */
public static Map<String, String[]> getHeadersMap(ExternalContext externalContext,
        IndentedLogger indentedLogger, Credentials credentials, Map<String, String[]> headerNameValues,
        String headersToForward) {

    final boolean doLog = (indentedLogger != null && indentedLogger.isDebugEnabled());

    // Resulting header names and values to set
    final LinkedHashMap<String, String[]> headersMap = new LinkedHashMap<String, String[]>();

    // Get header forwarding information
    final Map<String, String> headersToForwardMap = getHeadersToForward(headersToForward);

    // Set headers if provided
    if (headerNameValues != null && headerNameValues.size() > 0) {
        for (final Map.Entry<String, String[]> currentEntry : headerNameValues.entrySet()) {
            final String currentHeaderName = currentEntry.getKey();
            final String currentHeaderNameLowercase = currentHeaderName.toLowerCase();
            final String[] currentHeaderValues = currentEntry.getValue();
            // Set header
            headersMap.put(currentHeaderNameLowercase, currentHeaderValues);
            // Remove from list of headers to forward below
            if (headersToForwardMap != null)
                headersToForwardMap.remove(currentHeaderNameLowercase);
        }
    }

    // Forward cookies for session handling
    // NOTE: We use a property, as some app servers like WebLogic allow configuring the session cookie name.
    final String[] cookiesToForward = getForwardCookies();
    if (credentials == null && cookiesToForward.length > 0) {

        // NOTES 2011-01-22:
        //
        // If this is requested when a page is generated, it turns out we cannot rely on a JSESSIONID that makes
        // sense right after authentication, even in the scenario where the JSESSIONID is clean, because Tomcat
        // replays the initial request. In other words the JSESSIONID cookie can be stale.
        //
        // This means that the forwarding done below often doesn't make sense.
        //
        // We could possibly allow it only for XForms Ajax/page updates, where the probability that JSESSIONID is
        // correct is greater.
        //
        // A stronger fix might be to simply disable JSESSIONID forwarding, or support a stronger SSO option.
        //
        // See: http://forge.ow2.org/tracker/?func=detail&atid=350207&aid=315104&group_id=168
        //      https://issues.apache.org/bugzilla/show_bug.cgi?id=50633
        //

        // START "NEW" 2009 ALGORITHM

        // By convention, the first cookie name is the session cookie
        final String sessionCookieName = cookiesToForward[0];

        // 1. If there is an incoming JSESSIONID cookie, use it. The reason is that there is not necessarily an
        // obvious mapping between "session id" and JSESSIONID cookie value. With Tomcat, this works, but with e.g.
        // WebSphere, you get session id="foobar" and JSESSIONID=0000foobar:-1. So we must first try to get the
        // incoming JSESSIONID. To do this, we get the cookie, then serialize it as a header.

        // TODO: ExternalContext must provide direct access to cookies
        final Object nativeRequest = externalContext.getRequest().getNativeRequest();
        boolean sessionCookieSet = false;
        if (nativeRequest instanceof HttpServletRequest) {
            final Cookie[] cookies = ((HttpServletRequest) nativeRequest).getCookies();

            final StringBuilder sb = new StringBuilder();

            if (cookies != null) {

                // Figure out if we need to forward session cookies. We only forward if there is the requested
                // session id is the same as the current session. Otherwise, it means that the current session is no
                // longer valid, or that the incoming cookie is out of date.
                boolean forwardSessionCookies = false;
                final ExternalContext.Session session = externalContext.getSession(false);
                if (session != null) {
                    final String requestedSessionId = externalContext.getRequest().getRequestedSessionId();
                    if (session.getId().equals(requestedSessionId)) {
                        forwardSessionCookies = true;
                    }
                }

                if (forwardSessionCookies) {

                    final List<String> cookiesToForwardAsList = Arrays.asList(cookiesToForward);

                    for (final Cookie cookie : cookies) {
                        // Remember if we've seen the session cookie
                        sessionCookieSet |= cookie.getName().equals(sessionCookieName);

                        if (cookiesToForwardAsList.contains(cookie.getName())) {
                            // Multiple cookies in the header, separated with ";"
                            if (sb.length() > 0)
                                sb.append("; ");

                            sb.append(cookie.getName());
                            sb.append('=');
                            sb.append(cookie.getValue());
                        }
                    }

                    if (sb.length() > 0) {
                        // One or more cookies were set
                        final String cookieString = sb.toString();
                        if (doLog)
                            indentedLogger.logDebug(LOG_TYPE, "forwarding cookies", "cookie", cookieString,
                                    "requested session id",
                                    externalContext.getRequest().getRequestedSessionId());
                        StringConversions.addValueToStringArrayMap(headersMap, "cookie", cookieString);
                    }
                }
            }
        }

        // 2. If there is no incoming session cookie, try to make our own cookie. This may fail with e.g.
        // WebSphere.
        if (!sessionCookieSet) {
            final ExternalContext.Session session = externalContext.getSession(false);

            if (session != null) {

                // This will work with Tomcat, but may not work with other app servers
                StringConversions.addValueToStringArrayMap(headersMap, "cookie",
                        sessionCookieName + "=" + session.getId());

                // All this is for logging!
                if (doLog) {

                    String incomingSessionHeader = null;
                    final String[] cookieHeaders = externalContext.getRequest().getHeaderValuesMap()
                            .get("cookie");
                    if (cookieHeaders != null) {
                        for (final String cookie : cookieHeaders) {
                            if (cookie.contains(sessionCookieName)) {
                                incomingSessionHeader = cookie;
                            }
                        }
                    }

                    String incomingSessionCookie = null;
                    if (nativeRequest instanceof HttpServletRequest) {
                        final Cookie[] cookies = ((HttpServletRequest) externalContext.getRequest()
                                .getNativeRequest()).getCookies();
                        if (cookies != null) {
                            for (final Cookie cookie : cookies) {
                                if (cookie.getName().equals(sessionCookieName)) {
                                    incomingSessionCookie = cookie.getValue();
                                }
                            }
                        }
                    }

                    indentedLogger.logDebug(LOG_TYPE, "setting cookie", "new session",
                            Boolean.toString(session.isNew()), "session id", session.getId(),
                            "requested session id", externalContext.getRequest().getRequestedSessionId(),
                            "session cookie name", sessionCookieName, "incoming session cookie",
                            incomingSessionCookie, "incoming session header", incomingSessionHeader);
                }
            }
        }

        // END "NEW" 2009 ALGORITHM
    }

    // Forward headers if needed
    // NOTE: Forwarding the "Cookie" header may yield unpredictable results because of the above work done w/ session cookies
    if (headersToForwardMap != null) {

        final Map<String, String[]> requestHeaderValuesMap = externalContext.getRequest().getHeaderValuesMap();

        for (final Map.Entry<String, String> currentEntry : headersToForwardMap.entrySet()) {
            final String currentHeaderNameLowercase = currentEntry.getKey();

            // Get incoming header value (Map contains values in lowercase!)
            final String[] currentIncomingHeaderValues = requestHeaderValuesMap.get(currentHeaderNameLowercase);
            // Forward header if present
            if (currentIncomingHeaderValues != null) {
                final boolean isAuthorizationHeader = currentHeaderNameLowercase
                        .equalsIgnoreCase(Connection.AUTHORIZATION_HEADER);
                if (!isAuthorizationHeader || isAuthorizationHeader && credentials == null) {
                    // Only forward Authorization header if there is no credentials provided
                    if (doLog)
                        indentedLogger.logDebug(LOG_TYPE, "forwarding header", "name",
                                currentHeaderNameLowercase, "value",
                                StringUtils.join(currentIncomingHeaderValues, ' '));
                    StringConversions.addValuesToStringArrayMap(headersMap, currentHeaderNameLowercase,
                            currentIncomingHeaderValues);
                } else {
                    // Just log this information
                    if (doLog)
                        indentedLogger.logDebug(LOG_TYPE,
                                "not forwarding Authorization header because credentials are present");
                }
            }
        }
    }

    return headersMap;
}