Java Code Examples for org.eclipse.jetty.servlet.ServletContextHandler

The following examples show how to use org.eclipse.jetty.servlet.ServletContextHandler. 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
Source Project: phoebus   Source File: WebServletsDemo.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public static void main(String[] args) throws Exception
{
    final Server server = new Server(8080);

    final ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SECURITY | ServletContextHandler.NO_SESSIONS);

    // Our servlets
    context.addServlet(HelloServlet.class, "/hello");
    context.addServlet(StopServlet.class, "/stop");

    // Serve static files from webroot to "/"
    context.setContextPath("/");
    context.setResourceBase(WebServletsDemo.class.getResource("/webroot").toExternalForm());
    context.addServlet(DefaultServlet.class, "/");

    server.setHandler(context);

    server.start();
    System.out.println("Running web server, check http://localhost:8080, http://localhost:8080/hello");
    do
        System.out.println("Main thread could do other things while web server is running...");
    while (! done.await(5, TimeUnit.SECONDS));
    server.stop();
    server.join();
    System.out.println("Done.");
}
 
Example 2
Source Project: java_examples   Source File: JavaSimple.java    License: Apache License 2.0 6 votes vote down vote up
public static void main( String[] args ) throws Exception {
    Server server = new Server(1234);
    ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    server.setHandler(context);
    // Expose our example servlet.
    context.addServlet(new ServletHolder(new ExampleServlet()), "/");
    // Expose Promtheus metrics.
    context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics");
    // Add metrics about CPU, JVM memory etc.
    DefaultExports.initialize();


    // Start the webserver.
    server.start();
    server.join();
}
 
Example 3
Source Project: HongsCORE   Source File: ServerCmdlet.java    License: 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
public static void main(String[] args) throws Exception {

        var websocketAddress = new InetSocketAddress("localhost", WEBSOCKET_PORT);
        var twootrServer = new TwootrServer(websocketAddress);
        twootrServer.start();

        System.setProperty("org.eclipse.jetty.LEVEL", "INFO");

        var context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setResourceBase(System.getProperty("user.dir") + "/src/main/webapp");
        context.setContextPath("/");

        ServletHolder staticContentServlet = new ServletHolder(
            "staticContentServlet", DefaultServlet.class);
        staticContentServlet.setInitParameter("dirAllowed", "true");
        context.addServlet(staticContentServlet, "/");

        var jettyServer = new Server(STATIC_PORT);
        jettyServer.setHandler(context);
        jettyServer.start();
        jettyServer.dumpStdErr();
        jettyServer.join();
    }
 
Example 5
Source Project: bootique   Source File: BQInternalWebServerTestFactory.java    License: Apache License 2.0 6 votes vote down vote up
@Provides
@Singleton
Server provideServer(Environment env, ShutdownManager shutdownManager) {
    Server server = new Server();

    ServerConnector connector = new ServerConnector(server);
    connector.setPort(12025);
    server.addConnector(connector);

    ServletContextHandler handler = new ServletContextHandler();
    handler.setContextPath("/");

    DefaultServlet servlet = new DefaultServlet();

    ServletHolder holder = new ServletHolder(servlet);
    handler.addServlet(holder, "/*");
    handler.setResourceBase(env.getProperty("bq.internaljetty.base"));

    server.setHandler(handler);

    shutdownManager.addShutdownHook(() -> {
        server.stop();
    });

    return server;
}
 
Example 6
Source Project: selenium   Source File: HttpClientTestBase.java    License: Apache License 2.0 6 votes vote down vote up
private HttpResponse executeWithinServer(HttpRequest request, HttpServlet servlet)
    throws Exception {
  Server server = new Server(PortProber.findFreePort());
  ServletContextHandler handler = new ServletContextHandler();
  handler.setContextPath("");
  ServletHolder holder = new ServletHolder(servlet);
  handler.addServlet(holder, "/*");

  server.setHandler(handler);

  server.start();
  try {
    HttpClient client = createFactory().createClient(fromUri(server.getURI()));
    return client.execute(request);
  } finally {
    server.stop();
  }
}
 
