javax.servlet.ServletRequest Java Examples
The following examples show how to use
javax.servlet.ServletRequest.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MDCFilter.java From hadoop with Apache License 2.0 | 6 votes |
/** * Sets the slf4j <code>MDC</code> and delegates the request to the chain. * * @param request servlet request. * @param response servlet response. * @param chain filter chain. * * @throws IOException thrown if an IO error occurrs. * @throws ServletException thrown if a servet error occurrs. */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { try { MDC.clear(); String hostname = HostnameFilter.get(); if (hostname != null) { MDC.put("hostname", HostnameFilter.get()); } Principal principal = ((HttpServletRequest) request).getUserPrincipal(); String user = (principal != null) ? principal.getName() : null; if (user != null) { MDC.put("user", user); } MDC.put("method", ((HttpServletRequest) request).getMethod()); MDC.put("path", ((HttpServletRequest) request).getPathInfo()); chain.doFilter(request, response); } finally { MDC.clear(); } }
Example #2
Source File: AuthenticationFilter.java From oxTrust with MIT License | 6 votes |
/** * Determine filter execution conditions */ protected final boolean preFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException { final HttpServletRequest request = (HttpServletRequest) servletRequest; final HttpSession session = request.getSession(false); final OAuthData oAuthData = session != null ? (OAuthData) session.getAttribute(Configuration.SESSION_OAUTH_DATA) : null; if (oAuthData != null) { return false; } final String code = getParameter(request, Configuration.OAUTH_CODE); log.trace("code value: " + code); if (StringHelper.isNotEmpty(code)) { return false; } return true; }
Example #3
Source File: ServletUtils.java From uyuni with GNU General Public License v2.0 | 6 votes |
/** * Creates a encoded URL query string with the parameters from the given request. If the * request is a GET, then the returned query string will simply consist of the query * string from the request. If the request is a POST, the returned query string will * consist of the form variables. * <p> * <strong>Note</strong>: This method does not support multi-value parameters. * * @param request The request for which the query string will be generated. * * @return An encoded URL query string with the parameters from the given request. */ public static String requestParamsToQueryString(ServletRequest request) { StringBuffer queryString = new StringBuffer(); String paramName = null; String paramValue = null; Enumeration paramNames = request.getParameterNames(); while (paramNames.hasMoreElements()) { paramName = (String)paramNames.nextElement(); paramValue = request.getParameter(paramName); queryString.append(encode(paramName)).append("=").append(encode(paramValue)) .append("&"); } if (endsWith(queryString, '&')) { queryString.deleteCharAt(queryString.length() - 1); } return queryString.toString(); }
Example #4
Source File: X509CertificateFilterTest.java From seed with Mozilla Public License 2.0 | 6 votes |
@Test public void createToken_should_create_token() throws Exception { X509Certificate certificate = mock(X509Certificate.class); ServletRequest request = mock(ServletRequest.class); ServletResponse response = mock(ServletResponse.class); when(request.getAttribute("javax.servlet.request.X509Certificate")).thenReturn( new X509Certificate[]{certificate}); AuthenticationToken token = underTest.createToken(request, response); assertThat(token).isInstanceOf(AuthenticationTokenWrapper.class); AuthenticationTokenWrapper w = (AuthenticationTokenWrapper) token; assertThat(w.getSeedToken()).isInstanceOf(X509CertificateToken.class); X509CertificateToken x = (X509CertificateToken) w.getSeedToken(); assertThat(x.getAuthenticatingCertificates()).containsExactly(certificate); }
Example #5
Source File: ValidateUserFilter.java From civism-sso with Apache License 2.0 | 6 votes |
@Override protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) { boolean existSession = SecurityUtils.getSubject().isAuthenticated(); if (!existSession) { return false; } else { Session session = SecurityUtils.getSubject().getSession(false); if (session != null) { Serializable id = session.getId(); if (id != null) { if (redisClient.get((String) id) != null) { return true; } } } return false; } }
Example #6
Source File: AuthenticationFilter.java From journaldev with MIT License | 6 votes |
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; String uri = req.getRequestURI(); this.context.log("Requested Resource::"+uri); HttpSession session = req.getSession(false); if(session == null && !(uri.endsWith("html") || uri.endsWith("LoginServlet"))){ this.context.log("Unauthorized access request"); res.sendRedirect("login.html"); }else{ // pass the request along the filter chain chain.doFilter(request, response); } }
Example #7
Source File: ExtendedServletRequestDataBinder.java From spring-analysis-note with MIT License | 6 votes |
/** * Merge URI variables into the property values to use for data binding. */ @Override @SuppressWarnings("unchecked") protected void addBindValues(MutablePropertyValues mpvs, ServletRequest request) { String attr = HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE; Map<String, String> uriVars = (Map<String, String>) request.getAttribute(attr); if (uriVars != null) { uriVars.forEach((name, value) -> { if (mpvs.contains(name)) { if (logger.isWarnEnabled()) { logger.warn("Skipping URI variable '" + name + "' because request contains bind value with same name."); } } else { mpvs.addPropertyValue(name, value); } }); } }
Example #8
Source File: RequestResponseHolder.java From deltaspike with Apache License 2.0 | 6 votes |
/** * Binds the request or response to the current thread. * * @param instance * The request/response * @throws IllegalStateException * if there is already an instance bound to the thread */ void bind(Type instance) { if (isBound()) { // ignore forwards - Tomcat calls #requestInitialized two times with form authentication if (instance instanceof ServletRequest) { ServletRequest servletRequest = (ServletRequest) instance; if (servletRequest.getAttribute("javax.servlet.forward.request_uri") != null) { return; } } throw new IllegalStateException("There is already an instance bound to this thread."); } threadLocal.set(instance); }
Example #9
Source File: ClientICalendarFilter.java From cosmo with Apache License 2.0 | 6 votes |
private String translateUserAgent(ServletRequest request) { if( ! (request instanceof HttpServletRequest) || ((HttpServletRequest)request).getHeader("User-Agent") == null) { return null; } String agent = ((HttpServletRequest)request).getHeader("User-Agent"); // Translate User-Agent header into client key by finding match using rules in clientKeyMap. for(Entry<String, String> entry :clientKeyMap.entrySet()) { if(agent.matches(entry.getKey())) { return entry.getValue(); } } return agent; }
Example #10
Source File: FederationFilter.java From cxf-fediz with Apache License 2.0 | 6 votes |
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { try { Subject subject = WSSubject.getCallerSubject(); if (subject != null) { FedizResponse fedResponse = getCachedFederationResponse(subject); LOG.info("Security token found for user: {}", fedResponse.getUsername()); Element el = fedResponse.getToken(); if (el != null) { SecurityTokenThreadLocal.setToken(el); LOG.debug("Setting Security Token to SecurityTokenThreadLocal"); } } chain.doFilter(request, response); } catch (WSSecurityException e) { LOG.warn("No caller Subject/Principal found in request."); chain.doFilter(request, response); } finally { SecurityTokenThreadLocal.setToken(null); } }
Example #11
Source File: CorsFilter.java From blog with MIT License | 6 votes |
@Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; String domain = request.getHeader("Origin"); if (permissionFilterService.haveHeaderPermission(request)) { response.setHeader("Access-Control-Allow-Origin", domain); response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", " X-Requested-With, Content-Type,X-Requested-With, Content-Type, X-File-Name,token,Access-Control-Allow-Origin,Access-Control-Allow-Methods,Access-Control-Max-Age,authorization"); chain.doFilter(req, res); } else { request.setAttribute("gunjianpan", "Error"); // response.sendError(ErrorCodeConsts.STATUS_FORBIDDEN); chain.doFilter(req, res); } }
Example #12
Source File: CrnkFilterTest.java From crnk-framework with Apache License 2.0 | 6 votes |
@Test public void testNonHttpRequest() throws Exception { FilterChain chain = Mockito.mock(FilterChain.class); ServletRequest nonHttpRequest = Mockito.mock(ServletRequest.class); ServletResponse nonHttpResponse = Mockito.mock(ServletResponse.class); HttpServletRequest httpRequest = Mockito.mock(HttpServletRequest.class); ServletResponse httpResponse = Mockito.mock(HttpServletResponse.class); filter.doFilter(nonHttpRequest, nonHttpResponse, chain); Mockito.verify(chain, Mockito.times(1)).doFilter(nonHttpRequest, nonHttpResponse); filter.doFilter(nonHttpRequest, httpResponse, chain); Mockito.verify(chain, Mockito.times(1)).doFilter(nonHttpRequest, httpResponse); filter.doFilter(httpRequest, nonHttpResponse, chain); Mockito.verify(chain, Mockito.times(1)).doFilter(httpRequest, nonHttpResponse); }
Example #13
Source File: GWTCacheControlFilter.java From lumongo with Apache License 2.0 | 6 votes |
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; String requestURI = httpRequest.getRequestURI(); if (requestURI.contains(".nocache.")) { Date now = new Date(); HttpServletResponse httpResponse = (HttpServletResponse) response; httpResponse.setDateHeader("Date", now.getTime()); // one day old httpResponse.setDateHeader("Expires", now.getTime() - 86400000L); httpResponse.setHeader("Pragma", "no-cache"); httpResponse.setHeader("Cache-control", "no-cache, no-store, must-revalidate"); } filterChain.doFilter(request, response); }
Example #14
Source File: CognitoIdentityFilter.java From aws-serverless-java-container with Apache License 2.0 | 6 votes |
@Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { Object apiGwContext = servletRequest.getAttribute(RequestReader.API_GATEWAY_CONTEXT_PROPERTY); if (apiGwContext == null) { log.warn("API Gateway context is null"); filterChain.doFilter(servletRequest, servletResponse); } if (!AwsProxyRequestContext.class.isAssignableFrom(apiGwContext.getClass())) { log.warn("API Gateway context object is not of valid type"); filterChain.doFilter(servletRequest, servletResponse); } AwsProxyRequestContext ctx = (AwsProxyRequestContext)apiGwContext; if (ctx.getIdentity() == null) { log.warn("Identity context is null"); filterChain.doFilter(servletRequest, servletResponse); } String cognitoIdentityId = ctx.getIdentity().getCognitoIdentityId(); if (cognitoIdentityId == null || "".equals(cognitoIdentityId.trim())) { log.warn("Cognito identity id in request is null"); } servletRequest.setAttribute(COGNITO_IDENTITY_ATTRIBUTE, cognitoIdentityId); filterChain.doFilter(servletRequest, servletResponse); }
Example #15
Source File: TasksTest.java From appengine-tck with Apache License 2.0 | 6 votes |
@Test public void testMultiValueParams() throws Exception { class ParamHandler implements PrintServlet.RequestHandler { private String[] paramValues; public void handleRequest(ServletRequest req) { paramValues = req.getParameterValues("multi_value"); } } ParamHandler handler = new ParamHandler(); PrintServlet.setRequestHandler(handler); final Queue queue = QueueFactory.getQueue("tasks-queue"); queue.add( withUrl(URL) .param("multi_value", "param_value1") .param("multi_value", "param_value2")); sync(); assertNotNull(handler.paramValues); assertEquals( new HashSet<>(Arrays.asList("param_value1", "param_value2")), new HashSet<>(Arrays.asList(handler.paramValues))); }
Example #16
Source File: AnonymousAuthFilter.java From knox with Apache License 2.0 | 5 votes |
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest)request; String principal = httpRequest.getRemoteUser(); if (principal == null) { principal = "anonymous"; } Subject subject = new Subject(); subject.getPrincipals().add(new PrimaryPrincipal(principal)); auditService.getContext().setUsername( principal ); //KM: Audit Fix String sourceUri = (String)request.getAttribute( AbstractGatewayFilter.SOURCE_REQUEST_CONTEXT_URL_ATTRIBUTE_NAME ); auditor.audit( Action.AUTHENTICATION , sourceUri, ResourceType.URI, ActionOutcome.SUCCESS ); continueWithEstablishedSecurityContext(subject, (HttpServletRequest)request, (HttpServletResponse)response, filterChain); }
Example #17
Source File: RedirectFilter.java From qpid-broker-j with Apache License 2.0 | 5 votes |
@Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (response instanceof HttpServletResponse) { ((HttpServletResponse) response).sendRedirect(_redirectURI); } }
Example #18
Source File: HibSessionFilter.java From unitime with Apache License 2.0 | 5 votes |
/** * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) */ public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException, ServletException { if (filterConfig==null) return; if (request.getAttribute("TimeStamp")==null) request.setAttribute("TimeStamp", new Double(JProf.currentTimeSec())); try { // Process request chain.doFilter(request,response); _BaseRootDAO.closeCurrentThreadSessions(); } catch (Throwable ex) { _BaseRootDAO.rollbackCurrentThreadSessions(); if (ex instanceof ServletException) throw (ServletException)ex; if (ex instanceof IOException) throw (IOException)ex; if (ex instanceof RuntimeException) throw (RuntimeException)ex; // Let others handle it... maybe another interceptor for exceptions? throw new ServletException(ex); } }
Example #19
Source File: CommonsUploadMultipartObserver.java From vraptor4 with Apache License 2.0 | 5 votes |
protected String getValue(FileItem item, ServletRequest request) { String encoding = request.getCharacterEncoding(); if (!isNullOrEmpty(encoding)) { try { return item.getString(encoding); } catch (UnsupportedEncodingException e) { logger.debug("Request has an invalid encoding. Ignoring it", e); } } return item.getString(); }
Example #20
Source File: RestAsyncListener.java From servicecomb-java-chassis with Apache License 2.0 | 5 votes |
@Override public void onTimeout(AsyncEvent event) throws IOException { // in this time, maybe: // 1.invocation in executor's queue // 2.already executing in executor // 3.already send response // to avoid concurrent, must lock request ServletRequest request = event.getSuppliedRequest(); HttpServletRequestEx requestEx = (HttpServletRequestEx) request.getAttribute(RestConst.REST_REQUEST); LOGGER.error("Rest request timeout, method {}, path {}.", requestEx.getMethod(), requestEx.getRequestURI()); // Waiting till executing in executor done. This operation may block container pool and make timeout requests in executor's // queue getting executed, and will cause bad performance. So default timeout is setting to -1 to disable timeout. synchronized (requestEx) { ServletResponse response = event.getAsyncContext().getResponse(); if (!response.isCommitted()) { // invocation in executor's queue response.setContentType(MediaType.APPLICATION_JSON); // we don't know if developers declared one statusCode in contract // so we use cse inner statusCode here ((HttpServletResponse) response).setStatus(Status.INTERNAL_SERVER_ERROR.getStatusCode()); PrintWriter out = response.getWriter(); out.write(TIMEOUT_MESSAGE); response.flushBuffer(); } request.removeAttribute(RestConst.REST_REQUEST); } LOGGER.error("Rest request timeout committed, method {}, path {}.", requestEx.getMethod(), requestEx.getRequestURI()); }
Example #21
Source File: XssFilter.java From mall4j with GNU Affero General Public License v3.0 | 5 votes |
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException{ HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; logger.info("uri:{}",req.getRequestURI()); // xss 过滤 chain.doFilter(new XssWrapper(req), resp); }
Example #22
Source File: TrustedProxyLoginService.java From cruise-control with BSD 2-Clause "Simplified" License | 5 votes |
@Override public UserIdentity login(String username, Object credentials, ServletRequest request) { if (!(request instanceof HttpServletRequest)) { return null; } SpnegoUserIdentity serviceIdentity = (SpnegoUserIdentity) _delegateSpnegoLoginService.login(username, credentials, request); SpnegoUserPrincipal servicePrincipal = (SpnegoUserPrincipal) serviceIdentity.getUserPrincipal(); String doAsUser = request.getParameter(DO_AS); LOG.info("Authorizing proxy user {} from {} service", doAsUser, servicePrincipal.getName()); UserIdentity doAsIdentity = null; if (doAsUser != null && !doAsUser.isEmpty()) { doAsIdentity = _endUserAuthorizer.getUserIdentity((HttpServletRequest) request, doAsUser); } Principal principal = new TrustedProxyPrincipal(doAsUser, servicePrincipal); Subject subject = new Subject(READ_ONLY_SUBJECT, Collections.singleton(principal), Collections.emptySet(), Collections.emptySet()); if (!serviceIdentity.isEstablished()) { LOG.info("Service user {} isn't authorized as a trusted proxy", servicePrincipal.getName()); return new SpnegoUserIdentity(subject, principal, null); } else { if (doAsIdentity == null) { LOG.info("Couldn't authorize user {}", doAsUser); } return new SpnegoUserIdentity(subject, principal, doAsIdentity); } }
Example #23
Source File: CsrfIncludeFilter.java From graviteeio-access-management with Apache License 2.0 | 5 votes |
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse httpResponse = (HttpServletResponse) response; CsrfToken csrfToken = (CsrfToken) request.getAttribute(CsrfToken.class.getName()); httpResponse.addHeader(csrfToken.getHeaderName(), csrfToken.getToken()); chain.doFilter(request, response); }
Example #24
Source File: ServletRequestMethodArgumentResolver.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Override public boolean supportsParameter(MethodParameter parameter) { Class<?> paramType = parameter.getParameterType(); return (WebRequest.class.isAssignableFrom(paramType) || ServletRequest.class.isAssignableFrom(paramType) || MultipartRequest.class.isAssignableFrom(paramType) || HttpSession.class.isAssignableFrom(paramType) || Principal.class.isAssignableFrom(paramType) || Locale.class == paramType || TimeZone.class == paramType || "java.time.ZoneId".equals(paramType.getName()) || InputStream.class.isAssignableFrom(paramType) || Reader.class.isAssignableFrom(paramType) || HttpMethod.class == paramType); }
Example #25
Source File: EncodingFilter.java From OnlineShoppingSystem with MIT License | 5 votes |
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=utf-8"); chain.doFilter(request, response); }
Example #26
Source File: DefaultServletRequestDispatcher.java From piranha with BSD 3-Clause "New" or "Revised" License | 5 votes |
private void asyncHttpForward(AsyncHttpDispatchWrapper asyncHttpDispatchWrapper, ServletResponse servletResponse) throws ServletException, IOException { // A typical chain to arrive here is DefaultAsyncContext#dispatch -> DefaultAsyncDispatcher#dispatch -> forward -> asyncForwrd -> asyncHttpForward HttpServletRequest asyncStartRequest = asyncHttpDispatchWrapper.getRequest(); if (asyncStartRequest instanceof WebApplicationRequest) { // original request or previously dispatched request passed-in, not an application wrapped one // In this case our asyncHttpDispatchWrapper is both the object with which the Servlet will be invoked, as well as the // object on which the path and attributes for the previous path will be set. invokeTargetAsyncServlet(asyncHttpDispatchWrapper, servletResponse); } else if (asyncStartRequest instanceof HttpServletRequestWrapper) { // Application wrapped request passed-in. We now need no make sure that the applications sees this request // We swap our asyncHttpDispatchWrapper from being the head of the chain, to be in between the request that was provided by the application // and the request it is wrapping. HttpServletRequestWrapper applicationProvidedWrapper = (HttpServletRequestWrapper) asyncStartRequest; ServletRequest wrappedRequest = applicationProvidedWrapper.getRequest(); applicationProvidedWrapper.setRequest(asyncHttpDispatchWrapper); asyncHttpDispatchWrapper.setRequest(wrappedRequest); // Original chain: asyncHttpDispatchWrapper -> applicationProvidedWrapper (asyncStartRequest) -> wrappedRequest // New chain: applicationProvidedWrapper (asyncStartRequest) -> asyncHttpDispatchWrapper -> wrappedRequest invokeTargetAsyncServlet(applicationProvidedWrapper, asyncHttpDispatchWrapper, servletResponse); } else { throw new IllegalStateException("Async invocation with a request that was neither the original one nor a wrapped one: " + asyncStartRequest); } }
Example #27
Source File: RequestAttributeInjector.java From sling-org-apache-sling-models-impl with Apache License 2.0 | 5 votes |
@Override public Object getValue(@NotNull Object adaptable, String name, @NotNull Type declaredType, @NotNull AnnotatedElement element, @NotNull DisposalCallbackRegistry callbackRegistry) { if (!(adaptable instanceof ServletRequest)) { return null; } else { return ((ServletRequest) adaptable).getAttribute(name); } }
Example #28
Source File: CacheFilter.java From steady with Apache License 2.0 | 5 votes |
/** * Appends to the response a X-Accel-Expires header equal to two hours if cache=true is present in the querystring of the request * @param request an incoming HTTP request * @param response the HTTP resonse to return * @param chain the chain of filters * @return void */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { String cache = request.getParameter("cache"); if (cache != null && cache.equals("true")) { // Instructs Nginx to cache the response for 2 hours HttpServletResponse httpServletResponse=(HttpServletResponse)response; httpServletResponse.setHeader("X-Accel-Expires", "7200"); } chain.doFilter(request, response); }
Example #29
Source File: JwtTokenAuthenticationFilter.java From spring-webmvc-jwt-sample with GNU General Public License v3.0 | 5 votes |
@Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException, ServletException { String token = jwtTokenProvider.resolveToken((HttpServletRequest) req); if (token != null && jwtTokenProvider.validateToken(token)) { Authentication auth = jwtTokenProvider.getAuthentication(token); if (auth != null) { SecurityContextHolder.getContext().setAuthentication(auth); } } filterChain.doFilter(req, res); }
Example #30
Source File: ServletRequestUtils.java From lams with GNU General Public License v2.0 | 5 votes |
/** * Get an array of int parameters, return an empty array if not found. * @param request current HTTP request * @param name the name of the parameter with multiple possible values */ public static int[] getIntParameters(ServletRequest request, String name) { try { return getRequiredIntParameters(request, name); } catch (ServletRequestBindingException ex) { return new int[0]; } }