org.eclipse.jetty.servlet.FilterHolder Java Examples

The following examples show how to use org.eclipse.jetty.servlet.FilterHolder. 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: HttpServer2.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
@Override
public void addFilter(String name, String classname,
    Map<String, String> parameters) {

  FilterHolder filterHolder = getFilterHolder(name, classname, parameters);
  FilterMapping fmap =
      getFilterMapping(name, new String[] {"*.html", "*.jsp"});
  defineFilter(webAppContext, filterHolder, fmap);
  LOG.info("Added filter {} (class={}) to context {}", name, classname,
          webAppContext.getDisplayName());
  fmap = getFilterMapping(name, new String[] {"/*"});
  for (Map.Entry<ServletContextHandler, Boolean> e
      : defaultContexts.entrySet()) {
    if (e.getValue()) {
      ServletContextHandler ctx = e.getKey();
      defineFilter(ctx, filterHolder, fmap);
      LOG.info("Added filter {} (class={}) to context {}", name, classname,
              ctx.getDisplayName());
    }
  }
  filterNames.add(name);
}
 
Example #2
Source File: Poseidon.java    From Poseidon with Apache License 2.0 6 votes vote down vote up
private void addFilters(ServletContextHandler servletContextHandler) {
    // RequestContext is required in other filters, hence set it up first
    servletContextHandler.addFilter(new FilterHolder(new HystrixContextFilter(configuration)), "/*", EnumSet.of(REQUEST));
    // Set up distributed tracing filter
    ServletTraceFilter servletTraceFilter = ServletTraceFilterBuilder.build(configuration);
    if (servletTraceFilter != null) {
        servletContextHandler.addFilter(new FilterHolder(servletTraceFilter), "/*", EnumSet.of(REQUEST));
    }
    servletContextHandler.addFilter(new FilterHolder(new RequestGzipFilter()), "/*", EnumSet.of(REQUEST));

    List<JettyFilterConfiguration> jettyFilterConfigurations = Optional.ofNullable(configuration.getJettyConfiguration()).map(JettyConfiguration::getJettyFilterConfigurations).orElse(new ArrayList<>());
    for (JettyFilterConfiguration filterConfig : jettyFilterConfigurations) {
        FilterHolder filterHolder = new FilterHolder(filterConfig.getFilter());
        filterHolder.setInitParameters(filterConfig.getInitParameters());
        for (String mapping : filterConfig.getMappings()) {
            servletContextHandler.addFilter(filterHolder, mapping, filterConfig.getDispatcherTypes());
        }
    }
}
 
Example #3
Source File: RESTApp.java    From account-provisioning-for-google-apps with Apache License 2.0 6 votes vote down vote up
/**
 * Initializes the Jersey Servlet.
 */
private void initJerseyServlet() {
  servletContext = new ServletContextHandler(ServletContextHandler.SESSIONS);
  servletContext.setContextPath("/");
  // This is used for allowing access to different domains/ports.
  FilterHolder filterHolder = new FilterHolder(CrossOriginFilter.class);
  filterHolder.setInitParameter("allowedOrigins", "*");
  filterHolder.setInitParameter("allowedMethods", "GET, POST");
  servletContext.addFilter(filterHolder, "/*", null);

  jerseyServlet = servletContext.addServlet(org.glassfish.jersey.servlet.ServletContainer.class, "/*");
  jerseyServlet.setInitOrder(0);

  // Tell the Jersey Servlet which REST class to load.
  jerseyServlet.setInitParameter("jersey.config.server.provider.classnames",
      ProvisioningAction.class.getCanonicalName());
}
 