Example 7
Source Project: cxf   Source File: Server.java    License: Apache License 2.0 6 votes vote down vote up
protected Server() throws Exception {
    org.eclipse.jetty.server.Server server = new org.eclipse.jetty.server.Server(9000);

    final ServletHolder servletHolder = new ServletHolder(new CXFNonSpringJaxrsServlet());
    final ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    context.addServlet(servletHolder, "/*");
    servletHolder.setInitParameter("jaxrs.serviceClasses", Sample.class.getName());
    servletHolder.setInitParameter("jaxrs.features",
        Swagger2Feature.class.getName());
    servletHolder.setInitParameter("jaxrs.providers", StringUtils.join(
        new String[] {
            MultipartProvider.class.getName(),
            JacksonJsonProvider.class.getName(),
            ApiOriginFilter.class.getName()
        }, ",")
    );

    server.setHandler(context);
    server.start();
    server.join();
}
 
Example 8
@Bean
public Server jettyServer(ApplicationContext context) throws Exception {
    HttpHandler handler = WebHttpHandlerBuilder.applicationContext(context).build();
    Servlet servlet = new JettyHttpHandlerAdapter(handler);

    Server server = new Server();
    ServletContextHandler contextHandler = new ServletContextHandler(server, "");
    contextHandler.addServlet(new ServletHolder(servlet), "/");
    contextHandler.start();

    ServerConnector connector = new ServerConnector(server);
    connector.setHost("localhost");
    connector.setPort(port);
    server.addConnector(connector);

    return server;
}
 
Example 9
Source Project: knox   Source File: HttpServer2.java    License: 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 10
Source Project: flower   Source File: WebServer.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
  org.apache.ibatis.logging.LogFactory.useSlf4jLogging();
  ch.qos.logback.classic.Logger root =
      (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
  root.setLevel(Level.ERROR);
  org.eclipse.jetty.util.log.Log.setLog(new NoLogging());

  Server server = new Server(8080);
  ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
  context.setContextPath("/");
  server.setHandler(context);
  context.addServlet(new ServletHolder(new FlowServlet()), "/flow");
  context.addServlet(new ServletHolder(new SyncServlet()), "/sync");
  context.addServlet(new ServletHolder(new AsyncServlet()), "/async");
  context.addServlet(new ServletHolder(new ForkServlet()), "/test/fork");
  context.addServlet(new ServletHolder(new BlockServlet()), "/test/block");

  server.start();
  server.join();
}
 
Example 11
Source Project: phoebus   Source File: EngineWebServer.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public EngineWebServer(final int port)
{
    // Configure Jetty to use java.util.logging, and don't announce that it's doing that
    System.setProperty("org.eclipse.jetty.util.log.announce", "false");
    System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.JavaUtilLog");

    server = new Server(port);

    final ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SECURITY | ServletContextHandler.NO_SESSIONS);

    // Our servlets
    context.addServlet(MainServlet.class, "/main/*");
    context.addServlet(DisconnectedServlet.class, "/disconnected/*");
    context.addServlet(GroupsServlet.class, "/groups/*");
    context.addServlet(GroupServlet.class, "/group/*");
    context.addServlet(ChannelServlet.class, "/channel/*");
    context.addServlet(RestartServlet.class, "/restart/*");
    context.addServlet(StopServlet.class, "/stop/*");

    // Serve static files from webroot to "/"
    context.setContextPath("/");
    context.setResourceBase(EngineWebServer.class.getResource("/webroot").toExternalForm());
    context.addServlet(DefaultServlet.class, "/");

    server.setHandler(context);
}
 
Example 12
Source Project: Nicobar   Source File: ExplorerAppTest.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeClass
public void init() throws Exception {
    System.setProperty("archaius.deployment.applicationId","scriptmanager-app");
    System.setProperty("archaius.deployment.environment","dev");

    server = new Server(TEST_LOCAL_PORT);

    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    context.addEventListener(new KaryonGuiceContextListener());

    context.addFilter(GuiceFilter.class, "/*", 1);
    context.addServlet(DefaultServlet.class, "/");

    server.setHandler(context);

    server.start();
}
 
