List of usage examples for javax.servlet.http HttpServletRequest getCookies
public Cookie[] getCookies();
Cookie
objects the client sent with this request. From source file:com.shishu.utility.string.StringUtil.java
public static String getCookie(HttpServletRequest request, String CookieName) throws UnsupportedEncodingException { Cookie cookies[] = request.getCookies(); if (cookies == null) return null; for (int i = 0; i < cookies.length; i++) if (cookies[i].getName().equals(CookieName)) return URLDecoder.decode(cookies[i].getValue(), "utf-8"); return null;// ww w . j a v a2 s .c o m }
From source file:com.vmware.identity.openidconnect.sample.RelyingPartyController.java
private static SessionID getSessionID(HttpServletRequest request) { String sessionIdString = getCookieValue(request.getCookies(), SESSION_COOKIE_NAME, null); return (sessionIdString != null) ? new SessionID(sessionIdString) : null; }
From source file:com.webapp.desc.WebApp.java
/** * Retrieve a login from the current request. * //from ww w .jav a2 s. c o m * @param request The HTTP request containing container session and cookie data * * @return the login associated with the request, or null if the user has not logged into the system with valid credentials. */ public static Login getLogin(HttpServletRequest request) { Login retval = null; HttpSession session = request.getSession(true); try { retval = (Login) session.getAttribute(SESSION_LOGIN_KEY); } catch (Exception e) { LOG.error(e); } // If the login was not in the HTTP session, check for the cookie if (retval == null) { if (request != null) { String sessionid = null; Cookie[] cookies = request.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { if (COOKIE_SESSION_KEY.equals(cookies[i].getName())) { sessionid = cookies[i].getValue(); break; } } if (StringUtil.isNotBlank(sessionid)) { if (securityContext != null) { LOG.trace("Retrieving security session for " + sessionid); Session msession = securityContext.getSession(sessionid); if (msession != null) { // TODO: It might be interesting to ensure that // the servlet session identifier matches data // stored in the security context's session as // an additional check retval = msession.getLogin(); LOG.trace("Using existing session from security context"); } else { LOG.warn("No security session for session ID :" + sessionid); // TODO: Should we clear the cookie since we // lost the session? } } else { LOG.warn("Security Context not set"); } } // session id !null } // cookies !null } // request !null } // login was not stored in the local http session // return what we retrieved return retval; }
From source file:com.zimbra.cs.servlet.ZimbraServlet.java
public static void proxyServletRequest(HttpServletRequest req, HttpServletResponse resp, HttpMethod method, HttpState state) throws IOException, ServiceException { // create an HTTP client with the same cookies javax.servlet.http.Cookie cookies[] = req.getCookies(); String hostname = method.getURI().getHost(); boolean hasZMAuth = hasZimbraAuthCookie(state); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equals(ZimbraCookie.COOKIE_ZM_AUTH_TOKEN) && hasZMAuth) continue; state.addCookie(/*from w w w .j a v a 2 s . co m*/ new Cookie(hostname, cookies[i].getName(), cookies[i].getValue(), "/", null, false)); } } HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient(); if (state != null) client.setState(state); int hopcount = 0; for (Enumeration<?> enm = req.getHeaderNames(); enm.hasMoreElements();) { String hname = (String) enm.nextElement(), hlc = hname.toLowerCase(); if (hlc.equals("x-zimbra-hopcount")) try { hopcount = Math.max(Integer.parseInt(req.getHeader(hname)), 0); } catch (NumberFormatException e) { } else if (hlc.startsWith("x-") || hlc.startsWith("content-") || hlc.equals("authorization")) method.addRequestHeader(hname, req.getHeader(hname)); } if (hopcount >= MAX_PROXY_HOPCOUNT) throw ServiceException.TOO_MANY_HOPS(HttpUtil.getFullRequestURL(req)); method.addRequestHeader("X-Zimbra-Hopcount", Integer.toString(hopcount + 1)); if (method.getRequestHeader("X-Zimbra-Orig-Url") == null) method.addRequestHeader("X-Zimbra-Orig-Url", req.getRequestURL().toString()); String ua = req.getHeader("User-Agent"); if (ua != null) method.setRequestHeader("User-Agent", ua); // dispatch the request and copy over the results int statusCode = -1; for (int retryCount = 3; statusCode == -1 && retryCount > 0; retryCount--) { statusCode = HttpClientUtil.executeMethod(client, method); } if (statusCode == -1) { resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "retry limit reached"); return; } else if (statusCode >= 300) { resp.sendError(statusCode, method.getStatusText()); return; } Header[] headers = method.getResponseHeaders(); for (int i = 0; i < headers.length; i++) { String hname = headers[i].getName(), hlc = hname.toLowerCase(); if (hlc.startsWith("x-") || hlc.startsWith("content-") || hlc.startsWith("www-")) resp.addHeader(hname, headers[i].getValue()); } InputStream responseStream = method.getResponseBodyAsStream(); if (responseStream == null || resp.getOutputStream() == null) return; ByteUtil.copy(method.getResponseBodyAsStream(), false, resp.getOutputStream(), false); }
From source file:flex.messaging.services.http.proxy.RequestFilter.java
/** * Before calling the endpoint, set up the cookies found in the request. * @param context the context//from w ww . java2s .co m */ public static void copyCookiesToEndpoint(ProxyContext context) { HttpServletRequest clientRequest = FlexContext.getHttpRequest(); context.clearRequestCookies(); if (clientRequest != null) { javax.servlet.http.Cookie[] cookies = clientRequest.getCookies(); HttpState initState = context.getHttpClient().getState(); if (cookies != null) { // Gather up the cookies keyed on the length of the path. // This is done so that if we have two cookies with the same name, // we pass the cookie with the longest path first to the endpoint TreeMap cookieMap = new TreeMap(); for (javax.servlet.http.Cookie cookie : cookies) { CookieInfo origCookie = new CookieInfo(cookie.getName(), cookie.getDomain(), cookie.getName(), cookie.getValue(), cookie.getPath(), cookie.getMaxAge(), null, cookie.getSecure()); CookieInfo newCookie = RequestUtil.createCookie(origCookie, context, context.getTarget().getUrl().getHost(), context.getTarget().getUrl().getPath()); if (newCookie != null) { Integer pathInt = Integer.valueOf(0 - newCookie.path.length()); ArrayList list = (ArrayList) cookieMap.get(pathInt); if (list == null) { list = new ArrayList(); cookieMap.put(pathInt, list); } list.add(newCookie); } } // loop through (in order) the cookies we've gathered for (Object mapValue : cookieMap.values()) { ArrayList list = (ArrayList) mapValue; for (Object aList : list) { CookieInfo cookieInfo = (CookieInfo) aList; if (Log.isInfo()) { String str = "-- Cookie in request: " + cookieInfo; Log.getLogger(HTTPProxyService.LOG_CATEGORY).debug(str); } Cookie cookie = new Cookie(cookieInfo.domain, cookieInfo.name, cookieInfo.value, cookieInfo.path, cookieInfo.maxAge, cookieInfo.secure); // If this is a session cookie and we're dealing with local domain, make sure the session // cookie has the latest session id. This check is needed when the session was invalidated // and then recreated in this request; we shouldn't be sending the old session id to the endpoint. if (context.isLocalDomain() && STRING_JSESSIONID.equalsIgnoreCase(cookieInfo.clientName)) { FlexSession flexSession = FlexContext.getFlexSession(); if (flexSession != null && flexSession.isValid()) { String sessionId = flexSession.getId(); String cookieValue = cookie.getValue(); if (!cookieValue.contains(sessionId)) { int colonIndex = cookieValue.indexOf(':'); if (colonIndex != -1) { // Websphere changes jsession id to the following format: // 4 digit cacheId + jsessionId + ":" + cloneId. ServletContext servletContext = FlexContext.getServletContext(); String serverInfo = servletContext != null ? servletContext.getServerInfo() : null; boolean isWebSphere = serverInfo != null && serverInfo.contains("WebSphere"); if (isWebSphere) { String cacheId = cookieValue.substring(0, 4); String cloneId = cookieValue.substring(colonIndex); String wsSessionId = cacheId + sessionId + cloneId; cookie.setValue(wsSessionId); } else { cookie.setValue(sessionId); } } else { cookie.setValue(sessionId); } } } } // finally add the cookie to the current request initState.addCookie(cookie); context.addRequestCookie(cookie); } } } } }
From source file:com.vmware.identity.SharedUtils.java
/** * Create mock request based on the url//from w ww. ja v a2 s .c o m * * @param string * @return * @throws MalformedURLException * @throws UnsupportedEncodingException */ public static HttpServletRequest buildMockRequestObjectFromUrl(String string) throws MalformedURLException, UnsupportedEncodingException { Cookie[] expectedCookies = new Cookie[] {}; URL url = new URL(string); Map<String, String> queryMap = getQueryMap(url.getQuery()); String samlRequestParameter = getParameterFromQueryMap(queryMap, Shared.SAML_REQUEST_PARAMETER); String relayStateParameter = getParameterFromQueryMap(queryMap, Shared.RELAY_STATE_PARAMETER); String sigAlgParameter = getParameterFromQueryMap(queryMap, Shared.SIGNATURE_ALGORITHM_PARAMETER); String signatureParameter = getParameterFromQueryMap(queryMap, Shared.SIGNATURE_PARAMETER); StringBuffer sbRequestUrl = new StringBuffer(); sbRequestUrl.append(string.replace("?" + url.getQuery(), "")); // build mock request object HttpServletRequest request = createMock(HttpServletRequest.class); expect(request.getCookies()).andReturn(expectedCookies).anyTimes(); expect(request.getParameter(Shared.SAML_REQUEST_PARAMETER)).andReturn(samlRequestParameter).anyTimes(); expect(request.getParameter(Shared.RELAY_STATE_PARAMETER)).andReturn(relayStateParameter).anyTimes(); expect(request.getParameter(Shared.SIGNATURE_ALGORITHM_PARAMETER)).andReturn(sigAlgParameter).anyTimes(); expect(request.getParameter(Shared.SIGNATURE_PARAMETER)).andReturn(signatureParameter).anyTimes(); expect(request.getRequestURL()).andReturn(sbRequestUrl).anyTimes(); expect(request.getParameter(Shared.REQUEST_AUTH_PARAM)).andReturn(TestConstants.AUTHORIZATION).anyTimes(); String queryString = Shared.SAML_REQUEST_PARAMETER + "=" + samlRequestParameter; if (relayStateParameter != null) { queryString = queryString + "&" + Shared.RELAY_STATE_PARAMETER + "=" + relayStateParameter; } if (sigAlgParameter != null) { queryString = queryString + "&" + Shared.SIGNATURE_ALGORITHM_PARAMETER + "=" + sigAlgParameter; } if (signatureParameter != null) { queryString = queryString + "&" + Shared.SIGNATURE_PARAMETER + "=" + signatureParameter; } expect(request.getQueryString()).andReturn(queryString).anyTimes(); replay(request); return request; }
From source file:com.vmware.identity.SharedUtils.java
public static HttpServletRequest buildMockRequestObject(SignableSAMLObject samlObject, String relayStateParameter, String sigAlg, String signature, StringBuffer sbRequestUrl, String authorization, String sessionId, int tenantId) throws MarshallingException, IOException { Cookie[] expectedCookies = new Cookie[] {}; String tenant = ServerConfig.getTenant(tenantId); if (sessionId != null) { expectedCookies = new Cookie[] { new Cookie(Shared.getTenantSessionCookieName(tenant), sessionId) }; }/*ww w . j av a 2 s . co m*/ // build mock request object HttpServletRequest request = createMock(HttpServletRequest.class); expect(request.getCookies()).andReturn(expectedCookies).anyTimes(); if (samlObject instanceof LogoutResponse) { expect(request.getParameter(Shared.SAML_RESPONSE_PARAMETER)) .andReturn(SharedUtils.encodeRequest(samlObject)).anyTimes(); expect(request.getParameter(Shared.SAML_REQUEST_PARAMETER)).andReturn(null).anyTimes(); } else { expect(request.getHeader(Shared.IWA_AUTH_REQUEST_HEADER)).andReturn(null).anyTimes(); expect(request.getParameter(Shared.SAML_REQUEST_PARAMETER)) .andReturn(SharedUtils.encodeRequest(samlObject)).anyTimes(); expect(request.getParameter(Shared.SAML_RESPONSE_PARAMETER)).andReturn(null).anyTimes(); } expect(request.getParameter(Shared.RELAY_STATE_PARAMETER)).andReturn(relayStateParameter).anyTimes(); expect(request.getParameter(Shared.SIGNATURE_ALGORITHM_PARAMETER)).andReturn(sigAlg).anyTimes(); expect(request.getParameter(Shared.SIGNATURE_PARAMETER)).andReturn(signature).anyTimes(); expect(request.getRequestURL()).andReturn(sbRequestUrl).anyTimes(); expect(request.getParameter(Shared.REQUEST_AUTH_PARAM)).andReturn(authorization).anyTimes(); String queryString = Shared.SAML_REQUEST_PARAMETER + "=" + SharedUtils.encodeRequest(samlObject); if (relayStateParameter != null) { queryString = queryString + "&" + Shared.RELAY_STATE_PARAMETER + "=" + relayStateParameter; } if (sigAlg != null) { queryString = queryString + "&" + Shared.SIGNATURE_ALGORITHM_PARAMETER + "=" + sigAlg; } if (signature != null) { queryString = queryString + "&" + Shared.SIGNATURE_PARAMETER + "=" + signature; } expect(request.getQueryString()).andReturn(queryString).anyTimes(); replay(request); return request; }
From source file:org.jruby.rack.mock.WebUtils.java
/** * Retrieve the first cookie with the given name. Note that multiple * cookies can have the same name but different paths or domains. * @param request current servlet request * @param name cookie name//w w w. j a va 2 s . c om * @return the first cookie with the given name, or {@code null} if none is found */ public static Cookie getCookie(HttpServletRequest request, String name) { Assert.notNull(request, "Request must not be null"); Cookie cookies[] = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (name.equals(cookie.getName())) { return cookie; } } } return null; }
From source file:org.alfresco.web.app.servlet.AuthenticationHelper.java
/** * Helper to return the Alfresco auth cookie. The cookie saves the last used username value. * /*from ww w.j a v a2 s.c o m*/ * @param httpRequest * * @return Cookie if found or null if not present */ public static Cookie getAuthCookie(HttpServletRequest httpRequest) { if (logger.isDebugEnabled()) logger.debug("Searching for Alfresco auth cookie."); Cookie authCookie = null; Cookie[] cookies = httpRequest.getCookies(); if (cookies != null) { if (logger.isDebugEnabled()) logger.debug("Cookies present."); for (int i = 0; i < cookies.length; i++) { if (COOKIE_ALFUSER.equals(cookies[i].getName())) { // found cookie if (logger.isDebugEnabled()) logger.debug("Found Alfresco auth cookie: " + cookies[i].toString()); authCookie = cookies[i]; break; } } } return authCookie; }
From source file:no.sesat.search.http.filters.SiteLocatorFilter.java
private static String getCookieValue(final HttpServletRequest request, final String cookieName) { String value = ""; // Look in attributes (it could have already been updated this request) if (null != request) { // Look through cookies if (null != request.getCookies()) { for (Cookie c : request.getCookies()) { if (c.getName().equals(cookieName)) { value = c.getValue(); break; }//from w w w. j a v a 2 s. c o m } } } return value; }