Example #4
Source File: WorkerServer.java    From pulsar with Apache License 2.0 6 votes vote down vote up
public static ServletContextHandler newServletContextHandler(String contextPath, ResourceConfig config, WorkerService workerService, boolean requireAuthentication) {
    final ServletContextHandler contextHandler =
            new ServletContextHandler(ServletContextHandler.NO_SESSIONS);

    contextHandler.setAttribute(FunctionApiResource.ATTRIBUTE_FUNCTION_WORKER, workerService);
    contextHandler.setAttribute(WorkerApiV2Resource.ATTRIBUTE_WORKER_SERVICE, workerService);
    contextHandler.setAttribute(WorkerStatsApiV2Resource.ATTRIBUTE_WORKERSTATS_SERVICE, workerService);
    contextHandler.setContextPath(contextPath);

    final ServletHolder apiServlet =
            new ServletHolder(new ServletContainer(config));
    contextHandler.addServlet(apiServlet, "/*");
    if (workerService.getWorkerConfig().isAuthenticationEnabled() && requireAuthentication) {
        FilterHolder filter = new FilterHolder(new AuthenticationFilter(workerService.getAuthenticationService()));
        contextHandler.addFilter(filter, MATCH_ALL, EnumSet.allOf(DispatcherType.class));
    }

    return contextHandler;
}
 
Example #5
Source File: HTTPHeaderFiltersTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testCSPHeaderAppliedOnlyOnce() throws ServletException, IOException, Exception {
    // Arrange

    FilterHolder originFilter = new FilterHolder(new ContentSecurityPolicyFilter());

    // Set up request
    HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class);
    MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    FilterChain mockFilterChain = Mockito.mock(FilterChain.class);

    // Action
    originFilter.start();
    originFilter.initialize();
    originFilter.getFilter().doFilter(mockRequest, mockResponse, mockFilterChain);
    originFilter.getFilter().doFilter(mockRequest, mockResponse, mockFilterChain);

    // Verify
    assertEquals("frame-ancestors 'self'", mockResponse.getHeader("Content-Security-Policy"));
}
 
Example #6
Source File: WebServerModule.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Provides(type = Type.SET)
ContextConfigurator provideHeaderFilter() {
  return new ContextConfigurator() {
    @Override
    public void init(ServletContextHandler context) {
      FilterHolder filter = new FilterHolder(new HeaderFilter());
      filter.setInitParameter("headerConfig", "set X-Frame-Options: DENY");
      context.addFilter(filter, "/*", EnumSet.of(
          DispatcherType.FORWARD,
          DispatcherType.REQUEST,
          DispatcherType.INCLUDE,
          DispatcherType.ASYNC,
          DispatcherType.ERROR
      ));
    }
  };
}
 
Example #7
Source File: HttpServer2.java    From knox with Apache License 2.0 6 votes vote down vote up
@Override
public void addFilter(String name, String classname,
                      Map<String, String> parameters) {

  FilterHolder filterHolder = getFilterHolder(name, classname, parameters);
  final String[] USER_FACING_URLS = { "*.html", "*.jsp" };
  FilterMapping fmap = getFilterMapping(name, USER_FACING_URLS);
  defineFilter(webAppContext, filterHolder, fmap);
  LOG.info(
      "Added filter " + name + " (class=" + classname + ") to context "
          + webAppContext.getDisplayName());
  final String[] ALL_URLS = { "/*" };
  fmap = getFilterMapping(name, ALL_URLS);
  for (Map.Entry<ServletContextHandler, Boolean> e
      : defaultContexts.entrySet()) {
    if (e.getValue()) {
      ServletContextHandler ctx = e.getKey();
      defineFilter(ctx, filterHolder, fmap);
      LOG.info("Added filter " + name + " (class=" + classname
                   + ") to context " + ctx.getDisplayName());
    }
  }
  filterNames.add(name);
}
 
Example #8
Source File: Main.java    From Embedded-Jetty-RESTEasy-Guice-Example with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    Injector injector = Guice.createInjector(new HelloModule(args));

    injector.getAllBindings();

    injector.createChildInjector().getAllBindings();

    Server server = new Server(8080);
    ServletContextHandler servletHandler = new ServletContextHandler();
    servletHandler.addEventListener(injector.getInstance(GuiceResteasyBootstrapServletContextListener.class));

    ServletHolder sh = new ServletHolder(HttpServletDispatcher.class);
    servletHandler.setInitParameter("resteasy.role.based.security", "true");
    servletHandler.addFilter(new FilterHolder(injector.getInstance(HelloFilter.class)), "/*", null);
    //servletHandler.addServlet(DefaultServlet.class, "/*");
    servletHandler.addServlet(sh, "/*");

    server.setHandler(servletHandler);
    server.start();
    server.join();
}
 
