Java Code Examples for javax.servlet.DispatcherType

The following examples show how to use javax.servlet.DispatcherType. These examples are extracted from open source projects. 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
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    ServletRequest request = servletRequestContext.getServletRequest();
    if (request.getDispatcherType() == DispatcherType.REQUEST) {
        List<SingleConstraintMatch> constraints = servletRequestContext.getRequiredConstrains();
        SecurityContext sc = exchange.getSecurityContext();
        if (!authorizationManager.canAccessResource(constraints, sc.getAuthenticatedAccount(), servletRequestContext.getCurrentServlet().getManagedServlet().getServletInfo(), servletRequestContext.getOriginalRequest(), servletRequestContext.getDeployment())) {

            HttpServletResponse response = (HttpServletResponse) servletRequestContext.getServletResponse();
            response.sendError(StatusCodes.FORBIDDEN);
            return;
        }
    }
    next.handleRequest(exchange);
}
 
Example 2
Source Project: openwebbeans-meecrowave   Source File: OWBAutoSetup.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onStartup(final Set<Class<?>> c, final ServletContext ctx) {
    final Configuration builder = Configuration.class.cast(ctx.getAttribute("meecrowave.configuration"));
    final Meecrowave instance = Meecrowave.class.cast(ctx.getAttribute("meecrowave.instance"));
    if (builder.isCdiConversation()) {
        try {
            final Class<? extends Filter> clazz = (Class<? extends Filter>) OWBAutoSetup.class.getClassLoader()
                  .loadClass("org.apache.webbeans.web.context.WebConversationFilter");
            final FilterRegistration.Dynamic filter = ctx.addFilter("owb-conversation", clazz);
            filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), false, "/*");
        } catch (final Exception e) {
            // no-op
        }
    }

    // eager boot to let injections work in listeners
    final EagerBootListener bootListener = new EagerBootListener(instance);
    bootListener.doContextInitialized(new ServletContextEvent(ctx));
    ctx.addListener(bootListener);
}
 
Example 3
Source Project: gocd   Source File: Jetty9ServerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldAddDefaultHeadersForRootContext() throws Exception {
    jetty9Server.configure();
    jetty9Server.startHandlers();

    HttpServletResponse response = mock(HttpServletResponse.class);
    when(response.getWriter()).thenReturn(mock(PrintWriter.class));

    HttpServletRequest request = mock(HttpServletRequest.class);

    Request baseRequest = mock(Request.class);
    when(baseRequest.getDispatcherType()).thenReturn(DispatcherType.REQUEST);
    when(baseRequest.getHttpFields()).thenReturn(mock(HttpFields.class));

    ContextHandler rootPathHandler = getLoadedHandlers().get(GoServerLoadingIndicationHandler.class);
    rootPathHandler.setServer(server);
    rootPathHandler.start();
    rootPathHandler.handle("/something", baseRequest, request, response);

    verify(response).setHeader("X-XSS-Protection", "1; mode=block");
    verify(response).setHeader("X-Content-Type-Options", "nosniff");
    verify(response).setHeader("X-Frame-Options", "SAMEORIGIN");
    verify(response).setHeader("X-UA-Compatible", "chrome=1");
}
 
Example 4
Source Project: tomcatsrc   Source File: FilterMap.java    License: Apache License 2.0 6 votes vote down vote up
/**
 *
 * This method will be used to set the current state of the FilterMap
 * representing the state of when filters should be applied.
 */
public void setDispatcher(String dispatcherString) {
    String dispatcher = dispatcherString.toUpperCase(Locale.ENGLISH);
    
    if (dispatcher.equals(DispatcherType.FORWARD.name())) {
        // apply FORWARD to the global dispatcherMapping.
        dispatcherMapping |= FORWARD;
    } else if (dispatcher.equals(DispatcherType.INCLUDE.name())) {
        // apply INCLUDE to the global dispatcherMapping.
        dispatcherMapping |= INCLUDE;
    } else if (dispatcher.equals(DispatcherType.REQUEST.name())) {
        // apply REQUEST to the global dispatcherMapping.
        dispatcherMapping |= REQUEST;
    }  else if (dispatcher.equals(DispatcherType.ERROR.name())) {
        // apply ERROR to the global dispatcherMapping.
        dispatcherMapping |= ERROR;
    }  else if (dispatcher.equals(DispatcherType.ASYNC.name())) {
        // apply ERROR to the global dispatcherMapping.
        dispatcherMapping |= ASYNC;
    }
}
 
