Java Code Examples for org.eclipse.jetty.servlet.ServletContextHandler#addFilter()

The following examples show how to use org.eclipse.jetty.servlet.ServletContextHandler#addFilter() . 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: HttpManagement.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
private void addFiltersAndServletsForRest(final ServletContextHandler root)
{
    FilterHolder loggingFilter = new FilterHolder(new LoggingFilter());
    root.addFilter(loggingFilter, "/api/*", EnumSet.of(DispatcherType.REQUEST));
    root.addFilter(loggingFilter, "/service/*", EnumSet.of(DispatcherType.REQUEST));

    FilterHolder restAuthorizationFilter = new FilterHolder(new AuthenticationCheckFilter());
    restAuthorizationFilter.setInitParameter(AuthenticationCheckFilter.INIT_PARAM_ALLOWED, "/service/sasl");
    root.addFilter(restAuthorizationFilter, "/api/*", EnumSet.of(DispatcherType.REQUEST));
    root.addFilter(restAuthorizationFilter, "/service/*", EnumSet.of(DispatcherType.REQUEST));

    addRestServlet(root);

    ServletHolder queryServlet = new ServletHolder(new BrokerQueryServlet());
    root.addServlet(queryServlet, "/api/latest/querybroker/*");
    root.addServlet(queryServlet, "/api/v" + BrokerModel.MODEL_VERSION + "/querybroker/*");

    ServletHolder vhQueryServlet = new ServletHolder(new VirtualHostQueryServlet());
    root.addServlet(vhQueryServlet, "/api/latest/queryvhost/*");
    root.addServlet(vhQueryServlet, "/api/v" + BrokerModel.MODEL_VERSION + "/queryvhost/*");

    root.addServlet(new ServletHolder(new StructureServlet()), "/service/structure");
    root.addServlet(new ServletHolder(new QueueReportServlet()), "/service/queuereport/*");
    root.addServlet(new ServletHolder(new MetaDataServlet()), "/service/metadata");
    root.addServlet(new ServletHolder(new TimeZoneServlet()), "/service/timezones");
}
 
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: ServerCmdlet.java    From HongsCORE with MIT License 6 votes vote down vote up
private void addFilter(ServletContextHandler context, Class clso, WebFilter anno) {
    DispatcherType[]  ds = anno.dispatcherTypes(  );
    List   <DispatcherType> ls = Arrays .asList(ds);
    EnumSet<DispatcherType> es = EnumSet.copyOf(ls);

    FilterHolder  hd = new FilterHolder (clso );
    hd.setName          (anno.filterName(    ));
    hd.setAsyncSupported(anno.asyncSupported());

    for(WebInitParam nv : anno.initParams ()) {
        hd.setInitParameter(nv.name( ), nv.value());
    }

    for(String       ur : anno.urlPatterns()) {
        context.addFilter (hd, ur, es);
    }
}
 
Example 4
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 5
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 6
Source File: HelloServer.java    From new-bull with MIT License 6 votes vote down vote up
@Override
public void run(String... strings) throws Exception {
    Server server = new Server(8888);

    ServletContextHandler helloHandler = new ServletContextHandler(SESSIONS);
    helloHandler.setContextPath("/hello");
    helloHandler.addServlet(HelloServlet.class, "/*");
    helloHandler.addFilter(HelloFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));

    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[] {helloHandler});
    server.setHandler(handlers);
    server.start();
    log.info("hello server started");
    server.join();
}
 
Example 7
Source File: Main.java    From wingtips with Apache License 2.0 6 votes vote down vote up
private static ServletContextHandler generateServletContextHandler() throws IOException {
    ServletContextHandler contextHandler = new ServletContextHandler();
    contextHandler.setContextPath("/");

    ResourceConfig rc = new WebAppResourceConfig(Collections.<String, Object>emptyMap(), contextHandler.getServletContext());
    rc.getSingletons().add(new SampleResource());
    ServletContainer jerseyServletContainer = new ServletContainer(rc);
    contextHandler.addServlet(SampleResource.SampleAsyncServlet.class, SampleResource.ASYNC_PATH);
    contextHandler.addServlet(SampleResource.SampleBlockingForwardServlet.class, SampleResource.BLOCKING_FORWARD_PATH);
    contextHandler.addServlet(SampleResource.SampleAsyncForwardServlet.class, SampleResource.ASYNC_FORWARD_PATH);
    contextHandler.addServlet(SampleResource.SampleAsyncTimeoutServlet.class, SampleResource.ASYNC_TIMEOUT_PATH);
    contextHandler.addServlet(SampleResource.SampleAsyncErrorServlet.class, SampleResource.ASYNC_ERROR_PATH);
    contextHandler.addServlet(new ServletHolder(jerseyServletContainer), "/*");
    contextHandler.addFilter(RequestTracingFilter.class, "/*", EnumSet.allOf(DispatcherType.class));
    return contextHandler;
}
 