Example #9
Source File: HTTPHeaderFiltersTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testXSSProtectionHeaderApplied() throws ServletException, IOException, Exception {
    // Arrange

    FilterHolder xssFilter = new FilterHolder(new XSSProtectionFilter());

    // Set up request
    HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class);
    MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    FilterChain mockFilterChain = Mockito.mock(FilterChain.class);

    // Action
    xssFilter.start();
    xssFilter.initialize();
    xssFilter.getFilter().doFilter(mockRequest, mockResponse, mockFilterChain);

    // Verify
    assertEquals("1; mode=block", mockResponse.getHeader("X-XSS-Protection"));
}
 
Example #10
Source File: ContentLengthFilterTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
private void configureAndStartServer(HttpServlet servlet, int maxFormContentSize) throws Exception {
    serverUnderTest = new Server();
    localConnector = new LocalConnector(serverUnderTest);
    localConnector.setIdleTimeout(SERVER_IDLE_TIMEOUT);
    serverUnderTest.addConnector(localConnector);

    contextUnderTest = new ServletContextHandler(serverUnderTest, "/");
    if (maxFormContentSize > 0) {
        contextUnderTest.setMaxFormContentSize(maxFormContentSize);
    }
    contextUnderTest.addServlet(new ServletHolder(servlet), "/*");

    // This only adds the ContentLengthFilter if a valid maxFormContentSize is not provided
    if (maxFormContentSize < 0) {
        FilterHolder holder = contextUnderTest.addFilter(ContentLengthFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
        holder.setInitParameter(ContentLengthFilter.MAX_LENGTH_INIT_PARAM, String.valueOf(MAX_CONTENT_LENGTH));
    }
    serverUnderTest.start();
}
 
Example #11
Source File: AbstractParentSpanResolutionTest.java    From java-jaxrs with Apache License 2.0 6 votes vote down vote up
@Override
protected void initTracing(ServletContextHandler context) {
    client.register(new ClientTracingFeature.Builder(mockTracer).build());

    ServerTracingDynamicFeature.Builder builder = new ServerTracingDynamicFeature.Builder(mockTracer);
    if (shouldUseParentSpan()) {
        builder = builder.withJoinExistingActiveSpan(true);
    }
    ServerTracingDynamicFeature serverTracingFeature = builder.build();

    context.addFilter(new FilterHolder(new SpanFinishingFilter()),
            "/*", EnumSet.of(DispatcherType.REQUEST));

    context.setAttribute(TRACER_ATTRIBUTE, mockTracer);
    context.setAttribute(CLIENT_ATTRIBUTE, client);
    context.setAttribute(SERVER_TRACING_FEATURE, serverTracingFeature);
}
 
Example #12
Source File: DSSSpringApplication.java    From DataSphereStudio with Apache License 2.0 6 votes vote down vote up
@Bean
public WebServerFactoryCustomizer<JettyServletWebServerFactory> jettyFactoryCustomizer() {
    return new WebServerFactoryCustomizer<JettyServletWebServerFactory>() {
        public void customize(JettyServletWebServerFactory jettyServletWebServerFactory) {
            jettyServletWebServerFactory.addServerCustomizers(new JettyServerCustomizer() {
                public void customize(Server server) {
                    Handler[] childHandlersByClass = server.getChildHandlersByClass(WebAppContext.class);
                    final WebAppContext webApp = (WebAppContext) childHandlersByClass[0];
                    FilterHolder filterHolder = new FilterHolder(CharacterEncodingFilter.class);
                    filterHolder.setInitParameter("encoding", Configuration.BDP_ENCODING().getValue());
                    filterHolder.setInitParameter("forceEncoding", "true");
                    webApp.addFilter(filterHolder, "/*", EnumSet.allOf(DispatcherType.class));
                    BDPJettyServerHelper.setupRestApiContextHandler(webApp);
                    if(ServerConfiguration.BDP_SERVER_SOCKET_MODE().getValue()) {
                        BDPJettyServerHelper.setupControllerServer(webApp);
                    }
                    if(!ServerConfiguration.BDP_SERVER_DISTINCT_MODE().getValue()) {
                        BDPJettyServerHelper.setupWebAppContext(webApp);
                    }
                }
            });
        }
    };
}
 
Example #13
Source File: HTTPHeaderFiltersTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testCSPHeaderApplied() throws ServletException, IOException, Exception {
    // Arrange

    FilterHolder originFilter = new FilterHolder(new ContentSecurityPolicyFilter());

    // Set up request
    HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class);
    MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    FilterChain mockFilterChain = Mockito.mock(FilterChain.class);

    // Action
    originFilter.start();
    originFilter.initialize();
    originFilter.getFilter().doFilter(mockRequest, mockResponse, mockFilterChain);

    // Verify
    assertEquals("frame-ancestors 'self'", mockResponse.getHeader("Content-Security-Policy"));
}
 