Example 5
Source Project: Tomcat8-Source-Read   Source File: TestELInJsp.java    License: MIT License 6 votes vote down vote up
@Test
public void testBug57142() throws Exception {
    getTomcatInstanceTestWebapp(false, true);

    ByteChunk res = getUrl("http://localhost:" + getPort() +
            "/test/bug5nnnn/bug57142.jsp");

    String result = res.toString();
    // javax.servlet
    assertEcho(result, "00-" + DispatcherType.ASYNC);
    // No obvious static fields for javax.servlet.http
    // Could hack something with HttpUtils...
    // No obvious static fields for javax.servlet.jsp
    // Wild card (package) import
    assertEcho(result, "01-" + RoundingMode.HALF_UP);
    // Class import
    assertEcho(result, "02-" + Collections.EMPTY_LIST.size());
}
 
Example 6
Source Project: Tomcat8-Source-Read   Source File: TestJspContextWrapper.java    License: MIT License 6 votes vote down vote up
@Test
public void testELTagFileImports() throws Exception {
    getTomcatInstanceTestWebapp(false, true);

    ByteChunk out = new ByteChunk();

    int rc = getUrl("http://localhost:" + getPort() + "/test/bug5nnnn/bug58178b.jsp", out, null);

    Assert.assertEquals(HttpServletResponse.SC_OK, rc);

    String result = out.toString();

    Assert.assertTrue(result, result.contains("00-" + DispatcherType.ASYNC));
    // No obvious status fields for javax.servlet.http
    // Could hack something with HttpUtils...
    // No obvious status fields for javax.servlet.jsp
    // Wild card (package) import
    Assert.assertTrue(result, result.contains("01-" + RoundingMode.HALF_UP));
    // Class import
    Assert.assertTrue(result, result.contains("02-" + Collections.EMPTY_LIST.size()));
}
 
Example 7
Source Project: supplierShop   Source File: FilterConfig.java    License: MIT License 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
@Bean
public FilterRegistrationBean xssFilterRegistration()
{
    FilterRegistrationBean registration = new FilterRegistrationBean();
    registration.setDispatcherTypes(DispatcherType.REQUEST);
    registration.setFilter(new XssFilter());
    registration.addUrlPatterns(StringUtils.split(urlPatterns, ","));
    registration.setName("xssFilter");
    registration.setOrder(Integer.MAX_VALUE);
    Map<String, String> initParameters = new HashMap<String, String>();
    initParameters.put("excludes", excludes);
    initParameters.put("enabled", enabled);
    registration.setInitParameters(initParameters);
    return registration;
}
 
Example 8
Source Project: pinpoint   Source File: AbstractServerHandleInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void before(Object target, Object[] args) {
    if (isDebug) {
        logger.beforeInterceptor(target, args);
    }

    try {
        final HttpServletRequest request = toHttpServletRequest(args);
        if (request.getDispatcherType() == DispatcherType.ASYNC || request.getDispatcherType() == DispatcherType.ERROR) {
            if (isDebug) {
                logger.debug("Skip async servlet request event. isAsyncStarted={}, dispatcherType={}", request.isAsyncStarted(), request.getDispatcherType());
            }
            return;
        }
        this.servletRequestListenerInterceptorHelper.initialized(request, JettyConstants.JETTY_METHOD, this.methodDescriptor);
    } catch (Throwable t) {
        logger.info("Failed to servlet request event handle.", t);
    }
}
 
