Java Code Examples for org.eclipse.jetty.servlet.ServletHandler#addFilterWithMapping()

The following examples show how to use org.eclipse.jetty.servlet.ServletHandler#addFilterWithMapping() . 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: JettyServletTest.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void beforeClass() throws Exception {
  System.setProperty(Configuration.SPAN_DECORATORS, "io.opentracing.contrib.specialagent.rule.servlet.MockSpanDecorator");
  System.setProperty(Configuration.SKIP_PATTERN, "/skipit");

  server = new Server(0);

  final ServletHandler servletHandler = new ServletHandler();
  servletHandler.addServletWithMapping(MockServlet.class, "/hello");
  servletHandler.addServletWithMapping(MockServlet.class, "/skipit");
  servletHandler.addFilterWithMapping(MockFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
  server.setHandler(servletHandler);

  server.start();
  serverPort = ((ServerConnector)server.getConnectors()[0]).getLocalPort();
}
 
Example 2
Source File: SecurityTest.java    From cloud-security-xsuaa-integration with Apache License 2.0 6 votes vote down vote up
void startApplicationServer() throws Exception {
	WebAppContext context = createWebAppContext();
	ServletHandler servletHandler = createServletHandler(context);

	applicationServletsByPath
			.forEach((path, servletHolder) -> servletHandler.addServletWithMapping(servletHolder, path));
	applicationServletFilters.forEach((filterHolder) -> servletHandler
			.addFilterWithMapping(filterHolder, "/*", EnumSet.of(DispatcherType.REQUEST)));

	servletHandler
			.addFilterWithMapping(new FilterHolder(new SecurityFilter()), "/*", EnumSet.of(DispatcherType.REQUEST));

	applicationServer = new Server(applicationServerOptions.getPort());
	applicationServer.setHandler(context);
	applicationServer.start();
}
 
Example 3
Source File: ThriftOverHttpClientTServletIntegrationTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static Server startHttp1() throws Exception {
    final Server server = new Server(0);

    final ServletHandler handler = new ServletHandler();
    handler.addServletWithMapping(newServletHolder(thriftServlet), TSERVLET_PATH);
    handler.addServletWithMapping(newServletHolder(rootServlet), "/");
    handler.addFilterWithMapping(new FilterHolder(new ConnectionCloseFilter()), "/*",
                                 EnumSet.of(DispatcherType.REQUEST));

    server.setHandler(handler);

    for (Connector c : server.getConnectors()) {
        for (ConnectionFactory f : c.getConnectionFactories()) {
            for (String p : f.getProtocols()) {
                if (p.startsWith("h2c")) {
                    fail("Attempted to create a Jetty server without HTTP/2 support, but failed: " +
                         f.getProtocols());
                }
            }
        }
    }

    server.start();
    return server;
}
 
Example 4
Source File: NoContextJettyTest.java    From java-web-servlet-filter with Apache License 2.0 5 votes vote down vote up
@Before
public void beforeTest() throws Exception {
	mockTracer = Mockito.spy(new MockTracer(new ThreadLocalScopeManager(), MockTracer.Propagator.TEXT_MAP));

	ServletHandler servletHandler = new ServletHandler();
	servletHandler.addServletWithMapping(TestServlet.class, "/hello");

	servletHandler.addFilterWithMapping(new FilterHolder(tracingFilter()), "/*", EnumSet.of(DispatcherType.REQUEST,
			DispatcherType.FORWARD, DispatcherType.ASYNC, DispatcherType.ERROR, DispatcherType.INCLUDE));

	jettyServer = new Server(0);
	jettyServer.setHandler(servletHandler);
	jettyServer.start();
	serverPort = ((ServerConnector) jettyServer.getConnectors()[0]).getLocalPort();
}
 
Example 5
Source File: IpcServletFilterTest.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));
  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 6
Source File: JdbcBridge.java    From clickhouse-jdbc-bridge with Apache License 2.0 4 votes vote down vote up
@Override
@SneakyThrows
public void run() {
    log.info("Starting jdbc-bridge");

    JdbcDriverLoader.load(config.getDriverPath());

    BridgeConnectionManager manager = new BridgeConnectionManager();
    if (null != config.getConnectionFile()) {
        manager.load(config.getConnectionFile());
    }

    ServletHandler handler = new ServletHandler();
    handler.addServletWithMapping(new ServletHolder(new QueryHandlerServlet(manager)), "/");
    handler.addServletWithMapping(new ServletHolder(new ColumnsInfoServlet(manager, new ClickHouseConverter())), "/columns_info");
    handler.addServletWithMapping(new ServletHolder(new IdentifierQuoteServlet(manager)), "/identifier_quote");
    handler.addServletWithMapping(new ServletHolder(new PingHandlerServlet()), "/ping");
    handler.addFilterWithMapping(RequestLogger.class, "/*", EnumSet.of(DispatcherType.REQUEST));

    InetSocketAddress address = new InetSocketAddress(config.getListenHost(), config.getHttpPort());
    log.info("Will bind to {}", address);

    // this tricks are don in order to get good thread name in logs :(
    QueuedThreadPool pool = new QueuedThreadPool(1024, 10); // @todo make configurable?
    pool.setName("HTTP Handler");
    Server jettyServer = new Server(pool);
    ServerConnector connector = new ServerConnector(jettyServer);

    // @todo a temporary solution for dealing with too long URI for some endpoints
    HttpConfiguration httpConfiguration = new HttpConfiguration();
    httpConfiguration.setRequestHeaderSize(24 * 1024);
    HttpConnectionFactory factory = new HttpConnectionFactory(httpConfiguration);
    connector.setConnectionFactories(Collections.singleton(factory));

    connector.setHost(address.getHostName());
    connector.setPort(address.getPort());
    jettyServer.setConnectors(new Connector[]{connector});

    jettyServer.setHandler(handler);
    jettyServer.setErrorHandler(new ErrorHandler() {
        @Override
        protected void handleErrorPage(HttpServletRequest request, Writer writer, int code, String message) throws IOException {
            writer.write(message);
        }
    });

    try {
        log.info("Starting server");
        jettyServer.start();
        log.info("Server is ready to accept connections");
        jettyServer.join();
    } finally {
        jettyServer.destroy();
    }
}
 