Example #14
Source File: HttpServer2.java    From knox with Apache License 2.0 6 votes vote down vote up
@Override
public void addFilter(String name, String classname,
                      Map<String, String> parameters) {

  FilterHolder filterHolder = getFilterHolder(name, classname, parameters);
  final String[] USER_FACING_URLS = { "*.html", "*.jsp" };
  FilterMapping fmap = getFilterMapping(name, USER_FACING_URLS);
  defineFilter(webAppContext, filterHolder, fmap);
  LOG.info(
      "Added filter " + name + " (class=" + classname + ") to context "
          + webAppContext.getDisplayName());
  final String[] ALL_URLS = { "/*" };
  fmap = getFilterMapping(name, ALL_URLS);
  for (Map.Entry<ServletContextHandler, Boolean> e
      : defaultContexts.entrySet()) {
    if (e.getValue()) {
      ServletContextHandler ctx = e.getKey();
      defineFilter(ctx, filterHolder, fmap);
      LOG.info("Added filter " + name + " (class=" + classname
                   + ") to context " + ctx.getDisplayName());
    }
  }
  filterNames.add(name);
}
 
Example #15
Source File: HttpServer.java    From hbase with Apache License 2.0 6 votes vote down vote up
/**
 * Add an internal servlet in the server, specifying whether or not to
 * protect with Kerberos authentication.
 * Note: This method is to be used for adding servlets that facilitate
 * internal communication and not for user facing functionality. For
 * servlets added using this method, filters (except internal Kerberos
 * filters) are not enabled.
 *
 * @param name The name of the servlet (can be passed as null)
 * @param pathSpec The path spec for the servlet
 * @param clazz The servlet class
 * @param requireAuth Require Kerberos authenticate to access servlet
 */
void addInternalServlet(String name, String pathSpec,
    Class<? extends HttpServlet> clazz, boolean requireAuthz) {
  ServletHolder holder = new ServletHolder(clazz);
  if (name != null) {
    holder.setName(name);
  }
  if (authenticationEnabled && requireAuthz) {
    FilterHolder filter = new FilterHolder(AdminAuthorizedFilter.class);
    filter.setName(AdminAuthorizedFilter.class.getSimpleName());
    FilterMapping fmap = new FilterMapping();
    fmap.setPathSpec(pathSpec);
    fmap.setDispatches(FilterMapping.ALL);
    fmap.setFilterName(AdminAuthorizedFilter.class.getSimpleName());
    webAppContext.getServletHandler().addFilter(filter, fmap);
  }
  webAppContext.addServlet(holder, pathSpec);
}
 