Example 9
Source Project: Tomcat7.0.67   Source File: FilterMap.java    License: Apache License 2.0 6 votes vote down vote up
public String[] getDispatcherNames() {
    ArrayList<String> result = new ArrayList<String>();
    if ((dispatcherMapping & FORWARD) > 0) {
        result.add(DispatcherType.FORWARD.name());
    }
    if ((dispatcherMapping & INCLUDE) > 0) {
        result.add(DispatcherType.INCLUDE.name());
    }
    if ((dispatcherMapping & REQUEST) > 0) {
        result.add(DispatcherType.REQUEST.name());
    }
    if ((dispatcherMapping & ERROR) > 0) {
        result.add(DispatcherType.ERROR.name());
    }
    if ((dispatcherMapping & ASYNC) > 0) {
        result.add(DispatcherType.ASYNC.name());
    }
    return result.toArray(new String[result.size()]);
}
 
Example 10
@Override public void init(ServletContextHandler handler) {
  AnnotationConfigWebApplicationContext appContext =
    new AnnotationConfigWebApplicationContext() {
      // overriding this allows us to register dependencies of TracingHandlerInterceptor
      // without passing static state to a configuration class.
      @Override protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) {
        beanFactory.registerSingleton("httpTracing", httpTracing);
        super.loadBeanDefinitions(beanFactory);
      }
    };

  appContext.register(Servlet3TestController.class); // the test resource
  appContext.register(TracingConfig.class); // generic tracing setup
  DispatcherServlet servlet = new DispatcherServlet(appContext);
  servlet.setDispatchOptionsRequest(true);
  ServletHolder servletHolder = new ServletHolder(servlet);
  servletHolder.setAsyncSupported(true);
  handler.addServlet(servletHolder, "/*");
  handler.addEventListener(new ContextLoaderListener(appContext));

  // add the trace filter, which lazy initializes a real tracing filter from the spring context
  Dynamic filterRegistration =
    handler.getServletContext().addFilter("tracingFilter", DelegatingTracingFilter.class);
  filterRegistration.setAsyncSupported(true);
  filterRegistration.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
}
 
Example 11
/**
 * Constructor.
 */
public DefaultWebApplicationRequest() {
    this.authType = null;
    this.asyncStarted = false;
    this.asyncSupported = false;
    this.attributeManager = new DefaultAttributeManager();
    this.characterEncoding = "ISO-8859-1";
    this.contentLength = -1;
    this.contentType = null;
    this.contextPath = "";
    this.cookies = null;
    this.dispatcherType = DispatcherType.REQUEST;
    this.headerManager = new DefaultHttpHeaderManager();
    this.headerManager.setHeader("Accept", "*/*");
    this.inputStream = new ByteArrayInputStream(new byte[0]);
    this.method = "GET";
    this.protocol = "HTTP/1.1";
    this.scheme = "http";
    this.serverName = "localhost";
    this.serverPort = 80;
    this.servletPath = "";
    this.parameters = new HashMap<>();
    this.upgraded = false;
}
 
Example 12
Source Project: spring-analysis-note   Source File: ForwardedHeaderFilterTests.java    License: MIT License 6 votes vote down vote up
@Test // SPR-16983
public void forwardedRequestWithServletForward() throws Exception {
	this.request.setRequestURI("/foo");
	this.request.addHeader(X_FORWARDED_PROTO, "https");
	this.request.addHeader(X_FORWARDED_HOST, "www.mycompany.com");
	this.request.addHeader(X_FORWARDED_PORT, "443");

	this.filter.doFilter(this.request, new MockHttpServletResponse(), this.filterChain);
	HttpServletRequest wrappedRequest = (HttpServletRequest) this.filterChain.getRequest();

	this.request.setDispatcherType(DispatcherType.FORWARD);
	this.request.setRequestURI("/bar");
	this.filterChain.reset();

	this.filter.doFilter(wrappedRequest, new MockHttpServletResponse(), this.filterChain);
	HttpServletRequest actual = (HttpServletRequest) this.filterChain.getRequest();

	assertNotNull(actual);
	assertEquals("/bar", actual.getRequestURI());
	assertEquals("https://www.mycompany.com/bar", actual.getRequestURL().toString());
}
 
