List of usage examples for javax.servlet.http HttpServletRequest getCookies
public Cookie[] getCookies();
Cookie
objects the client sent with this request. From source file:eionet.webq.web.interceptor.CdrAuthorizationInterceptor.java
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String authorization = request.getHeader(AUTHORIZATION_HEADER); // if (true) return PROCEED; if (StringUtils.isNotEmpty(authorization) || request.getParameter("auth") != null) { // if Basic auth is present in the request, then try to log in to CDR to test if it is valid token for given domain. // "auth" parameter is just meant for testing the CDR API in development environment - WebQ asks to authenticate. HttpHeaders headers = new HttpHeaders(); headers.add(AUTHORIZATION_HEADER, authorization); // return PROCEED; try {//from w ww. j a v a 2 s . co m ResponseEntity<String> loginResponse = restOperations.postForEntity( extractCdrUrl(request) + "/" + cdrLoginMethod, new HttpEntity<Object>(headers), String.class); LOGGER.info("Response code received from CDR basic authorization request " + loginResponse.getStatusCode()); return PROCEED; } catch (HttpStatusCodeException e) { if (e.getStatusCode() != HttpStatus.UNAUTHORIZED) { LOGGER.warn("Authorization against CDR failed with unexpected HTTP status code", e); } } } else { // if Basic auth is not present, then test if user is already authorised in this domain // by using provided cookies to fetch CDR envelope properties page. Cookie[] cookies = request.getCookies(); if (cookies != null) { HttpHeaders headers = new HttpHeaders(); for (Cookie cookie : cookies) { // put ZopeId parameter to request header. It works only when the value is surrounded with quotes. headers.add("Cookie", cookiesConverter.convertCookieToString(cookie)); } String urlToFetch = extractCdrEnvelopeUrl(request) + "/" + cdrEnvelopePropertiesMethod; //ResponseEntity<String> loginResponse = restOperations.exchange(urlToFetch, HttpMethod.GET, // new HttpEntity<Object>(headers), String.class); HttpResponse responseFromCdr = fetchUrlWithoutRedirection(urlToFetch, headers); try { int statusCode = responseFromCdr.getStatusLine().getStatusCode(); LOGGER.info("Response code received from CDR envelope request using cookies " + statusCode); if (statusCode == HttpStatus.OK.value()) { request.setAttribute(PARSED_COOKIES_ATTRIBUTE, cookiesConverter.convertCookiesToString(cookies)); return PROCEED; } else if ((statusCode == HttpStatus.MOVED_PERMANENTLY.value() || statusCode == HttpStatus.MOVED_TEMPORARILY.value()) && responseFromCdr.getFirstHeader("Location") != null) { // redirect to CDR login page String redirectUrl = extractCdrUrl(request) + responseFromCdr.getFirstHeader("Location").getValue(); LOGGER.info("Redirect to " + redirectUrl); response.sendRedirect(redirectUrl); } } catch (HttpStatusCodeException e) { if (e.getStatusCode() != HttpStatus.UNAUTHORIZED) { LOGGER.warn("Fetching CDR envelope page failed with unexpected HTTP status code", e); } } } } if (isFailureCountsEqualsToAllowedFailuresCount()) { request.setAttribute(AUTHORIZATION_FAILED_ATTRIBUTE, AUTHORIZATION_FAILED_ATTRIBUTE); session.removeAttribute(AUTHORIZATION_TRY_COUNT); return PROCEED; } increaseFailedAuthorizationsCount(); response.addHeader("WWW-Authenticate", "Basic realm=\"Please login to use webforms.\""); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return STOP_REQUEST_PROPAGATION; }
From source file:com.ibm.jaggr.core.impl.transport.AbstractHttpTransport.java
/** * This method checks the request for the has conditions which may either be contained in URL * query arguments or in a cookie sent from the client. * * @param request//from w w w. j a va 2 s . c o m * the request object * @return The has conditions from the request. * @throws IOException * @throws UnsupportedEncodingException */ protected String getHasConditionsFromRequest(HttpServletRequest request) throws IOException { final String sourceMethod = "getHasConditionsFromRequest"; //$NON-NLS-1$ boolean isTraceLogging = log.isLoggable(Level.FINER); if (isTraceLogging) { log.entering(AbstractHttpTransport.class.getName(), sourceMethod, new Object[] { request }); } String ret = null; if (request.getParameter(FEATUREMAPHASH_REQPARAM) != null) { // The cookie called 'has' contains the has conditions if (isTraceLogging) { log.finer("has hash = " + request.getParameter(FEATUREMAPHASH_REQPARAM)); //$NON-NLS-1$ } Cookie[] cookies = request.getCookies(); if (cookies != null) { for (int i = 0; ret == null && i < cookies.length; i++) { Cookie cookie = cookies[i]; if (cookie.getName().equals(FEATUREMAP_REQPARAM) && cookie.getValue() != null) { if (isTraceLogging) { log.finer("has cookie = " + cookie.getValue()); //$NON-NLS-1$ } ret = URLDecoder.decode(cookie.getValue(), "US-ASCII"); //$NON-NLS-1$ break; } } } if (ret == null) { if (log.isLoggable(Level.WARNING)) { StringBuffer url = request.getRequestURL(); if (url != null) { // might be null if using mock request for unit testing url.append("?").append(request.getQueryString()).toString(); //$NON-NLS-1$ log.warning(MessageFormat.format(Messages.AbstractHttpTransport_0, new Object[] { url, request.getHeader("User-Agent") })); //$NON-NLS-1$ } } } } else { ret = request.getParameter(FEATUREMAP_REQPARAM); if (isTraceLogging) { log.finer("reading features from has query arg"); //$NON-NLS-1$ } } if (isTraceLogging) { log.exiting(AbstractHttpTransport.class.getName(), sourceMethod, ret); } return ret; }
From source file:org.esigate.servlet.impl.RequestFactory.java
public IncomingRequest create(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException { HttpServletRequestContext context = new HttpServletRequestContext(request, response, servletContext, filterChain);/*from w w w. j a va2 s.c om*/ // create request line String uri = UriUtils.createURI(request.getScheme(), request.getServerName(), request.getServerPort(), request.getRequestURI(), request.getQueryString(), null); ProtocolVersion protocolVersion = BasicLineParser.parseProtocolVersion(request.getProtocol(), null); IncomingRequest.Builder builder = IncomingRequest .builder(new BasicRequestLine(request.getMethod(), uri, protocolVersion)); builder.setContext(context); // copy headers @SuppressWarnings("rawtypes") Enumeration names = request.getHeaderNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); @SuppressWarnings("rawtypes") Enumeration values = request.getHeaders(name); while (values.hasMoreElements()) { String value = (String) values.nextElement(); builder.addHeader(name, value); } } // create entity HttpServletRequestEntity entity = new HttpServletRequestEntity(request); builder.setEntity(entity); builder.setRemoteAddr(request.getRemoteAddr()); builder.setRemoteUser(request.getRemoteUser()); HttpSession session = request.getSession(false); if (session != null) { builder.setSessionId(session.getId()); } builder.setUserPrincipal(request.getUserPrincipal()); // Copy cookies // As cookie header contains only name=value so we don't need to copy // all attributes! javax.servlet.http.Cookie[] src = request.getCookies(); if (src != null) { for (int i = 0; i < src.length; i++) { javax.servlet.http.Cookie c = src[i]; BasicClientCookie dest = new BasicClientCookie(c.getName(), c.getValue()); builder.addCookie(dest); } } builder.setSession(new HttpServletSession(request)); builder.setContextPath(request.getContextPath()); return builder.build(); }
From source file:org.sakaiproject.entitybroker.util.http.EntityHttpServletRequest.java
/** * Set all the values from a request on this request object and set this request * as the one which the values were copied from * @param req any request/*from ww w. j a v a 2 s . c om*/ */ public void setRequestValues(HttpServletRequest req) { if (req == null) { throw new IllegalArgumentException("request cannot be null"); } // get the collections of values out Enumeration<String> attribNames = req.getAttributeNames(); while (attribNames.hasMoreElements()) { String name = (String) attribNames.nextElement(); Object obj = req.getAttribute(name); if (obj != null) { attributes.put(name, obj); } } Cookie[] ck = req.getCookies(); if (ck != null) { for (int i = 0; i < ck.length; i++) { cookies.add(ck[i]); } } Enumeration<String> headerNames = req.getHeaderNames(); while (headerNames.hasMoreElements()) { String name = headerNames.nextElement(); Enumeration<String> henum = req.getHeaders(name); Vector<String> v = new Vector<String>(1); while (henum.hasMoreElements()) { String h = henum.nextElement(); v.add(h); } } for (Entry<String, String[]> entry : (Set<Entry<String, String[]>>) req.getParameterMap().entrySet()) { parameters.put(entry.getKey(), entry.getValue()); } // get the basic values out this.locale = req.getLocale(); this.method = req.getMethod(); this.contentType = req.getContentType(); this.characterEncoding = req.getCharacterEncoding() == null ? "UTF-8" : req.getCharacterEncoding(); this.contentLength = req.getContentLength(); this.contextPath = req.getContextPath(); this.pathInfo = req.getPathInfo(); this.queryString = req.getQueryString(); this.requestURI = req.getRequestURI(); this.servletPath = req.getServletPath(); this.scheme = req.getScheme(); this.protocol = req.getProtocol(); this.serverName = req.getServerName(); this.serverPort = req.getServerPort(); this.remoteAddr = req.getRemoteAddr(); this.remoteHost = req.getRemoteHost(); this.realDispatcher = true; }
From source file:org.apache.unomi.web.EventsCollectorServlet.java
private void doEvent(HttpServletRequest request, HttpServletResponse response) throws IOException { Date timestamp = new Date(); if (request.getParameter("timestamp") != null) { timestamp.setTime(Long.parseLong(request.getParameter("timestamp"))); }//from ww w . ja v a 2 s . com // logger.debug(HttpUtils.dumpRequestInfo(request)); HttpUtils.setupCORSHeaders(request, response); String sessionId = request.getParameter("sessionId"); if (sessionId == null) { logger.error( "No sessionId found in incoming request, aborting processing. See debug level for more information"); if (logger.isDebugEnabled()) { logger.debug("Request dump:" + HttpUtils.dumpRequestInfo(request)); } return; } Session session = profileService.loadSession(sessionId, timestamp); if (session == null) { logger.error("No session found for sessionId={}, aborting request !", sessionId); return; } String profileIdCookieName = "context-profile-id"; Profile sessionProfile = session.getProfile(); Profile profile = null; if (sessionProfile.getItemId() != null) { // Reload up-to-date profile profile = profileService.load(sessionProfile.getItemId()); if (profile == null || profile instanceof Persona) { logger.error("No valid profile found or persona found for profileId={}, aborting request !", session.getProfileId()); return; } } else { // Session uses anonymous profile, try to find profile from cookie Cookie[] cookies = request.getCookies(); for (Cookie cookie : cookies) { if (profileIdCookieName.equals(cookie.getName())) { profile = profileService.load(cookie.getValue()); } } if (profile == null) { logger.error("No valid profile found or persona found for profileId={}, aborting request !", session.getProfileId()); return; } } String payload = HttpUtils.getPayload(request); if (payload == null) { logger.error("No event payload found for request, aborting !"); return; } ObjectMapper mapper = CustomObjectMapper.getObjectMapper(); JsonFactory factory = mapper.getFactory(); EventsCollectorRequest events = null; try { events = mapper.readValue(factory.createParser(payload), EventsCollectorRequest.class); } catch (Exception e) { logger.error("Cannot read payload " + payload, e); return; } if (events == null || events.getEvents() == null) { logger.error("No events found in payload"); return; } String thirdPartyId = eventService.authenticateThirdPartyServer( ((HttpServletRequest) request).getHeader("X-Unomi-Peer"), request.getRemoteAddr()); int changes = 0; List<String> filteredEventTypes = privacyService.getFilteredEventTypes(profile.getItemId()); for (Event event : events.getEvents()) { if (event.getEventType() != null) { Event eventToSend = new Event(event.getEventType(), session, profile, event.getScope(), event.getSource(), event.getTarget(), event.getProperties(), timestamp); if (sessionProfile.isAnonymousProfile()) { // Do not keep track of profile in event eventToSend.setProfileId(null); } if (!eventService.isEventAllowed(event, thirdPartyId)) { logger.debug("Event is not allowed : {}", event.getEventType()); continue; } if (filteredEventTypes != null && filteredEventTypes.contains(event.getEventType())) { logger.debug("Profile is filtering event type {}", event.getEventType()); continue; } eventToSend.getAttributes().put(Event.HTTP_REQUEST_ATTRIBUTE, request); eventToSend.getAttributes().put(Event.HTTP_RESPONSE_ATTRIBUTE, response); logger.debug("Received event " + event.getEventType() + " for profile=" + sessionProfile.getItemId() + " session=" + session.getItemId() + " target=" + event.getTarget() + " timestamp=" + timestamp); int eventChanged = eventService.send(eventToSend); //if the event execution changes the profile if ((eventChanged & EventService.PROFILE_UPDATED) == EventService.PROFILE_UPDATED) { profile = eventToSend.getProfile(); } changes |= eventChanged; } } if ((changes & EventService.PROFILE_UPDATED) == EventService.PROFILE_UPDATED) { profileService.save(profile); } if ((changes & EventService.SESSION_UPDATED) == EventService.SESSION_UPDATED) { profileService.saveSession(session); } PrintWriter responseWriter = response.getWriter(); responseWriter.append("{\"updated\":" + changes + "}"); responseWriter.flush(); }
From source file:memedb.httpd.MemeDBHandler.java
protected Credentials getCredentials(HttpServletRequest request, HttpServletResponse response) throws IOException { Credentials cred = null;/*from w w w . ja v a 2 s. c om*/ if (request.getRequestURI().equals("/_auth")) { String username = request.getParameter("username"); String password = request.getParameter("password"); log.debug("login attempt for {}", username); if (!allowAnonymous && "anonymous".equals(username)) { sendNoAuthError(response, "Bad username / password combination"); return null; } if (username != null) { if (password == null) { password = ""; } if (allowAnonymous && allowAnonymousAsSa && "anonymous".equals(username)) { return new SACredentials("anonymous", "", timeout); } cred = memeDB.getAuthentication().authenticate(username, password); if (cred != null) { if (request.getParameter("setcookie") == null || request.getParameter("setcookie").toLowerCase().equals("false")) { Cookie cookie = new Cookie(COOKIE_ID, cred.getToken()); cookie.setMaxAge(timeout); response.addCookie(cookie); } return cred; } else { log.warn("Bad login attempt for {}", username); sendNoAuthError(response, "Bad username / password combination"); return null; } } } Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals(COOKIE_ID)) { cred = memeDB.getAuthentication().getCredentialsFromToken(cookie.getValue()); if (cred != null) { log.debug("Got credentials from cookie token: {}", cookie.getValue()); return cred; } } } } String param = request.getParameter("token"); if (param != null && !param.equals("")) { cred = memeDB.getAuthentication().getCredentialsFromToken(param); if (cred != null) { log.debug("Authenticated as {} => {} via Req param", cred.getUsername(), cred.getToken()); addCredentialedCookie(response, cred); return cred; } } String headerparam = request.getHeader("MemeDB-Token"); if (headerparam != null && !headerparam.equals("")) { log.info("Attempting authentication with token {}", headerparam); cred = memeDB.getAuthentication().getCredentialsFromToken(headerparam); if (cred != null) { log.info("Got credentials!"); log.debug("Authenticated as {} => {} via HTTP-Header", cred.getUsername(), cred.getToken()); addCredentialedCookie(response, cred); return cred; } } String authHeader = request.getHeader("Authorization"); if (authHeader != null) { String[] authSplit = authHeader.split(" "); if (authSplit.length == 2) { String userpass = new String(Base64.decodeBase64(authSplit[1].getBytes())); if (userpass != null) { String[] ar = userpass.split(":"); if (ar.length > 0) { String u = ar[0]; String p = ""; if (ar.length > 1) { p = ar[1]; } if (!allowAnonymous && "anonymous".equals(u)) { } else { cred = memeDB.getAuthentication().authenticate(u, p); if (cred != null) { log.debug("Authenticated as {} => {} via HTTP-AUTH", cred.getUsername(), cred.getToken()); addCredentialedCookie(response, cred); } return cred; } } } } response.addHeader("WWW-Authenticate", " Basic realm=\"" + realm + "\""); sendNoAuthError(response, "You need a username and password"); return null; } if (allowAnonymous) { if (allowAnonymousAsSa) return new SACredentials("anonymous", "", timeout); return new AnonCredentials("", timeout); } log.warn("Error authenticating"); response.addHeader("WWW-Authenticate", " Basic realm=\"" + realm + "\""); sendNoAuthError(response, "You need a username and password"); return null; }
From source file:com.haulmont.cuba.web.sys.CubaApplicationServlet.java
protected void redirectToApp(HttpServletRequest request, HttpServletResponse response, String contextName, String[] uriParts, String action) throws IOException { StringBuilder redirectAddress = new StringBuilder(); for (int i = 0; i < uriParts.length; i++) { redirectAddress.append(uriParts[i]); if (uriParts[i].equals(contextName)) { break; }//ww w . j a va 2 s . co m if (i < uriParts.length - 1) { redirectAddress.append("/"); } } // redirect to ROOT context if (redirectAddress.length() == 0) { redirectAddress.append("/"); } HttpSession httpSession = request.getSession(); if (action != null) { httpSession.setAttribute(AppUI.LAST_REQUEST_ACTION_ATTR, action); } if (request.getParameterNames().hasMoreElements()) { Map<String, String> params = new HashMap<>(); Enumeration parameterNames = request.getParameterNames(); while (parameterNames.hasMoreElements()) { String name = (String) parameterNames.nextElement(); if (!FROM_HTML_REDIRECT_PARAM.equals(name)) { params.put(name, request.getParameter(name)); } } httpSession.setAttribute(AppUI.LAST_REQUEST_PARAMS_ATTR, params); } statisticsCounter.incWebRequestsCount(); String httpSessionId = httpSession.getId(); log.debug("Redirect to application {}", httpSessionId); Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if ("JSESSIONID".equals(cookie.getName()) && !httpSessionId.equals(cookie.getValue())) { cookie.setValue(httpSessionId); break; } } } response.sendRedirect(redirectAddress.toString()); }
From source file:com.ibm.jaggr.core.test.TestUtils.java
public static HttpServletRequest createMockRequest(IAggregator aggregator, final Map<String, Object> requestAttributes, final Map<String, String[]> requestParameters, final Cookie[] cookies, final Map<String, String> headers) { HttpServletRequest mockRequest = EasyMock.createNiceMock(HttpServletRequest.class); if (requestAttributes != null) { requestAttributes.put(IAggregator.AGGREGATOR_REQATTRNAME, aggregator); EasyMock.expect(mockRequest.getAttribute((String) EasyMock.anyObject())) .andAnswer(new IAnswer<Object>() { public Object answer() throws Throwable { return requestAttributes.get((String) EasyMock.getCurrentArguments()[0]); }// w ww . j a v a2s .c o m }).anyTimes(); mockRequest.setAttribute((String) EasyMock.anyObject(), EasyMock.anyObject()); EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() { public Object answer() throws Throwable { String name = (String) EasyMock.getCurrentArguments()[0]; Object value = EasyMock.getCurrentArguments()[1]; requestAttributes.put(name, value); return null; } }).anyTimes(); mockRequest.removeAttribute((String) EasyMock.anyObject()); EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() { public Object answer() throws Throwable { String name = (String) EasyMock.getCurrentArguments()[0]; requestAttributes.remove(name); return null; } }).anyTimes(); } else { EasyMock.expect(mockRequest.getAttribute(IAggregator.AGGREGATOR_REQATTRNAME)).andReturn(aggregator) .anyTimes(); } if (requestParameters != null) { EasyMock.expect(mockRequest.getParameter((String) EasyMock.anyObject())) .andAnswer(new IAnswer<String>() { public String answer() throws Throwable { String[] ary = requestParameters.get((String) EasyMock.getCurrentArguments()[0]); return ary != null && ary.length > 0 ? ary[0] : null; } }).anyTimes(); EasyMock.expect(mockRequest.getParameterMap()).andAnswer(new IAnswer<Map<String, String[]>>() { @Override public Map<String, String[]> answer() throws Throwable { return requestParameters; } }).anyTimes(); } if (cookies != null) { EasyMock.expect(mockRequest.getCookies()).andAnswer(new IAnswer<Cookie[]>() { public Cookie[] answer() throws Throwable { return cookies; } }).anyTimes(); } if (headers != null) { EasyMock.expect(mockRequest.getHeader((String) EasyMock.anyObject())).andAnswer(new IAnswer<String>() { public String answer() throws Throwable { return headers.get((String) EasyMock.getCurrentArguments()[0]); } }).anyTimes(); } return mockRequest; }
From source file:org.apache.catalina.valves.ExtendedAccessLogValve.java
/** * Get app specific data.//w w w. ja va 2s .co m * @param fieldInfo The field to decode * @param request Where we will pull the data from. * @return The appropriate value */ private String getAppSpecific(FieldInfo fieldInfo, Request request) { ServletRequest sr = request.getRequest(); HttpServletRequest hsr = null; if (sr instanceof HttpServletRequest) hsr = (HttpServletRequest) sr; switch (fieldInfo.xType) { case FieldInfo.X_PARAMETER: return wrap(urlEncode(sr.getParameter(fieldInfo.value))); case FieldInfo.X_REQUEST: return wrap(sr.getAttribute(fieldInfo.value)); case FieldInfo.X_SESSION: HttpSession session = null; if (hsr != null) { session = hsr.getSession(false); if (session != null) return wrap(session.getAttribute(fieldInfo.value)); } break; case FieldInfo.X_COOKIE: Cookie[] c = hsr.getCookies(); for (int i = 0; c != null && i < c.length; i++) { if (fieldInfo.value.equals(c[i].getName())) { return wrap(c[i].getValue()); } } case FieldInfo.X_APP: return wrap(request.getContext().getServletContext().getAttribute(fieldInfo.value)); case FieldInfo.X_SERVLET_REQUEST: if (fieldInfo.location == FieldInfo.X_LOC_AUTHTYPE) { return wrap(hsr.getAuthType()); } else if (fieldInfo.location == FieldInfo.X_LOC_REMOTEUSER) { return wrap(hsr.getRemoteUser()); } else if (fieldInfo.location == FieldInfo.X_LOC_REQUESTEDSESSIONID) { return wrap(hsr.getRequestedSessionId()); } else if (fieldInfo.location == FieldInfo.X_LOC_REQUESTEDSESSIONIDFROMCOOKIE) { return wrap("" + hsr.isRequestedSessionIdFromCookie()); } else if (fieldInfo.location == FieldInfo.X_LOC_REQUESTEDSESSIONIDVALID) { return wrap("" + hsr.isRequestedSessionIdValid()); } else if (fieldInfo.location == FieldInfo.X_LOC_CONTENTLENGTH) { return wrap("" + hsr.getContentLength()); } else if (fieldInfo.location == FieldInfo.X_LOC_CHARACTERENCODING) { return wrap(hsr.getCharacterEncoding()); } else if (fieldInfo.location == FieldInfo.X_LOC_LOCALE) { return wrap(hsr.getLocale()); } else if (fieldInfo.location == FieldInfo.X_LOC_PROTOCOL) { return wrap(hsr.getProtocol()); } else if (fieldInfo.location == FieldInfo.X_LOC_SCHEME) { return wrap(hsr.getScheme()); } else if (fieldInfo.location == FieldInfo.X_LOC_SECURE) { return wrap("" + hsr.isSecure()); } break; default: ; } return "-"; }