Example 7
Source File: ODataTestServer.java    From syndesis with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings( "deprecation" )
private void initServer(SSLContext sslContext, String userName) throws UnknownHostException {
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath(FORWARD_SLASH);
    this.setHandler(context);

    ServletHandler productsHandler = new ServletHandler();
    productsHandler.addServletWithMapping(
        ProductsServlet.class,
        FORWARD_SLASH + PRODUCTS_SVC + FORWARD_SLASH + STAR);
    productsHandler.addFilterWithMapping(ODataPathFilter.class, FORWARD_SLASH + STAR, FilterMapping.REQUEST);
    context.insertHandler(productsHandler);

    if (userName != null) {
        LoginService loginService = new HashLoginService("MyRealm", "src/test/resources/realm.properties");
        this.addBean(loginService);

        ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
        Constraint constraint = new Constraint();
        constraint.setName("auth");
        constraint.setAuthenticate(true);
        constraint.setRoles(new String[] { USER, "admin" });

        ConstraintMapping mapping = new ConstraintMapping();
        mapping.setPathSpec(FORWARD_SLASH + PRODUCTS_SVC + FORWARD_SLASH + STAR);
        mapping.setConstraint(constraint);

        securityHandler.setConstraintMappings(Collections.singletonList(mapping));
        securityHandler.setAuthenticator(new BasicAuthenticator());

        context.setSecurityHandler(securityHandler);
    }

    httpConnector = new ServerConnector(this);
    httpConnector.setPort(httpPort); // Finds next available port if still 0
    this.addConnector(httpConnector);


    if (sslContext != null) {
        // HTTPS
        HttpConfiguration httpConfiguration = new HttpConfiguration();
        httpConfiguration.setSecureScheme("https");
        httpConfiguration.setSecurePort(httpsPort); // Finds next available port if still 0
        httpConfiguration.addCustomizer(new SecureRequestCustomizer());

        final SslContextFactory sslContextFactory = new SslContextFactory();
        sslContextFactory.setSslContext(sslContext);
        httpsConnector = new ServerConnector(this, sslContextFactory, new HttpConnectionFactory(httpConfiguration));
        httpsConnector.setPort(httpsPort); // Finds next available port if still 0
        this.addConnector(httpsConnector);
    }
}
 
Example 8
Source File: Application.java    From sqs-exporter with Apache License 2.0 4 votes vote down vote up
private void go() throws Exception {
	DefaultExports.initialize();
	new Sqs().register();

	Server server = new Server(9384);

	ServletHandler handler = new ServletHandler();
	server.setHandler(handler);
	handler.addServletWithMapping(IndexServlet.class, "/");
	handler.addServletWithMapping(MetricsServlet.class, "/metrics");
	handler.addFilterWithMapping(DisableMethodsFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));

	server.start();

	logger.info("Exporter has started.");
	startup.inc();
	
	HttpGenerator.setJettyVersion("");

	server.join();

}
 
Example 9
Source File: WebDAVServer.java    From MtgDesktopCompanion with GNU General Public License v3.0 3 votes vote down vote up
@Override
public void start() throws IOException {
	server = new Server(getInt(SERVER_PORT));
	
	
	log = getString(LOGIN);
	pas = getString(PASS);
	
	
	ServletContextHandler ctx = new ServletContextHandler(ServletContextHandler.SESSIONS);
	ctx.setContextPath("/");
	
	ServletHandler handler = new ServletHandler();
	
	ctx.addServlet(new ServletHolder("default", new MiltonServlet()),"/");
	
	
	FilterHolder fh = handler.addFilterWithMapping(MiltonFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
				 fh.setInitParameter("resource.factory.class", WebDavMTGResourceFactory.class.getCanonicalName());
				 

	ctx.addFilter(fh, "/*", EnumSet.of(DispatcherType.REQUEST));
				 
	logger.trace(ctx.dump());

	ctx.setHandler(handler);
	server.setHandler(ctx);
	
	try {
		server.start();
		logger.info("Webdav start on port http://"+InetAddress.getLocalHost().getHostName() + ":"+getInt(SERVER_PORT));

	} catch (Exception e) {
		throw new IOException(e);
	}
}