Example 13
Source Project: lams   Source File: FilterHandler.java    License: GNU General Public License v2.0 6 votes vote down vote up
public FilterHandler(final Map<DispatcherType, List<ManagedFilter>> filters, final boolean allowNonStandardWrappers, final HttpHandler next) {
    this.allowNonStandardWrappers = allowNonStandardWrappers;
    this.next = next;
    this.filters = new EnumMap<>(filters);
    Map<DispatcherType, Boolean> asyncSupported = new EnumMap<>(DispatcherType.class);
    for(Map.Entry<DispatcherType, List<ManagedFilter>> entry : filters.entrySet()) {
        boolean supported = true;
        for(ManagedFilter i : entry.getValue()) {
            if(!i.getFilterInfo().isAsyncSupported()) {
                supported = false;
                break;
            }
        }
        asyncSupported.put(entry.getKey(), supported);
    }
    this.asyncSupported = asyncSupported;
}
 
Example 14
Source Project: pinpoint   Source File: AbstractServerHandleInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void after(Object target, Object[] args, Object result, Throwable throwable) {
    if (isDebug) {
        logger.afterInterceptor(target, args, result, throwable);
    }

    try {
        final HttpServletRequest request = toHttpServletRequest(args);
        final HttpServletResponse response = toHttpServletResponse(args);
        if (request.getDispatcherType() == DispatcherType.ASYNC || request.getDispatcherType() == DispatcherType.ERROR) {
            if (isDebug) {
                logger.debug("Skip async servlet request event. isAsyncStarted={}, dispatcherType={}", request.isAsyncStarted(), request.getDispatcherType());
            }
            return;
        }
        final int statusCode = getStatusCode(response);
        this.servletRequestListenerInterceptorHelper.destroyed(request, throwable, statusCode);
    } catch (Throwable t) {
        if (isInfo) {
            logger.info("Failed to servlet request event handle.", t);
        }
    }
}
 
Example 15
@Override
public void before(Object target, Object[] args) {
    if (isDebug) {
        logger.beforeInterceptor(target, args);
    }

    if (!argumentValidator.validate(args)) {
        return;
    }

    try {
        final HttpServletRequest request = (HttpServletRequest) args[0];
        if (request.getDispatcherType() == DispatcherType.ASYNC) {
            if (isDebug) {
                logger.debug("Skip async servlet Request. isAsyncStarted={}, dispatcherType={}", request.isAsyncStarted(), request.getDispatcherType());
            }
            return;
        }

        this.servletRequestListenerInterceptorHelper.initialized(request, ResinConstants.RESIN_METHOD, this.methodDescriptor);
    } catch (Throwable t) {
        if (isInfo) {
            logger.info("Failed to servlet request event handle.", t);
        }
    }
}
 
Example 16
Source Project: tomcatsrc   Source File: FilterMap.java    License: Apache License 2.0 6 votes vote down vote up
public String[] getDispatcherNames() {
    ArrayList<String> result = new ArrayList<String>();
    if ((dispatcherMapping & FORWARD) > 0) {
        result.add(DispatcherType.FORWARD.name());
    }
    if ((dispatcherMapping & INCLUDE) > 0) {
        result.add(DispatcherType.INCLUDE.name());
    }
    if ((dispatcherMapping & REQUEST) > 0) {
        result.add(DispatcherType.REQUEST.name());
    }
    if ((dispatcherMapping & ERROR) > 0) {
        result.add(DispatcherType.ERROR.name());
    }
    if ((dispatcherMapping & ASYNC) > 0) {
        result.add(DispatcherType.ASYNC.name());
    }
    return result.toArray(new String[result.size()]);
}
 
Example 17
Source Project: registry   Source File: RegistryApplication.java    License: Apache License 2.0 6 votes vote down vote up
private void addServletFilters(RegistryConfiguration registryConfiguration, Environment environment) {
    List<ServletFilterConfiguration> servletFilterConfigurations = registryConfiguration.getServletFilters();
    if (servletFilterConfigurations != null && !servletFilterConfigurations.isEmpty()) {
        for (ServletFilterConfiguration servletFilterConfig : servletFilterConfigurations) {
            try {
                String className = servletFilterConfig.getClassName();
                Map<String, String> params = servletFilterConfig.getParams();
                String typeSuffix = params.get("type") != null ? ("-" + params.get("type").toString()) : "";
                LOG.info("Registering servlet filter [{}]", servletFilterConfig);
                Class<? extends Filter> filterClass = (Class<? extends Filter>) Class.forName(className);
                FilterRegistration.Dynamic dynamic = environment.servlets().addFilter(className + typeSuffix, filterClass);
                if (params != null) {
                    dynamic.setInitParameters(params);
                }
                dynamic.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
            } catch (Exception e) {
                LOG.error("Error registering servlet filter {}", servletFilterConfig);
                throw new RuntimeException(e);
            }
        }
    }
}
 