Example 8
Source File: GraphQlServer.java    From rejoiner with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
  Server server = new Server(HTTP_PORT);

  ServletContextHandler context = new ServletContextHandler(server, "/", SESSIONS);

  context.addEventListener(
      new GuiceServletContextListener() {
        @Override
        protected Injector getInjector() {
          return Guice.createInjector(
              new ServletModule() {
                @Override
                protected void configureServlets() {
                  serve("/graphql").with(GraphQlServlet.class);
                }
              },
              new DataLoaderModule(),
              new SchemaProviderModule(), // Part of Rejoiner framework (Provides `@Schema
              // GraphQLSchema`)
              new ClientModule(), // Installs all of the client modules
              new SchemaModule() // Installs all of the schema modules
              );
        }
      });

  context.addFilter(GuiceFilter.class, "/*", EnumSet.of(REQUEST, ASYNC));

  context.setBaseResource(
      new PathResource(new File("./src/main/resources").toPath().toRealPath()));
  context.addServlet(DefaultServlet.class, "/");
  server.start();
  logger.info("Server running on port " + HTTP_PORT);
  server.join();
}
 
Example 9
Source File: JettyComposer.java    From ja-micro with 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 10
Source File: ExplorerServer.java    From Explorer with Apache License 2.0 5 votes vote down vote up
private static ServletContextHandler setupRestApiContextHandler() {
    final ServletHolder cxfServletHolder = new ServletHolder(new CXFNonSpringJaxrsServlet());
    cxfServletHolder.setInitParameter("javax.ws.rs.Application", ExplorerServer.class.getName());
    cxfServletHolder.setName("rest");
    cxfServletHolder.setForcedPath("rest");

    final ServletContextHandler cxfContext = new ServletContextHandler();
    cxfContext.setSessionHandler(new SessionHandler());
    cxfContext.setContextPath("/api");
    cxfContext.addServlet(cxfServletHolder, "/*");
    cxfContext.addFilter(new FilterHolder(CorsFilter.class), "/*",
            EnumSet.allOf(DispatcherType.class));
    return cxfContext;
}
 
Example 11
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 12
Source File: ManagementApiServer.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
public void attachHandlers() {

        // Create the servlet context
        final ServletContextHandler context = new ServletContextHandler(this.server, entrypoint, ServletContextHandler.SESSIONS);

        // REST configuration
        final ServletHolder servletHolder = new ServletHolder(ServletContainer.class);
        servletHolder.setInitParameter("javax.ws.rs.Application", ManagementApplication.class.getName());
        servletHolder.setInitOrder(1);
        servletHolder.setAsyncSupported(true);

        AnnotationConfigWebApplicationContext webApplicationContext = new AnnotationConfigWebApplicationContext();
        webApplicationContext.setEnvironment((ConfigurableEnvironment) applicationContext.getEnvironment());
        webApplicationContext.setParent(applicationContext);
        webApplicationContext.setServletContext(context.getServletContext());

        webApplicationContext.register(ManagementConfiguration.class);

        context.addEventListener(new ContextLoaderListener(webApplicationContext));
        context.addServlet(servletHolder, "/*");
        context.addServlet(new ServletHolder(new DispatcherServlet(webApplicationContext)), "/auth/*");

        // X-Forwarded-* support
        context.addFilter(ForwardedHeaderFilter.class, "/*", EnumSet.allOf(DispatcherType.class));

        // Spring Security filter
        context.addFilter(new FilterHolder(new DelegatingFilterProxy("springSecurityFilterChain")), "/*", EnumSet.allOf(DispatcherType.class));
    }
 