Example 13
Source Project: nifi   Source File: PrometheusServer.java    License: Apache License 2.0 6 votes vote down vote up
public PrometheusServer(int addr, SSLContextService sslContextService, ComponentLog logger, boolean needClientAuth, boolean wantClientAuth) throws Exception {
    PrometheusServer.logger = logger;
    this.server = new Server();
    this.handler = new ServletContextHandler(server, "/metrics");
    this.handler.addServlet(new ServletHolder(new MetricsServlet()), "/");

    SslContextFactory sslFactory = createSslFactory(sslContextService, needClientAuth, wantClientAuth);
    HttpConfiguration httpsConfiguration = new HttpConfiguration();
    httpsConfiguration.setSecureScheme("https");
    httpsConfiguration.setSecurePort(addr);
    httpsConfiguration.addCustomizer(new SecureRequestCustomizer());

    ServerConnector https = new ServerConnector(server, new SslConnectionFactory(sslFactory, "http/1.1"),
            new HttpConnectionFactory(httpsConfiguration));
    https.setPort(addr);
    this.server.setConnectors(new Connector[]{https});
    this.server.start();

}
 
Example 14
Source Project: java-slack-sdk   Source File: ProxyTest.java    License: MIT License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    // https://github.com/eclipse/jetty.project/blob/jetty-9.2.x/examples/embedded/src/main/java/org/eclipse/jetty/embedded/ProxyServer.java
    int port = PortProvider.getPort(ProxyTest.class.getName());
    connector.setPort(port);
    server.addConnector(connector);
    ConnectHandler proxy = new ConnectHandler() {
        @Override
        public void handle(String target, Request br, HttpServletRequest request, HttpServletResponse res)
                throws ServletException, IOException {
            log.info("ConnectHandler (target: {})", target);
            callCount.incrementAndGet();
            super.handle(target, br, request, res);
        }
    };
    server.setHandler(proxy);
    ServletContextHandler context = new ServletContextHandler(proxy, "/", ServletContextHandler.SESSIONS);
    ServletHolder proxyServlet = new ServletHolder(ProxyServlet.class);
    context.addServlet(proxyServlet, "/*");
    server.start();

    config.setProxyUrl("http://localhost:" + port);
}
 
Example 15
Source Project: new-bull   Source File: HelloServer.java    License: 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 16
Source Project: example-java-jetty   Source File: HelloWorld.java    License: MIT License 6 votes vote down vote up
public static void main(String[] args) throws Exception{
    String portEnv = System.getenv("PORT");
    int port = 5000;
    if (portEnv != null) {
        port = Integer.valueOf(portEnv);
    }

    Server server = new Server(port);
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    server.setHandler(context);
    context.addServlet(new ServletHolder(new Healthcheck()),"/healthz");
    context.addServlet(new ServletHolder(new Index()),"/*");
    server.start();
    server.join();
}
 
Example 17
Source Project: jenkins-test-harness   Source File: JavaNetReverseProxy.java    License: MIT License 6 votes vote down vote up
public JavaNetReverseProxy(File cacheFolder) throws Exception {
    this.cacheFolder = cacheFolder;
    cacheFolder.mkdirs();
    QueuedThreadPool qtp = new QueuedThreadPool();
    qtp.setName("Jetty (JavaNetReverseProxy)");
    server = new Server(qtp);

    ContextHandlerCollection contexts = new ContextHandlerCollection();
    server.setHandler(contexts);

    ServletContextHandler root = new ServletContextHandler(contexts, "/", ServletContextHandler.SESSIONS);
    root.addServlet(new ServletHolder(this), "/");

    ServerConnector connector = new ServerConnector(server);
    server.addConnector(connector);
    server.start();

    localPort = connector.getLocalPort();
}
 