Example 18
Source Project: quarkus-http   Source File: FilterHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    ServletRequest request = servletRequestContext.getServletRequest();
    ServletResponse response = servletRequestContext.getServletResponse();
    DispatcherType dispatcher = servletRequestContext.getDispatcherType();
    Boolean supported = asyncSupported.get(dispatcher);
    if(supported != null && ! supported) {
        servletRequestContext.setAsyncSupported(false);
    }

    final List<ManagedFilter> filters = this.filters.get(dispatcher);
    if(filters == null) {
        next.handleRequest(exchange);
    } else {
        final FilterChainImpl filterChain = new FilterChainImpl(exchange, filters, next, allowNonStandardWrappers);
        filterChain.doFilter(request, response);
    }
}
 
Example 19
@Override
public void onStartup(ServletContext servletContext) throws ServletException {

	/* Setting the configuration classes */
	AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
	context.setConfigLocation("qa.qcri.aidr.data.config");

	/*Configuring error handler filter for errors out isde the controllers
	FilterRegistration.Dynamic errorHandlerFilter = servletContext.addFilter("errorHandlerFilter", new ErrorHandlerFilter());
	errorHandlerFilter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
	*/
	FilterRegistration.Dynamic encodingFilter = servletContext.addFilter("encodingFilter", new org.springframework.web.filter.CharacterEncodingFilter());
	encodingFilter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
	encodingFilter.setInitParameter("encoding", "UTF-8");
	encodingFilter.setInitParameter("forceEncoding", "true");
	
	/* Adding context listener */
	servletContext.addListener(new ContextLoaderListener(context));
	
	/* Adding request listener */
	servletContext.addListener(new RequestContextListener());

	/* Configuring dispatcher servlet for spring mvc */
	/*CustomDispatcherServlet servlet = new CustomDispatcherServlet(context); */
	ServletRegistration.Dynamic appServlet = servletContext.addServlet("dispatcher", new DispatcherServlet(context));
	appServlet.setLoadOnStartup(1);
	appServlet.addMapping("/*");
}
 
Example 20
Source Project: ja-micro   Source File: JettyComposer.java    License: Apache License 2.0 5 votes vote down vote up
public static void compose(Server server) {
    //Servlets + Guice
    ServletContextHandler servletContextHandler = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS);
    servletContextHandler.addFilter(GuiceFilter.class, "/*", EnumSet.allOf(DispatcherType.class));
    servletContextHandler.addServlet(DefaultServlet.class, "/");

    //JMX stuff...
    MBeanContainer mbContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
    server.addEventListener(mbContainer);
    server.addBean(mbContainer);
    server.addBean(Log.getLog());
}
 
Example 21
Source Project: Tomcat8-Source-Read   Source File: Request.java    License: MIT License 5 votes vote down vote up
@Override
public DispatcherType getDispatcherType() {
    if (internalDispatcherType == null) {
        return DispatcherType.REQUEST;
    }

    return this.internalDispatcherType;
}
 
Example 22
Source Project: cloudbreak   Source File: CommonFilterConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public FilterRegistrationBean spanFinishingFilter() {
    FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
    filterRegistrationBean.setFilter(new SpanFinishingFilter());
    filterRegistrationBean.setAsyncSupported(true);
    filterRegistrationBean.setOrder(Integer.MIN_VALUE);
    filterRegistrationBean.setDispatcherTypes(DispatcherType.REQUEST);
    filterRegistrationBean.addUrlPatterns("*");
    return filterRegistrationBean;
}
 
Example 23
Source Project: flowable-engine   Source File: WebConfigurer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Initializes Spring Security.
 */
private void initSpringSecurity(ServletContext servletContext, EnumSet<DispatcherType> disps) {
    LOGGER.debug("Registering Spring Security Filter");
    FilterRegistration.Dynamic springSecurityFilter = servletContext.addFilter("springSecurityFilterChain", new DelegatingFilterProxy());

    springSecurityFilter.addMappingForUrlPatterns(disps, false, "/*");
}
 