Example #16
Source File: YanagishimaServer.java    From yanagishima with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    Properties properties = loadProperties(args, new OptionParser());
    YanagishimaConfig config = new YanagishimaConfig(properties);

    Injector injector = createInjector(properties);

    createTables(injector.getInstance(TinyORM.class), config.getDatabaseType());

    Server server = new Server(config.getServerPort());
    server.setAttribute("org.eclipse.jetty.server.Request.maxFormContentSize", -1);

    ServletContextHandler servletContextHandler = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS);
    servletContextHandler.addFilter(new FilterHolder(new YanagishimaFilter(config.corsEnabled(), config.getAuditHttpHeaderName())), "/*", EnumSet.of(DispatcherType.REQUEST));
    servletContextHandler.addFilter(GuiceFilter.class, "/*", EnumSet.allOf(DispatcherType.class));
    servletContextHandler.addServlet(DefaultServlet.class, "/");
    servletContextHandler.setResourceBase(properties.getProperty("web.resource.dir", "web"));

    LOGGER.info("Yanagishima Server started...");
    server.start();

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            LOGGER.info("Shutting down Yanagishima Server...");
            try {
                server.stop();
                server.destroy();
            } catch (Exception e) {
                LOGGER.error("Error while shutting down Yanagishima Server", e);
            }
        }
    });
    LOGGER.info("Yanagishima Server running port " + config.getServerPort());
}
 
Example #17
Source File: HttpServer2.java    From knox with Apache License 2.0 5 votes vote down vote up
@Override
public void addGlobalFilter(String name, String classname,
                            Map<String, String> parameters) {
  final String[] ALL_URLS = { "/*" };
  FilterHolder filterHolder = getFilterHolder(name, classname, parameters);
  FilterMapping fmap = getFilterMapping(name, ALL_URLS);
  defineFilter(webAppContext, filterHolder, fmap);
  for (ServletContextHandler ctx : defaultContexts.keySet()) {
    defineFilter(ctx, filterHolder, fmap);
  }
  LOG.info("Added global filter '" + name + "' (class=" + classname + ")");
}
 
Example #18
Source File: RESTServer.java    From hbase with Apache License 2.0 5 votes vote down vote up
private void addClickjackingPreventionFilter(ServletContextHandler ctxHandler,
    Configuration conf) {
  FilterHolder holder = new FilterHolder();
  holder.setName("clickjackingprevention");
  holder.setClassName(ClickjackingPreventionFilter.class.getName());
  holder.setInitParameters(ClickjackingPreventionFilter.getDefaultParameters(conf));
  ctxHandler.addFilter(holder, PATH_SPEC_ANY, EnumSet.allOf(DispatcherType.class));
}
 
Example #19
Source File: Application.java    From rest-utils with Apache License 2.0 5 votes vote down vote up
/**
 * Register header filter to ServletContextHandler.
 * @param context The serverlet context handler
 */
protected void configureHttpResponsHeaderFilter(ServletContextHandler context) {
  String headerConfig = config.getString(RestConfig.RESPONSE_HTTP_HEADERS_CONFIG);
  log.debug("headerConfig : " + headerConfig);
  String[] configs = StringUtil.csvSplit(headerConfig);
  Arrays.stream(configs)
          .forEach(RestConfig::validateHttpResponseHeaderConfig);
  FilterHolder headerFilterHolder = new FilterHolder(HeaderFilter.class);
  headerFilterHolder.setInitParameter("headerConfig", headerConfig);
  context.addFilter(headerFilterHolder, "/*", EnumSet.of(DispatcherType.REQUEST));
}
 
Example #20
Source File: HelloBrotliApplication.java    From jbrotli with Apache License 2.0 5 votes vote down vote up
@Override
  public void run(HelloBrotliConfiguration configuration, Environment environment) {
    final FilterHolder brotliFilterHolder = new FilterHolder(checkNotNull(new BrotliServletFilter()));
    brotliFilterHolder.setName("BrotliCompressionFilter");
    brotliFilterHolder.setInitParameter(BrotliServletFilter.BROTLI_COMPRESSION_PARAMETER_QUALITY, "5");
//    brotliFilterHolder.setInitParameter(BrotliServletFilter.BROTLI_COMPRESSION_PARAMETER_MODE, "GENERIC");
//    brotliFilterHolder.setInitParameter(BrotliServletFilter.BROTLI_COMPRESSION_PARAMETER_LGBLOCK, "0");
//    brotliFilterHolder.setInitParameter(BrotliServletFilter.BROTLI_COMPRESSION_PARAMETER_LGWIN, "22");
    environment.getApplicationContext().getServletHandler().addFilter(brotliFilterHolder);
    brotliFilterHolder.getRegistration().addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");

    environment.jersey().register(new HelloBrotliResource());
  }
 