Example 13
Source File: EmbeddedServer.java    From javamelody with Apache License 2.0 5 votes vote down vote up
/**
 * Start the server with a http port and optional javamelody parameters.
 * @param port Http port
 * @param parameters Optional javamelody parameters
 * @throws Exception e
 */
public static void start(int port, Map<Parameter, String> parameters) throws Exception {
	// Init jetty
	server = new Server(port);
	final ContextHandlerCollection contexts = new ContextHandlerCollection();
	final ServletContextHandler context = new ServletContextHandler(contexts, "/",
			ServletContextHandler.SESSIONS);

	final net.bull.javamelody.MonitoringFilter monitoringFilter = new net.bull.javamelody.MonitoringFilter();
	monitoringFilter.setApplicationType("Standalone");
	final FilterHolder filterHolder = new FilterHolder(monitoringFilter);
	if (parameters != null) {
		for (final Map.Entry<Parameter, String> entry : parameters.entrySet()) {
			final net.bull.javamelody.Parameter parameter = entry.getKey();
			final String value = entry.getValue();
			filterHolder.setInitParameter(parameter.getCode(), value);
		}
	}
	context.addFilter(filterHolder, "/*",
			EnumSet.of(DispatcherType.INCLUDE, DispatcherType.REQUEST));

	context.addEventListener(new SessionListener());

	final RequestLogHandler requestLogHandler = new RequestLogHandler();
	contexts.addHandler(requestLogHandler);

	final HandlerCollection handlers = new HandlerCollection();
	handlers.setHandlers(new Handler[] { contexts });
	server.setHandler(handlers);

	server.start();
}
 
Example 14
Source File: RequestLogTest.java    From cf-java-logging-support with Apache License 2.0 5 votes vote down vote up
private Server initJetty() throws Exception {
	Server server = new Server(0);
	ServletContextHandler handler = new ServletContextHandler(server, null);
	handler.addFilter(RequestLoggingFilter.class, "/*", EnumSet.of(DispatcherType.INCLUDE, DispatcherType.REQUEST,
			DispatcherType.ERROR, DispatcherType.FORWARD, DispatcherType.ASYNC));
	handler.addServlet(TestServlet.class, "/test");
	server.start();
	return server;
}
 
Example 15
Source File: GuiceServletFilterTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@BeforeAll
public static void init() throws Exception {
  server = new Server(new InetSocketAddress("localhost", 0));
  ServletContextHandler handler = new ServletContextHandler(server, "/");
  handler.addEventListener(new TestListener());
  handler.addFilter(GuiceFilter.class, "/*", EnumSet.allOf(DispatcherType.class));
  server.setHandler(handler);
  server.start();
  baseUri = server.getURI();
}
 
Example 16
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 17
Source File: AdminTransportConfiguration.java    From chassis with Apache License 2.0 4 votes vote down vote up
@Bean(initMethod="start", destroyMethod="stop")
@Order(0)
public Server adminServer(
           @Value("${admin.hostname}") String hostname,
           @Value("${admin.port}") int port) {

       // set up servlets
       ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SESSIONS | ServletContextHandler.NO_SECURITY);
	context.setErrorHandler(null);
	context.setWelcomeFiles(new String[] { "/" });
	
	// enable gzip
	context.addFilter(GzipFilter.class, "/*", null);
	
	// add common admin servlets
	context.addServlet(new ServletHolder(new HealthServlet(healthCheckRegistry)), "/healthcheck");
	context.addServlet(new ServletHolder(new ClasspathResourceServlet("com/kixeye/chassis/transport/admin", "/admin/", "index.html")), "/admin/*");
	context.addServlet(new ServletHolder(new PropertiesServlet()), "/admin/properties");
	context.addServlet(new ServletHolder(new ClasspathDumpServlet()), "/admin/classpath");

       // add websocket servlets if WebSockets have been initialized
       if (mappingRegistry != null && messageRegistry != null) {
           context.addServlet(new ServletHolder(new ProtobufMessagesDocumentationServlet(appName, mappingRegistry, messageRegistry)), "/schema/messages/protobuf");
           context.addServlet(new ServletHolder(new ProtobufEnvelopeDocumentationServlet()), "/schema/envelope/protobuf");
       }
	
       // add metric servlets if Metric has been initialized
       if (metricRegistry != null && healthCheckRegistry != null) {
           context.getServletContext().setAttribute(MetricsServlet.METRICS_REGISTRY, metricRegistry);
           context.getServletContext().setAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY, healthCheckRegistry);
           
           ServletHolder holder = new ServletHolder(new AdminServlet());
           holder.setInitParameter("service-name", System.getProperty("app.name"));
           context.addServlet(holder, "/metrics/*");
       }

       // create the server
   	InetSocketAddress address = StringUtils.isBlank(hostname) ? new InetSocketAddress(port) : new InetSocketAddress(hostname, port);
   	
   	Server server = new Server();

   	JettyConnectorRegistry.registerHttpConnector(server, address);
       server.setHandler(context);
   
	return server;
}
 