Example 24
Source Project: spectator   Source File: IpcServletFilterTest.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeAll
public static void init() throws Exception {
  server = new Server(new InetSocketAddress("localhost", 0));
  ServletHandler handler = new ServletHandler();
  handler.addServletWithMapping(OkServlet.class, "/test/foo/*");
  handler.addServletWithMapping(OkServlet.class, "/api/*");
  handler.addServletWithMapping(BadRequestServlet.class, "/bad/*");
  handler.addServletWithMapping(FailServlet.class, "/throw/*");
  handler.addServletWithMapping(CustomEndpointServlet.class, "/endpoint/*");
  handler.addServletWithMapping(OkServlet.class, "/*");
  handler.addFilterWithMapping(IpcServletFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
  server.setHandler(handler);
  server.start();
  baseUri = server.getURI();
}
 
Example 25
Source Project: lams   Source File: DefaultServlet.java    License: GNU General Public License v2.0 5 votes vote down vote up
private boolean isAllowed(String path, DispatcherType dispatcherType) {
    if (!path.isEmpty()) {
        if(dispatcherType == DispatcherType.REQUEST) {
            //WFLY-3543 allow the dispatcher to access stuff in web-inf and meta inf
            if (path.startsWith("/META-INF") ||
                    path.startsWith("META-INF") ||
                    path.startsWith("/WEB-INF") ||
                    path.startsWith("WEB-INF")) {
                return false;
            }
        }
    }
    if(defaultAllowed && disallowed.isEmpty()) {
        return true;
    }
    int pos = path.lastIndexOf('/');
    final String lastSegment;
    if (pos == -1) {
        lastSegment = path;
    } else {
        lastSegment = path.substring(pos + 1);
    }
    if (lastSegment.isEmpty()) {
        return true;
    }
    int ext = lastSegment.lastIndexOf('.');
    if (ext == -1) {
        //no extension
        return true;
    }
    final String extension = lastSegment.substring(ext + 1, lastSegment.length());
    if (defaultAllowed) {
        return !disallowed.contains(extension);
    } else {
        return allowed.contains(extension);
    }
}
 
Example 26
@Override
public void addMappingForUrlPatterns(
        EnumSet<DispatcherType> dispatcherTypes, boolean isMatchAfter,
        String... urlPatterns) {

    FilterMap filterMap = new FilterMap();

    filterMap.setFilterName(filterDef.getFilterName());

    if (dispatcherTypes != null) {
        for (DispatcherType dispatcherType : dispatcherTypes) {
            filterMap.setDispatcher(dispatcherType.name());
        }
    }

    if (urlPatterns != null) {
        // % decoded (if necessary) using UTF-8
        for (String urlPattern : urlPatterns) {
            filterMap.addURLPattern(urlPattern);
        }

        if (isMatchAfter) {
            context.addFilterMap(filterMap);
        } else {
            context.addFilterMapBefore(filterMap);
        }
    }
    // else error?

}
 
Example 27
Source Project: quarkus-http   Source File: ServletInitialHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    final String path = exchange.getRelativePath();
    if (isForbiddenPath(path)) {
        exchange.setStatusCode(StatusCodes.NOT_FOUND);
        return;
    }
    final ServletPathMatch info = paths.getServletHandlerByPath(path);
    if (info.getType() == ServletPathMatch.Type.REWRITE) {
        // this can only happen if the path ends with a /
        // otherwise there would be a redirect instead
        exchange.setRelativePath(info.getRewriteLocation());
        exchange.setRequestPath(exchange.getResolvedPath() + info.getRewriteLocation());
    }
    final HttpServletResponseImpl response = new HttpServletResponseImpl(exchange, servletContext);
    final HttpServletRequestImpl request = new HttpServletRequestImpl(exchange, servletContext);
    final ServletRequestContext servletRequestContext = new ServletRequestContext(servletContext.getDeployment(), request, response, info);
    //set the max request size if applicable
    if (info.getServletChain().getManagedServlet().getMaxRequestSize() > 0) {
        exchange.setMaxEntitySize(info.getServletChain().getManagedServlet().getMaxRequestSize());
    }
    exchange.putAttachment(ServletRequestContext.ATTACHMENT_KEY, servletRequestContext);

    exchange.startBlocking(new ServletBlockingHttpExchange(exchange));
    servletRequestContext.setServletPathMatch(info);

    Executor executor = info.getServletChain().getExecutor();
    if (executor == null) {
        executor = servletContext.getDeployment().getExecutor();
    }

    if (exchange.isInIoThread() || executor != null) {
        //either the exchange has not been dispatched yet, or we need to use a special executor
        exchange.dispatch(executor, dispatchHandler);
    } else {
        dispatchRequest(exchange, servletRequestContext, info.getServletChain(), DispatcherType.REQUEST);
    }
}
 