Example 18
Source Project: wisp   Source File: ServerMain.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");

        Server jettyServer = new Server(8067);
        jettyServer.setHandler(context);

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

        // Tells the Jersey Servlet which REST service/class to load.
        jerseyServlet.setInitParameter(
                "jersey.config.server.provider.classnames",
                EntryPointTestHandler.class.getCanonicalName());

        try {
            jettyServer.start();
            jettyServer.join();
        } finally {
            jettyServer.destroy();
        }
    }
 
Example 19
Source Project: submarine   Source File: SubmarineServer.java    License: Apache License 2.0 5 votes vote down vote up
private static void setupNotebookServer(WebAppContext webapp,
    SubmarineConfiguration conf, ServiceLocator serviceLocator) {
  String maxTextMessageSize = conf.getWebsocketMaxTextMessageSize();
  final ServletHolder servletHolder =
      new ServletHolder(serviceLocator.getService(NotebookServer.class));
  servletHolder.setInitParameter("maxTextMessageSize", maxTextMessageSize);

  final ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
  webapp.addServlet(servletHolder, "/ws/*");
}
 
Example 20
Source Project: nifi   Source File: PostSlackTextMessageTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
    testRunner = TestRunners.newTestRunner(PostSlack.class);

    servlet = new PostSlackCaptureServlet();

    ServletContextHandler handler = new ServletContextHandler();
    handler.addServlet(new ServletHolder(servlet), "/*");

    server = new TestServer();
    server.addHandler(handler);
    server.startServer();
}
 
Example 21
Source Project: chassis   Source File: ChassisEurekaTestConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Order(0)
@Bean(initMethod="start", destroyMethod="stop")
public Server httpServer(
        @Value("${http.hostname}") String hostname,
        @Value("${http.port}") int port,
        ConfigurableWebApplicationContext webApplicationContext) {

    // set up servlets
    ServletHandler servlets = new ServletHandler();
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SESSIONS | ServletContextHandler.NO_SECURITY);
    context.setErrorHandler(null);
    context.setWelcomeFiles(new String[] { "/" });

    // set up spring with the servlet context
    setServletContext(context.getServletContext());

    // configure the spring mvc dispatcher
    DispatcherServlet dispatcher = new DispatcherServlet(webApplicationContext);

    // map application servlets
    context.addServlet(new ServletHolder(dispatcher), "/");

    servlets.setHandler(context);

    // create the server
    InetSocketAddress address = StringUtils.isBlank(hostname) ? new InetSocketAddress(port) : new InetSocketAddress(hostname, port);
    Server server = new Server();
    ServerConnector connector = new ServerConnector(server);
    connector.setHost(address.getHostName());
    connector.setPort(address.getPort());
    server.setConnectors(new Connector[]{ connector });
    server.setHandler(servlets);

    return server;
}
 
Example 22
Source Project: hadoop-ozone   Source File: HttpServer2.java    License: 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 23
Source Project: cf-java-logging-support   Source File: RequestLogTest.java    License: 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 24
Source Project: selenium   Source File: Main.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
  Flags flags = new Flags();
  JCommander.newBuilder().addObject(flags).build().parse(args);

  Server server = new Server();
  ServerConnector connector = new ServerConnector(server);
  connector.setPort(flags.port);
  server.setConnectors(new Connector[] {connector });

  HandlerList handlers = new HandlerList();

  ContextHandler context = new ContextHandler();
  context.setContextPath("/tests");
  ResourceHandler testHandler = new ResourceHandler();
  testHandler.setBaseResource(Resource.newClassPathResource("/tests"));
  testHandler.setDirectoriesListed(true);
  context.setHandler(testHandler);
  handlers.addHandler(context);

  ContextHandler coreContext = new ContextHandler();
  coreContext.setContextPath("/core");
  ResourceHandler coreHandler = new ResourceHandler();
  coreHandler.setBaseResource(Resource.newClassPathResource("/core"));
  coreContext.setHandler(coreHandler);
  handlers.addHandler(coreContext);

  ServletContextHandler driverContext = new ServletContextHandler();
  driverContext.setContextPath("/");
  driverContext.addServlet(WebDriverServlet.class, "/wd/hub/*");
  handlers.addHandler(driverContext);

  server.setHandler(handlers);
  server.start();
}
 