Example #21
Source File: WebServerModule.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Provides(type = Type.SET)
ContextConfigurator provideSubjectInContext(final UserGroupManager userGroupManager) {
  return new ContextConfigurator() {
    @Override
    public void init(ServletContextHandler context) {
      FilterHolder filter = new FilterHolder(new GroupsInScopeFilter());
      context.addFilter(filter, "/*", EnumSet.of(DispatcherType.REQUEST));
    }
  };
}
 
Example #22
Source File: WebServerModule.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Provides(type = Type.SET)
ContextConfigurator provideNoAuthenticationRoles(final Configuration configuration, final RuntimeInfo runtimeInfo) {
  return new ContextConfigurator() {
    @Override
    public void init(ServletContextHandler context) {
      if (configuration.get(WebServerTask.AUTHENTICATION_KEY, WebServerTask.AUTHENTICATION_DEFAULT).equals("none") &&
          !runtimeInfo.isDPMEnabled()) {
        FilterHolder filter = new FilterHolder(new AlwaysAllRolesFilter());
        context.addFilter(filter, "/*", EnumSet.of(DispatcherType.REQUEST));
      }
    }
  };
}
 
Example #23
Source File: TestServerApplication.java    From jbrotli with Apache License 2.0 5 votes vote down vote up
@Override
public void run(TestServerConfiguration configuration, Environment environment) {
  final FilterHolder brotliFilterHolder = new FilterHolder(checkNotNull(new BrotliServletFilter()));
  brotliFilterHolder.setName("BrotliCompressionFilter");
  environment.getApplicationContext().getServletHandler().addFilter(brotliFilterHolder);
  brotliFilterHolder.getRegistration().addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");
}
 
Example #24
Source File: AbstractServerWithTraceNothingTest.java    From java-jaxrs with Apache License 2.0 5 votes vote down vote up
@Override
protected void initTracing(ServletContextHandler context) {
    client.register(new ClientTracingFeature.Builder(mockTracer).build());

    ServerTracingDynamicFeature serverTracingBuilder =
            new ServerTracingDynamicFeature.Builder(mockTracer)
                    .withTraceNothing() // This should only trace @Traced annotations, per documentation!
                    .build();
    context.addFilter(new FilterHolder(new SpanFinishingFilter()),
            "/*", EnumSet.of(DispatcherType.REQUEST));

    context.setAttribute(TRACER_ATTRIBUTE, mockTracer);
    context.setAttribute(CLIENT_ATTRIBUTE, client);
    context.setAttribute(SERVER_TRACING_FEATURE, serverTracingBuilder);
}
 
Example #25
Source File: AbstractServerDefaultConfigurationTest.java    From java-jaxrs with Apache License 2.0 5 votes vote down vote up
@Override
protected void initTracing(ServletContextHandler context) {
    client.register(new Builder(mockTracer).build());

    ServerTracingDynamicFeature serverTracingBuilder =
            new ServerTracingDynamicFeature.Builder(mockTracer)
                    .build();
    context.addFilter(new FilterHolder(new SpanFinishingFilter()),
        "/*", EnumSet.of(DispatcherType.REQUEST));

    context.setAttribute(TRACER_ATTRIBUTE, mockTracer);
    context.setAttribute(CLIENT_ATTRIBUTE, client);
    context.setAttribute(SERVER_TRACING_FEATURE, serverTracingBuilder);
}
 