Example 28
private void configureCors(Environment environment) {
  FilterRegistration.Dynamic filter = environment.servlets().addFilter("CORS", CrossOriginFilter.class);
  filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
  filter.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET,PUT,POST,DELETE,OPTIONS");
  filter.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*");
  filter.setInitParameter(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, "*");
  filter.setInitParameter("allowedHeaders", "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin");
  filter.setInitParameter("allowCredentials", "true");
}
 
Example 29
Source Project: activiti6-boot2   Source File: WebConfigurer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Initializes Spring Security.
 */
private void initSpringSecurity(ServletContext servletContext, EnumSet<DispatcherType> disps) {
  log.debug("Registering Spring Security Filter");
  FilterRegistration.Dynamic springSecurityFilter = servletContext.addFilter("springSecurityFilterChain", new DelegatingFilterProxy());

  springSecurityFilter.addMappingForUrlPatterns(disps, false, "/*");
}
 
Example 30
public TestApplicationContextGetRequestDispatcherB(String startMapping, String startUri,
       DispatcherType dispatcherType, String targetMapping, String targetUri,
       boolean useEncodedDispatchPaths,
       String expectedRequestURI, String expectedContextPath, String expectedServletPath,
       String expectedPathInfo, String expectedQueryString, MappingMatch expectedMappingMatch,
       String expectedMappingPattern, String expectedMappingMatchValue,
       String expectedMappingServletName,
       String expectedDispatcherRequestURI, String expectedDispatcherContextPath,
       String expectedDispatcherServletPath, String expectedDispatcherPathInfo,
       String expectedDispatcherQueryString, MappingMatch expectedDispatcherMappingMatch,
       String expectedDispatcherMappingPattern, String expectedDispatcherMappingMatchValue,
       String expectedDispatcherMappingServletName,
       String expectedBody) {
   this.startMapping = startMapping;
   this.startUri = startUri;
   this.dispatcherType = dispatcherType;
   this.targetMapping = targetMapping;
   this.targetUri = targetUri;
   this.useEncodedDispatchPaths = useEncodedDispatchPaths;
   this.expectedRequestURI = expectedRequestURI;
   this.expectedContextPath = expectedContextPath;
   this.expectedServletPath = expectedServletPath;
   this.expectedPathInfo = expectedPathInfo;
   this.expectedQueryString = expectedQueryString;
   this.expectedMappingMatch = expectedMappingMatch;
   this.expectedMappingPattern = expectedMappingPattern;
   this.expectedMappingMatchValue = expectedMappingMatchValue;
   this.expectedMappingServletName = expectedMappingServletName;
   this.expectedDispatcherRequestURI = expectedDispatcherRequestURI;
   this.expectedDispatcherContextPath = expectedDispatcherContextPath;
   this.expectedDispatcherServletPath = expectedDispatcherServletPath;
   this.expectedDispatcherPathInfo = expectedDispatcherPathInfo;
   this.expectedDispatcherQueryString = expectedDispatcherQueryString;
   this.expectedDispatcherMappingMatch = expectedDispatcherMappingMatch;
   this.expectedDispatcherMappingPattern = expectedDispatcherMappingPattern;
   this.expectedDispatcherMappingMatchValue = expectedDispatcherMappingMatchValue;
   this.expectedDispatcherMappingServletName = expectedDispatcherMappingServletName;
   this.expectedBody = expectedBody;
}