Example 25
Source Project: java-jaxrs   Source File: AbstractClassOperationNameTest.java    License: 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 26
Source Project: spring-analysis-note   Source File: JettyWebSocketTestServer.java    License: MIT License 5 votes vote down vote up
@Override
public void deployConfig(WebApplicationContext wac, Filter... filters) {
	ServletHolder servletHolder = new ServletHolder(new DispatcherServlet(wac));
	this.contextHandler = new ServletContextHandler();
	this.contextHandler.addServlet(servletHolder, "/");
	for (Filter filter : filters) {
		this.contextHandler.addFilter(new FilterHolder(filter), "/*", getDispatcherTypes());
	}
	this.jettyServer.setHandler(this.contextHandler);
}
 
Example 27
Source Project: OmniOcular   Source File: ClientProxy.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void startHttpServer() {
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            Server server = new Server(23333);
            try {
                ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
                context.setContextPath("/");
                ServletHolder wsHolder = new ServletHolder("echo", new WebSocketServlet() {
                    @Override
                    public void configure(WebSocketServletFactory factory) {
                        factory.register(WebSocketHandler.class);
                    }
                });
                context.addServlet(wsHolder, "/w");

                URI uri = OmniOcular.class.getResource("/assets/omniocular/static/").toURI();
                context.setBaseResource(Resource.newResource(uri));
                context.setWelcomeFiles(new String[]{"index.html"});
                ServletHolder holderPwd = new ServletHolder("default", DefaultServlet.class);
                holderPwd.setInitParameter("cacheControl", "max-age=0,public");
                holderPwd.setInitParameter("useFileMappedBuffer", "false");
                context.addServlet(holderPwd, "/");

                server.setHandler(context);
                server.start();
                server.join();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    t.start();

}
 
Example 28
@Override
protected void initServletContext(ServletContextHandler context) {
    context.addFilter(new FilterHolder(new FilterThatInitsSpan()), "/*",
            EnumSet.of(
                    DispatcherType.REQUEST,
                    DispatcherType.FORWARD,
                    // TODO CXF does not call AsyncListener#onComplete() without this (it calls only onStartAsync)
                    DispatcherType.ASYNC,
                    DispatcherType.ERROR,
                    DispatcherType.INCLUDE
            )
    );
}
 
Example 29
Source Project: datacollector   Source File: WebServerModule.java    License: Apache License 2.0 5 votes vote down vote up
@Provides(type = Type.SET)
ContextConfigurator provideConfiguration(final Configuration configuration) {
  return new ContextConfigurator() {
    @Override
    public void init(ServletContextHandler context) {
      context.setAttribute(ConfigurationInjector.CONFIGURATION, configuration);
    }
  };
}
 
Example 30
Source Project: cloudwatch_exporter   Source File: WebServer.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    if (args.length < 2) {
        System.err.println("Usage: WebServer <port> <yml configuration file>");
        System.exit(1);
    }

    configFilePath = args[1];
    CloudWatchCollector collector = null;
    FileReader reader = null;

    try {
      reader = new FileReader(configFilePath);
      collector = new CloudWatchCollector(new FileReader(configFilePath)).register();
    } finally {
      if (reader != null) {
        reader.close();
      }
    }

    ReloadSignalHandler.start(collector);

    int port = Integer.parseInt(args[0]);
    Server server = new Server(port);
    ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    server.setHandler(context);
    context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics");
    context.addServlet(new ServletHolder(new DynamicReloadServlet(collector)), "/-/reload");
    context.addServlet(new ServletHolder(new HealthServlet()), "/-/healthy");
    context.addServlet(new ServletHolder(new HealthServlet()), "/-/ready");
    context.addServlet(new ServletHolder(new HomePageServlet()), "/");
    server.start();
    server.join();
}