Example 18
Source File: HttpManagement.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
private Server createServer(Collection<HttpPort<?>> ports)
{
    LOGGER.debug("Starting up web server on {}", ports);

    _jettyServerExecutor = new ScheduledThreadPoolExecutor(1, new DaemonThreadFactory("Jetty-Server-Thread"));
    Server server = new Server(new ExecutorThreadPool(_jettyServerExecutor));
    int lastPort = -1;
    for (HttpPort<?> port : ports)
    {
        ServerConnector connector = createConnector(port, server);
        connector.addBean(new ConnectionTrackingListener());
        server.addConnector(connector);
        _portConnectorMap.put(port, connector);
        lastPort = port.getPort();
    }

    ServletContextHandler root = new ServletContextHandler(ServletContextHandler.SESSIONS);
    root.setContextPath("/");
    root.setCompactPath(true);
    server.setHandler(root);

    final ErrorHandler errorHandler = new ErrorHandler()
    {
        @Override
        protected void writeErrorPageBody(HttpServletRequest request, Writer writer, int code, String message, boolean showStacks)
                throws IOException
        {
            String uri= request.getRequestURI();

            writeErrorPageMessage(request,writer,code,message,uri);

            for (int i= 0; i < 20; i++)
                writer.write("<br/>                                                \n");
        }
    };
    root.setErrorHandler(errorHandler);

    // set servlet context attributes for broker and configuration
    root.getServletContext().setAttribute(HttpManagementUtil.ATTR_BROKER, getBroker());
    root.getServletContext().setAttribute(HttpManagementUtil.ATTR_MANAGEMENT_CONFIGURATION, this);

    root.addFilter(new FilterHolder(new ExceptionHandlingFilter()), "/*", EnumSet.allOf(DispatcherType.class));

    FilterHolder corsFilter = new FilterHolder(new CrossOriginFilter());
    corsFilter.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, getCorsAllowOrigins());
    corsFilter.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, Joiner.on(",").join(getCorsAllowMethods()));
    corsFilter.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, getCorsAllowHeaders());
    corsFilter.setInitParameter(CrossOriginFilter.ALLOW_CREDENTIALS_PARAM, String.valueOf(getCorsAllowCredentials()));
    root.addFilter(corsFilter, "/*", EnumSet.of(DispatcherType.REQUEST));

    root.addFilter(new FilterHolder(new ForbiddingTraceFilter()), "/*", EnumSet.of(DispatcherType.REQUEST));

    addFiltersAndServletsForRest(root);
    if (!Boolean.TRUE.equals(getContextValue(Boolean.class, DISABLE_UI_CONTEXT_NAME)))
    {
        addFiltersAndServletsForUserInterfaces(root);
    }

    root.getSessionHandler().getSessionCookieConfig().setName(JSESSIONID_COOKIE_PREFIX + lastPort);
    root.getSessionHandler().getSessionCookieConfig().setHttpOnly(true);
    root.getSessionHandler().setMaxInactiveInterval(getSessionTimeout());

    return server;
}
 
Example 19
Source File: RestApiSetup.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public static void installServletFilters(ServletContextHandler context, Collection<Class<? extends Filter>> filters) {
    for (Class<? extends Filter> filter : filters) {
        context.addFilter(filter, "/*", EnumSet.allOf(DispatcherType.class));
    }
}
 
Example 20
Source File: GatewayMicroService.java    From apiman with Apache License 2.0 4 votes vote down vote up
/**
 * @param apiManServer
 */
protected void addApiAuthFilter(ServletContextHandler apiManServer) {
    apiManServer.addFilter(AuthenticationFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
}