Example #26
Source File: JettyServer.java    From nifi with Apache License 2.0 5 votes vote down vote up
private void performInjectionForComponentUis(final Collection<WebAppContext> componentUiExtensionWebContexts,
                                             final NiFiWebConfigurationContext configurationContext, final FilterHolder securityFilter) {
    if (CollectionUtils.isNotEmpty(componentUiExtensionWebContexts)) {
        for (final WebAppContext customUiContext : componentUiExtensionWebContexts) {
            // set the NiFi context in each custom ui servlet context
            final ServletContext customUiServletContext = customUiContext.getServletHandler().getServletContext();
            customUiServletContext.setAttribute("nifi-web-configuration-context", configurationContext);

            // add the security filter to any ui extensions wars
            if (securityFilter != null) {
                customUiContext.addFilter(securityFilter, "/*", EnumSet.allOf(DispatcherType.class));
            }
        }
    }
}
 
Example #27
Source File: HttpServer2.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
@Override
public void addGlobalFilter(String name, String classname,
    Map<String, String> parameters) {
  FilterHolder filterHolder = getFilterHolder(name, classname, parameters);
  FilterMapping fmap = getFilterMapping(name, new String[] {"/*"});
  defineFilter(webAppContext, filterHolder, fmap);
  for (ServletContextHandler ctx : defaultContexts.keySet()) {
    defineFilter(ctx, filterHolder, fmap);
  }
  LOG.info("Added global filter '{}' (class={})", name, classname);
}
 
Example #28
Source File: AbstractClassOperationNameTest.java    From java-jaxrs with Apache License 2.0 5 votes vote down vote up
@Override
protected void initTracing(ServletContextHandler context) {
  client.register(new Builder(mockTracer).build());

  ServerTracingDynamicFeature serverTracingBuilder =
      new ServerTracingDynamicFeature.Builder(mockTracer)
          .withOperationNameProvider(ClassNameOperationName.newBuilder())
          .build();
  context.addFilter(new FilterHolder(new SpanFinishingFilter()),
      "/*", EnumSet.of(DispatcherType.REQUEST));

  context.setAttribute(TRACER_ATTRIBUTE, mockTracer);
  context.setAttribute(CLIENT_ATTRIBUTE, client);
  context.setAttribute(SERVER_TRACING_FEATURE, serverTracingBuilder);
}
 
Example #29
Source File: JettyServer.java    From pippo with Apache License 2.0 5 votes vote down vote up
private void addPippoFilter(ServletContextHandler handler) {
    if (pippoFilterPath == null) {
        pippoFilterPath = "/*"; // default value
    }

    EnumSet<DispatcherType> dispatches = EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR);

    FilterHolder pippoFilterHolder = new FilterHolder(getPippoFilter());
    handler.addFilter(pippoFilterHolder, pippoFilterPath, dispatches);
    log.debug("Using pippo filter for path '{}'", pippoFilterPath);
}
 
Example #30
Source File: WebMappingsRenderer.java    From dropwizard-guicey with MIT License 5 votes vote down vote up
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
private Multimap<String, FilterReference> renderContextFilters(final MappingsConfig config,
                                                               final MutableServletContextHandler handler,
                                                               final TreeNode root) throws Exception {
    final Multimap<String, FilterReference> servletFilters = LinkedHashMultimap.create();
    for (FilterMapping mapping : handler.getServletHandler().getFilterMappings()) {
        final FilterHolder holder = handler.getServletHandler().getFilter(mapping.getFilterName());
        // single filter instance used for both contexts and so the name is also the same
        final boolean isGuiceFilter = mapping.getFilterName().equals(GuiceWebModule.GUICE_FILTER);
        if ((isGuiceFilter && !config.isGuiceMappings())
                || !isAllowed(holder.getClassName(), config)) {
            continue;
        }
        if (mapping.getServletNames() != null && mapping.getServletNames().length > 0) {
            // filters targeting exact servlet are only remembered to be shown below target servlet
            for (String servlet : mapping.getServletNames()) {
                servletFilters.put(servlet, new FilterReference(mapping, holder));
            }
        } else {
            final TreeNode filter = renderFilter(mapping, holder, root);
            if (isGuiceFilter) {
                renderGuiceWeb(filter);
            }
        }
    }
    return servletFilters;
}