Java Code Examples for org.eclipse.jetty.servlet.ServletContextHandler#addServlet()
The following examples show how to use
org.eclipse.jetty.servlet.ServletContextHandler#addServlet() .
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: HelloWorld.java From example-java-jetty with MIT License | 8 votes |
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 2
Source File: Main.java From stepic_java_webserver with MIT License | 6 votes |
public static void main(String[] args) throws Exception { AccountService accountService = new AccountService(); accountService.addNewUser(new UserProfile("admin")); accountService.addNewUser(new UserProfile("test")); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.addServlet(new ServletHolder(new UsersServlet(accountService)), "/api/v1/users"); context.addServlet(new ServletHolder(new SessionsServlet(accountService)), "/api/v1/sessions"); ResourceHandler resource_handler = new ResourceHandler(); resource_handler.setResourceBase("public_html"); HandlerList handlers = new HandlerList(); handlers.setHandlers(new Handler[]{resource_handler, context}); Server server = new Server(8080); server.setHandler(handlers); server.start(); server.join(); }
Example 3
Source File: TransactionServer.java From tcc-transaction with Apache License 2.0 | 6 votes |
private TransactionServer() { this.server = new Server(port); try { ServletContextHandler handler = new ServletContextHandler(); handler.setContextPath("/"); handler.setSessionHandler(new SessionHandler()); handler.addServlet(EnvServlet.class, "/api/env"); handler.addServlet(PropertiesServlet.class, "/api/props"); handler.addServlet(TaskServlet.class, "/api/tasks"); handler.addServlet(StaticContentServlet.class, "/*"); handler.addServlet(StartServlet.class, "/api/start"); server.setHandler(handler); } catch (Exception e) { log.error("Exception in building AdminResourcesContainer ", e); } }
Example 4
Source File: ParallelDownloadTest.java From chipster with MIT License | 6 votes |
public static Server getJetty() throws Exception { Server server = new Server(); //http //ServerConnector connector = new ServerConnector(server); //https SslContextFactory factory = new SslContextFactory(); factory.setKeyStorePath("filebroker.ks"); factory.setKeyStorePassword("password"); ServerConnector connector = new ServerConnector(server, factory); connector.setPort(8080); server.setConnectors(new Connector[]{ connector }); ServletContextHandler handler = new ServletContextHandler(server, "/", false, false); handler.setResourceBase(new File("").getAbsolutePath()); handler.addServlet(new ServletHolder(new DefaultServlet()), "/*"); return server; }
Example 5
Source File: WebServer.java From sparkler with Apache License 2.0 | 6 votes |
public WebServer(int port, String resRoot){ super(port); LOG.info("Port:{}, Resources Root:{}", port, resRoot); ResourceHandler rh0 = new ResourceHandler(); ContextHandler context0 = new ContextHandler(); context0.setContextPath("/res/*"); context0.setResourceBase(resRoot); context0.setHandler(rh0); //ServletHandler context1 = new ServletHandler(); //this.setHandler(context1); ServletContextHandler context1 = new ServletContextHandler(); context1.addServlet(TestSlaveServlet.class, "/slavesite/*"); // Create a ContextHandlerCollection and set the context handlers to it. // This will let jetty process urls against the declared contexts in // order to match up content. ContextHandlerCollection contexts = new ContextHandlerCollection(); contexts.setHandlers(new Handler[] { context1, context0}); this.setHandler(contexts); }
Example 6
Source File: JavaDropwizard.java From java_examples with Apache License 2.0 | 6 votes |
public static void main( String[] args ) throws Exception { // Increment the counter. counter.inc(); // Hook the Dropwizard registry into the Prometheus registry // via the DropwizardExports collector. CollectorRegistry.defaultRegistry.register(new DropwizardExports(metrics)); // Expose Prometheus metrics. Server server = new Server(1234); ServletContextHandler context = new ServletContextHandler(); context.setContextPath("/"); server.setHandler(context); context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics"); // Add metrics about CPU, JVM memory etc. DefaultExports.initialize(); // Start the webserver. server.start(); server.join(); }
Example 7
Source File: RequestPartIntegrationTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@BeforeClass public static void startServer() throws Exception { // Let server pick its own random, available port. server = new Server(0); ServletContextHandler handler = new ServletContextHandler(); handler.setContextPath("/"); Class<?> config = CommonsMultipartResolverTestConfig.class; ServletHolder commonsResolverServlet = new ServletHolder(DispatcherServlet.class); commonsResolverServlet.setInitParameter("contextConfigLocation", config.getName()); commonsResolverServlet.setInitParameter("contextClass", AnnotationConfigWebApplicationContext.class.getName()); handler.addServlet(commonsResolverServlet, "/commons-resolver/*"); config = StandardMultipartResolverTestConfig.class; ServletHolder standardResolverServlet = new ServletHolder(DispatcherServlet.class); standardResolverServlet.setInitParameter("contextConfigLocation", config.getName()); standardResolverServlet.setInitParameter("contextClass", AnnotationConfigWebApplicationContext.class.getName()); standardResolverServlet.getRegistration().setMultipartConfig(new MultipartConfigElement("")); handler.addServlet(standardResolverServlet, "/standard-resolver/*"); server.setHandler(handler); server.start(); Connector[] connectors = server.getConnectors(); NetworkConnector connector = (NetworkConnector) connectors[0]; baseUrl = "http://localhost:" + connector.getLocalPort(); }
Example 8
Source File: Main.java From tp_java_2015_02 with MIT License | 5 votes |
public static void main(String[] args) throws Exception { Frontend frontend = new Frontend(); Server server = new Server(8080); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); server.setHandler(context); context.addServlet(new ServletHolder(frontend), "/authform"); server.start(); server.join(); }
Example 9
Source File: JettyCoreServer.java From jvm-sandbox with GNU Lesser General Public License v3.0 | 5 votes |
private void initJettyContextHandler() { final String namespace = cfg.getNamespace(); final ServletContextHandler context = new ServletContextHandler(NO_SESSIONS); final String contextPath = "/sandbox/" + namespace; context.setContextPath(contextPath); context.setClassLoader(getClass().getClassLoader()); // web-socket-servlet final String wsPathSpec = "/module/websocket/*"; logger.info("initializing ws-http-handler. path={}", contextPath + wsPathSpec); //noinspection deprecation context.addServlet( new ServletHolder(new WebSocketAcceptorServlet(jvmSandbox.getCoreModuleManager())), wsPathSpec ); // module-http-servlet final String pathSpec = "/module/http/*"; logger.info("initializing http-handler. path={}", contextPath + pathSpec); context.addServlet( new ServletHolder(new ModuleHttpServlet(cfg, jvmSandbox.getCoreModuleManager())), pathSpec ); httpServer.setHandler(context); }
Example 10
Source File: ServletTest.java From attic-polygene-java with Apache License 2.0 | 5 votes |
@Test public void test() throws Exception { int port = FreePortFinder.findFreePortOnLoopback(); Server server = new Server( port ); try { ServletContextHandler context = new ServletContextHandler(); context.setContextPath( "/" ); context.addEventListener( new FooServletContextListener() ); context.addServlet( FooServlet.class, "/*" ); server.setHandler( context ); server.start(); try( CloseableHttpClient client = HttpClientBuilder.create().build() ) { String result = client.execute( new HttpGet( "http://127.0.0.1:" + port + "/" ), new BasicResponseHandler() ); Assert.assertEquals( APP_NAME, result.trim() ); } } finally { server.stop(); } }
Example 11
Source File: Jersey2App.java From HotswapAgentExamples with GNU General Public License v2.0 | 5 votes |
public static void main(String[] args) throws Exception { MyApplication config = new MyApplication(); ServletHolder jerseyServlet = new ServletHolder(new ServletContainer(config)); Server server = new Server(8080); ServletContextHandler context = new ServletContextHandler(server, "/"); context.addServlet(jerseyServlet, "/*"); server.start(); server.join(); }
Example 12
Source File: JettyUtil.java From incubator-iotdb with Apache License 2.0 | 5 votes |
public static ServletContextHandler createServletHandler(String path, HttpServlet servlet) { ServletContextHandler contextHandler = new ServletContextHandler(ServletContextHandler.SESSIONS); ServletHolder holder = new ServletHolder(servlet); contextHandler.setContextPath(path); contextHandler.addServlet(holder, "/"); return contextHandler; }
Example 13
Source File: WebServer.java From buck with Apache License 2.0 | 5 votes |
@VisibleForTesting ImmutableList<ContextHandler> createHandlers() { Map<String, Handler> contextPathToHandler = new HashMap<>(); contextPathToHandler.put(INDEX_CONTEXT_PATH, new TemplateHandler(new IndexHandlerDelegate())); StaticResourcesHandler staticResourcesHandler = new StaticResourcesHandler(); contextPathToHandler.put(STATIC_CONTEXT_PATH, staticResourcesHandler); // Handlers for traces. BuildTraces buildTraces = new BuildTraces(projectFilesystem); contextPathToHandler.put( TRACE_CONTEXT_PATH, new TemplateHandler(new TraceHandlerDelegate(buildTraces))); contextPathToHandler.put( TRACES_CONTEXT_PATH, new TemplateHandler(new TracesHandlerDelegate(buildTraces))); contextPathToHandler.put(TRACE_DATA_CONTEXT_PATH, new TraceDataHandler(buildTraces)); contextPathToHandler.put(ARTIFACTS_CONTEXT_PATH, artifactCacheHandler); ImmutableList.Builder<ContextHandler> handlers = ImmutableList.builder(); for (Map.Entry<String, Handler> entry : contextPathToHandler.entrySet()) { String contextPath = entry.getKey(); Handler handler = entry.getValue(); ContextHandler contextHandler = new ContextHandler(contextPath); contextHandler.setHandler(handler); handlers.add(contextHandler); } // Create a handler that acts as a WebSocket server. ServletContextHandler servletContextHandler = new ServletContextHandler( /* parent */ server, /* contextPath */ "/ws", /* sessions */ true, /* security */ false); servletContextHandler.addServlet(new ServletHolder(streamingWebSocketServlet), "/build"); handlers.add(servletContextHandler); return handlers.build(); }
Example 14
Source File: EchoServer.java From apiman with Apache License 2.0 | 5 votes |
/** * Configure the web application(s). * @param handlers * @throws Exception */ protected void addModulesToJetty(ContextHandlerCollection handlers) throws Exception { /* ************* * Echo Server * ************* */ ServletContextHandler server = new ServletContextHandler(ServletContextHandler.SESSIONS); // server.setSecurityHandler(createSecurityHandler()); server.setContextPath("/"); //$NON-NLS-1$ ServletHolder servlet = new ServletHolder(new EchoServlet()); server.addServlet(servlet, "/"); //$NON-NLS-1$ // Add the web contexts to jetty handlers.addHandler(server); }
Example 15
Source File: GatewayMicroService.java From apiman with Apache License 2.0 | 5 votes |
/** * Configure the web application(s). * @param handlers * @throws Exception */ protected void addModulesToJetty(ContextHandlerCollection handlers) throws Exception { /* ************* * Gateway API * ************* */ ServletContextHandler gatewayApiServer = new ServletContextHandler(ServletContextHandler.SESSIONS); addSecurityHandler(gatewayApiServer); gatewayApiServer.setContextPath("/api"); gatewayApiServer.addEventListener(new ResteasyBootstrap()); gatewayApiServer.addEventListener(new WarGatewayBootstrapper()); gatewayApiServer.addFilter(HttpRequestThreadLocalFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST)); gatewayApiServer.addFilter(LocaleFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST)); gatewayApiServer.addFilter(ApimanCorsFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST)); gatewayApiServer.addFilter(DisableCachingFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST)); addApiAuthFilter(gatewayApiServer); gatewayApiServer.addFilter(RootResourceFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST)); ServletHolder resteasyServlet = new ServletHolder(new HttpServletDispatcher()); resteasyServlet.setInitParameter("javax.ws.rs.Application", GatewayMicroServiceApplication.class.getName()); gatewayApiServer.addServlet(resteasyServlet, "/*"); gatewayApiServer.setInitParameter("resteasy.servlet.mapping.prefix", ""); handlers.addHandler(gatewayApiServer); /* ************* * Gateway * ************* */ ServletContextHandler gatewayServer = new ServletContextHandler(ServletContextHandler.SESSIONS); addSecurityHandler(gatewayServer); gatewayServer.setContextPath("/gateway"); ServletHolder servlet = new ServletHolder(new WarGatewayServlet()); gatewayServer.addServlet(servlet, "/*"); handlers.addHandler(gatewayServer); }
Example 16
Source File: ClientJettyReaderWriterITest.java From hawkular-apm with Apache License 2.0 | 5 votes |
@BeforeClass public static void initClass() { server = new Server(8180); ServletContextHandler context = new ServletContextHandler(); context.setContextPath("/"); context.addServlet(EmbeddedServlet.class, "/hello"); server.setHandler(context); try { server.start(); } catch (Exception e) { fail("Failed to start server: " + e); } }
Example 17
Source File: Application.java From rest-utils with Apache License 2.0 | 4 votes |
final Handler configureHandler() { ResourceConfig resourceConfig = new ResourceConfig(); configureBaseApplication(resourceConfig, getMetricsTags()); configureResourceExtensions(resourceConfig); setupResources(resourceConfig, getConfiguration()); // Configure the servlet container ServletContainer servletContainer = new ServletContainer(resourceConfig); final FilterHolder servletHolder = new FilterHolder(servletContainer); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath(path); ServletHolder defaultHolder = new ServletHolder("default", DefaultServlet.class); defaultHolder.setInitParameter("dirAllowed", "false"); ResourceCollection staticResources = getStaticResources(); if (staticResources != null) { context.setBaseResource(staticResources); } configureSecurityHandler(context); if (isCorsEnabled()) { String allowedOrigins = config.getString(RestConfig.ACCESS_CONTROL_ALLOW_ORIGIN_CONFIG); FilterHolder filterHolder = new FilterHolder(CrossOriginFilter.class); filterHolder.setName("cross-origin"); filterHolder.setInitParameter( CrossOriginFilter.ALLOWED_ORIGINS_PARAM, allowedOrigins ); String allowedMethods = config.getString(RestConfig.ACCESS_CONTROL_ALLOW_METHODS); String allowedHeaders = config.getString(RestConfig.ACCESS_CONTROL_ALLOW_HEADERS); if (allowedMethods != null && !allowedMethods.trim().isEmpty()) { filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, allowedMethods); } if (allowedHeaders != null && !allowedHeaders.trim().isEmpty()) { filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, allowedHeaders); } // handle preflight cors requests at the filter level, do not forward down the filter chain filterHolder.setInitParameter(CrossOriginFilter.CHAIN_PREFLIGHT_PARAM, "false"); context.addFilter(filterHolder, "/*", EnumSet.of(DispatcherType.REQUEST)); } if (config.getString(RestConfig.RESPONSE_HTTP_HEADERS_CONFIG) != null && !config.getString(RestConfig.RESPONSE_HTTP_HEADERS_CONFIG).isEmpty()) { configureHttpResponsHeaderFilter(context); } configurePreResourceHandling(context); context.addFilter(servletHolder, "/*", null); configurePostResourceHandling(context); context.addServlet(defaultHolder, "/*"); applyCustomConfiguration(context, REST_SERVLET_INITIALIZERS_CLASSES_CONFIG); RequestLogHandler requestLogHandler = new RequestLogHandler(); requestLogHandler.setRequestLog(requestLog); HandlerCollection handlers = new HandlerCollection(); handlers.setHandlers(new Handler[]{context, requestLogHandler}); return handlers; }
Example 18
Source File: Main.java From homework_tester with MIT License | 4 votes |
public static void main(String[] args) throws Exception { int port = 8080; logger.info("Starting at http://127.0.0.1:" + port); AccountServer accountServer = new AccountServerImpl(); createMBean(accountServer); Server server = new Server(port); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.addServlet(new ServletHolder(new AdminPageServlet(accountServer)), AdminPageServlet.PAGE_URL); ResourceHandler resource_handler = new ResourceHandler(); HandlerList handlers = new HandlerList(); handlers.setHandlers(new Handler[]{resource_handler, context}); server.setHandler(handlers); server.start(); logger.info("Server started"); server.join(); }
Example 19
Source File: ManagerApiMicroService.java From apiman with Apache License 2.0 | 4 votes |
/** * Configure the web application(s). * @param handlers * @throws Exception */ protected void addModulesToJetty(HandlerCollection handlers) throws Exception { /* ************* * Manager API * ************* */ ServletContextHandler apiManServer = new ServletContextHandler(ServletContextHandler.SESSIONS); addSecurityHandler(apiManServer); apiManServer.setContextPath("/apiman"); apiManServer.addEventListener(new Listener()); apiManServer.addEventListener(new BeanManagerResourceBindingListener()); apiManServer.addEventListener(new ResteasyBootstrap()); apiManServer.addFilter(LocaleFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST)); apiManServer.addFilter(ApimanCorsFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST)); apiManServer.addFilter(DisableCachingFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST)); addAuthFilter(apiManServer); apiManServer.addFilter(DefaultSecurityContextFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST)); apiManServer.addFilter(RootResourceFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST)); apiManServer.addFilter(ManagerApiMicroServiceTxWatchdogFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST)); ServletHolder resteasyServlet = new ServletHolder(new HttpServletDispatcher()); resteasyServlet.setInitParameter("javax.ws.rs.Application", ManagerApiMicroServiceApplication.class.getName()); apiManServer.addServlet(resteasyServlet, "/*"); apiManServer.setInitParameter("resteasy.injector.factory", "org.jboss.resteasy.cdi.CdiInjectorFactory"); apiManServer.setInitParameter("resteasy.scan", "true"); apiManServer.setInitParameter("resteasy.servlet.mapping.prefix", ""); handlers.addHandler(apiManServer); /* ********** * * Manager UI * * ********** */ ResourceHandler apimanUiServer = new ResourceHandler() { /** * @see org.eclipse.jetty.server.handler.ResourceHandler#getResource(java.lang.String) */ @Override public Resource getResource(String path) { Resource resource = null; if (path == null || path.equals("/") || path.equals("/index.html")) { path = "/index.html"; } if (path.startsWith("/apimanui/api-manager") || path.equals("/apimanui") || path.equals("/apimanui/")) { path = "/apimanui/index.html"; } if (path.equals("/apimanui/apiman/config.js")) { resource = getConfigResource(path); } if (path.equals("/apimanui/apiman/translations.js")) { resource = getTranslationsResource(path); } if (resource == null) { URL url = getClass().getResource(path); if (url != null) { resource = new ApimanResource(url); } } return resource; } }; apimanUiServer.setResourceBase("/apimanui/"); apimanUiServer.setWelcomeFiles(new String[] { "index.html" }); handlers.addHandler(apimanUiServer); }
Example 20
Source File: Main.java From billow with Apache License 2.0 | 4 votes |
private Main(Config config) throws Exception { log.info("Startup..."); try { System.out.println(Resources.toString(getResource("banner.txt"), Charsets.UTF_8)); } catch (IllegalArgumentException | IOException e) { log.debug("No banner.txt", e); } final MetricRegistry metricRegistry = new MetricRegistry(); final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); log.info("Creating database"); final Config awsConfig = config.getConfig("aws"); final Long refreshRate = awsConfig.getDuration("refreshRate", TimeUnit.MILLISECONDS); final AWSDatabaseHolder dbHolder = new AWSDatabaseHolder(awsConfig); final Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); scheduler.getContext().put(AWSDatabaseHolderRefreshJob.DB_KEY, dbHolder); scheduler.start(); final SimpleTrigger trigger = newTrigger(). withIdentity(AWSDatabaseHolderRefreshJob.NAME). startNow(). withSchedule(simpleSchedule().withIntervalInMilliseconds(refreshRate).repeatForever()). build(); final JobDetail jobDetail = newJob(AWSDatabaseHolderRefreshJob.class). withIdentity(AWSDatabaseHolderRefreshJob.NAME). build(); scheduler.scheduleJob(jobDetail, trigger); log.info("Creating age health check"); healthCheckRegistry.register("DB", new HealthCheck() { @Override protected Result check() throws Exception { return dbHolder.healthy(); } }); log.info("Creating HTTP servers"); final Server mainServer = new Server(config.getInt("mainPort")); final Server adminServer = new Server(config.getInt("adminPort")); configureConnectors(mainServer); configureConnectors(adminServer); log.info("Creating HTTP handlers"); final Handler mainHandler = new Handler(metricRegistry, dbHolder, refreshRate); final InstrumentedHandler instrumentedHandler = new InstrumentedHandler(metricRegistry); instrumentedHandler.setHandler(mainHandler); mainServer.setHandler(instrumentedHandler); final ServletContextHandler adminHandler = new ServletContextHandler(); adminHandler.addServlet(new ServletHolder(new AdminServlet()), "/*"); final ServletContext adminContext = adminHandler.getServletContext(); adminContext.setAttribute(MetricsServlet.METRICS_REGISTRY, metricRegistry); adminContext.setAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY, healthCheckRegistry); adminServer.setHandler(adminHandler); log.info("Starting HTTP servers"); adminServer.start(); mainServer.start(); log.info("Joining..."); mainServer.join(); adminServer.join(); log.info("Shutting down scheduler..."); scheduler.shutdown(); log.info("We're done!"); }