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

The following examples show how to use org.eclipse.jetty.servlet.ServletContextHandler#addEventListener() . 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: StatsServer.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
    final Server server = new Server(8686);

    final ServletHolder staticHolder = new ServletHolder(new DefaultServlet());
    final ServletContextHandler staticContext = new ServletContextHandler();
    staticContext.setContextPath("/static");
    staticContext.addServlet(staticHolder, "/*");
    staticContext.setResourceBase(StatsServer.class.getResource("/web-ui").toURI().toString());

     // Register and map the dispatcher servlet
    final CXFCdiServlet cxfServlet = new CXFCdiServlet();
    final ServletHolder cxfServletHolder = new ServletHolder(cxfServlet);
    final ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    context.addEventListener(new Listener());
    context.addEventListener(new BeanManagerResourceBindingListener());
    context.addServlet(cxfServletHolder, "/rest/*");

    HandlerList handlers = new HandlerList();
    handlers.addHandler(staticContext);
    handlers.addHandler(context);

    server.setHandler(handlers);
    server.start();
    server.join();
}
 
Example 2
Source File: StatsServer.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
    final Server server = new Server(8686);

    final ServletHolder staticHolder = new ServletHolder(new DefaultServlet());
    final ServletContextHandler staticContext = new ServletContextHandler();
    staticContext.setContextPath("/static");
    staticContext.addServlet(staticHolder, "/*");
    staticContext.setResourceBase(StatsServer.class.getResource("/web-ui").toURI().toString());

     // Register and map the dispatcher servlet
    final ServletHolder cxfServletHolder = new ServletHolder(new CXFServlet());
    final ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    context.addEventListener(new ContextLoaderListener());
    context.addServlet(cxfServletHolder, "/rest/*");
    context.setInitParameter("contextClass", AnnotationConfigWebApplicationContext.class.getName());
    context.setInitParameter("contextConfigLocation", StatsConfig.class.getName());

    HandlerList handlers = new HandlerList();
    handlers.addHandler(staticContext);
    handlers.addHandler(context);

    server.setHandler(handlers);
    server.start();
    server.join();
}
 
Example 3
Source File: ApiServer.java    From act-platform with ISC License 6 votes vote down vote up
@Override
public void startComponent() {
  // Initialize servlet using RESTEasy and it's Guice bridge.
  // The listener must be injected by the same Guice module which also binds the REST endpoints.
  ServletContextHandler servletHandler = new ServletContextHandler();
  servletHandler.addEventListener(listener);
  servletHandler.addServlet(HttpServletDispatcher.class, "/*");

  // Configure Jetty: Remove 'server' header from response and set listen port.
  HttpConfiguration httpConfig = new HttpConfiguration();
  httpConfig.setSendServerVersion(false);
  ServerConnector connector = new ServerConnector(server, new HttpConnectionFactory(httpConfig));
  connector.setPort(port);

  // Starting up Jetty to serve the REST API.
  server.addConnector(connector);
  server.setHandler(servletHandler);

  if (!LambdaUtils.tryTo(server::start, ex -> logger.error(ex, "Failed to start REST API."))) {
    throw new IllegalStateException("Failed to start REST API.");
  }
}
 
Example 4
Source File: ExplorerAppTest.java    From Nicobar with 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 5
Source File: EmissaryServer.java    From emissary with Apache License 2.0 6 votes vote down vote up
private ContextHandler buildEmissaryHandler() throws EmissaryException {
    // must set these set or you are not an EmissaryNode
    String configDir = System.getProperty(ConfigUtil.CONFIG_DIR_PROPERTY, null);
    if (configDir == null || !Files.exists(Paths.get(configDir))) {
        throw new EmissaryException("Config dir error. " + ConfigUtil.CONFIG_DIR_PROPERTY + " is " + configDir);
    }
    // set number of agents if it has been set
    if (cmd.getAgents() != 0) {
        System.setProperty("agent.poolsize", Integer.toString(cmd.getAgents()));
    }

    ServletContextHandler emissaryHolderContext = new ServletContextHandler(ServletContextHandler.SESSIONS);
    emissaryHolderContext.addEventListener(new InitializeContext(emissaryNode));

    return emissaryHolderContext;
}
 
Example 6
Source File: WebServletShiroTest.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Test
public void test()
        throws Exception
{
    int port = FreePortFinder.findFreePortOnLoopback();
    Server server = new Server( port );
    try {

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

        context.setInitParameter( "shiroConfigLocations", "classpath:web-shiro.ini" );
        context.addEventListener( new EnvironmentLoaderListener() );

        context.addFilter( ShiroFilter.class, "/*", EnumSet.of( REQUEST, FORWARD, INCLUDE, ERROR ) );

        server.setHandler( context );
        server.start();

        // HttpClient client = new DefaultHttpClient();
        // String result = client.execute( new HttpGet( "http://127.0.0.1:" + port + "/" ), new BasicResponseHandler() );

    } finally {
        server.stop();
    }

}
 
Example 7
Source File: TestServerUtil.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
private static ServletContextHandler getServletContextHandler(AnnotationConfigWebApplicationContext context) throws IOException {
    ServletContextHandler contextHandler = new ServletContextHandler();
    WebConfigurer configurer = new WebConfigurer();
    configurer.setContext(context);
    contextHandler.addEventListener(configurer);

    // Create the SessionHandler (wrapper) to handle the sessions
    HashSessionManager manager = new HashSessionManager();
    SessionHandler sessions = new SessionHandler(manager);
    contextHandler.setHandler(sessions);

    return contextHandler;
}
 
Example 8
Source File: TestServerUtil.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
private static ServletContextHandler getServletContextHandler(AnnotationConfigWebApplicationContext context) throws IOException {
    ServletContextHandler contextHandler = new ServletContextHandler();
    WebConfigurer configurer = new WebConfigurer();
    configurer.setContext(context);
    contextHandler.addEventListener(configurer);

    // Create the SessionHandler (wrapper) to handle the sessions
    HashSessionManager manager = new HashSessionManager();
    SessionHandler sessions = new SessionHandler(manager);
    contextHandler.setHandler(sessions);

    return contextHandler;
}
 
Example 9
Source File: TestServerUtil.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
private static ServletContextHandler getServletContextHandler(AnnotationConfigWebApplicationContext context) throws IOException {
    ServletContextHandler contextHandler = new ServletContextHandler();
    WebConfigurer configurer = new WebConfigurer();
    configurer.setContext(context);
    contextHandler.addEventListener(configurer);

    // Create the SessionHandler (wrapper) to handle the sessions
    HashSessionManager manager = new HashSessionManager();
    SessionHandler sessions = new SessionHandler(manager);
    contextHandler.setHandler(sessions);

    return contextHandler;
}
 
Example 10
Source File: JettyConfigurationHelper.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
static void addContextListeners( ServletContextHandler root, Iterable<ServiceReference<ServletContextListener>> contextListeners )
{
    // Iterate the available context listeners and add them to the server
    for( ServiceReference<ServletContextListener> contextListener : contextListeners )
    {
        ContextListenerInfo contextListenerInfo = contextListener.metaInfo( ContextListenerInfo.class );
        Map<String, String> initParams = contextListenerInfo.initParams();
        for( Map.Entry<String, String> entry : initParams.entrySet() )
        {
            root.setInitParameter( entry.getKey(), entry.getValue() );
        }
        root.addEventListener( contextListener.get() );
    }
}
 
Example 11
Source File: TestServerUtil.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
private static ServletContextHandler getServletContextHandler(AnnotationConfigWebApplicationContext context) throws IOException {
    ServletContextHandler contextHandler = new ServletContextHandler();
    WebConfigurer configurer = new WebConfigurer();
    configurer.setContext(context);
    contextHandler.addEventListener(configurer);

    // Create the SessionHandler (wrapper) to handle the sessions
    HashSessionManager manager = new HashSessionManager();
    SessionHandler sessions = new SessionHandler(manager);
    contextHandler.setHandler(sessions);

    return contextHandler;
}
 
Example 12
Source File: ServletReporter.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
public void start() throws Exception {
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    jettyServer.setHandler(context);

    context.addEventListener(new HealthCheckServletContextListener(healthCheckRegistry));
    context.addEventListener(new MetricsServletContextListener(metricRegistry));
    context.addServlet(new ServletHolder(new AdminServlet()), "/*");

    jettyServer.start();
}
 
Example 13
Source File: SpringMvcJettyComponentTestServer.java    From backstopper with Apache License 2.0 5 votes vote down vote up
private static ServletContextHandler generateServletContextHandler(WebApplicationContext context) {
    ServletContextHandler contextHandler = new ServletContextHandler();
    contextHandler.setErrorHandler(generateErrorHandler());
    contextHandler.setContextPath("/");
    contextHandler.addServlet(new ServletHolder(generateDispatcherServlet(context)), "/*");
    contextHandler.addEventListener(new ContextLoaderListener(context));
    contextHandler.addFilter(
        ExplodingServletFilter.class, "/*", EnumSet.allOf(DispatcherType.class)
    );
    return contextHandler;
}
 
Example 14
Source File: PaasLauncher.java    From staash with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    LOG.info("Starting PAAS");
    
    // Create the server.
    Server server = new Server(DEFAULT_PORT);
     
    // Create a servlet context and add the jersey servlet.
    ServletContextHandler sch = new ServletContextHandler(server, "/");
     
    // Add our Guice listener that includes our bindings
    sch.addEventListener(new PaasGuiceServletConfig());
     
    // Then add GuiceFilter and configure the server to 
    // reroute all requests through this filter. 
    sch.addFilter(GuiceFilter.class, "/*", null);
     
    // Must add DefaultServlet for embedded Jetty. 
    // Failing to do this will cause 404 errors.
    // This is not needed if web.xml is used instead.
    sch.addServlet(DefaultServlet.class, "/");
     
    // Start the server
    server.start();
    server.join();  
    
    LOG.info("Stopping PAAS");
}
 
Example 15
Source File: JettyServer.java    From sumk with Apache License 2.0 5 votes vote down vote up
protected synchronized void init() {
	try {
		buildJettyProperties();
		server = new Server(new ExecutorThreadPool(HttpExcutors.getThreadPool()));
		ServerConnector connector = this.createConnector();
		Logs.http().info("listen port: {}", port);
		String host = StartContext.httpHost();
		if (host != null && host.length() > 0) {
			connector.setHost(host);
		}
		connector.setPort(port);

		server.setConnectors(new Connector[] { connector });
		ServletContextHandler context = createServletContextHandler();
		context.setContextPath(AppInfo.get("sumk.jetty.web.root", "/"));
		context.addEventListener(new SumkLoaderListener());
		addUserListener(context, Arrays.asList(ServletContextListener.class, ContextScopeListener.class));
		String resourcePath = AppInfo.get("sumk.jetty.resource");
		if (StringUtil.isNotEmpty(resourcePath)) {
			ResourceHandler resourceHandler = JettyHandlerSupplier.resourceHandlerSupplier().get();
			if (resourceHandler != null) {
				resourceHandler.setResourceBase(resourcePath);
				context.insertHandler(resourceHandler);
			}
		}

		if (AppInfo.getBoolean("sumk.jetty.session.enable", false)) {
			SessionHandler h = JettyHandlerSupplier.sessionHandlerSupplier().get();
			if (h != null) {
				context.insertHandler(h);
			}
		}
		server.setHandler(context);
	} catch (Throwable e) {
		Log.printStack("sumk.http", e);
		System.exit(1);
	}

}
 
Example 16
Source File: AbstractDownloadTest.java    From archiva with Apache License 2.0 5 votes vote down vote up
@Before
public void startServer()
    throws Exception
{

    System.setProperty( "redback.admin.creation.file", "target/auto-admin-creation.properties" );

    server = new Server();
    serverConnector = new ServerConnector( server, new HttpConnectionFactory() );
    server.addConnector( serverConnector );

    ServletHolder servletHolder = new ServletHolder( new CXFServlet() );
    ServletContextHandler context = new ServletContextHandler( ServletContextHandler.SESSIONS );
    context.setResourceBase( SystemUtils.JAVA_IO_TMPDIR );
    context.setSessionHandler( new SessionHandler() );
    context.addServlet( servletHolder, "/" + getRestServicesPath() + "/*" );
    context.setInitParameter( "contextConfigLocation", getSpringConfigLocation() );
    context.addEventListener( new ContextLoaderListener() );

    ServletHolder servletHolderRepo = new ServletHolder( new RepositoryServlet() );
    context.addServlet( servletHolderRepo, "/repository/*" );

    server.setHandler( context );
    server.start();
    port = serverConnector.getLocalPort();
    log.info( "start server on port {}", this.port );

    User user = new User();
    user.setEmail( "[email protected]" );
    user.setFullName( "the root user" );
    user.setUsername( RedbackRoleConstants.ADMINISTRATOR_ACCOUNT_NAME );
    user.setPassword( FakeCreateAdminService.ADMIN_TEST_PWD );

    getUserService( null ).createAdminUser( user );


}
 
Example 17
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 18
Source File: ITSpanCustomizingContainerFilter.java    From brave with Apache License 2.0 5 votes vote down vote up
@Override public void init(ServletContextHandler handler) {
  // Adds application programmatically as opposed to using web.xml
  handler.addServlet(new ServletHolder(new HttpServletDispatcher()), "/*");
  handler.addEventListener(new TaggingBootstrap(new TestResource(httpTracing)));

  addFilter(handler, TracingFilter.create(httpTracing));
}
 
Example 19
Source File: SentryWebServer.java    From incubator-sentry with Apache License 2.0 4 votes vote down vote up
public SentryWebServer(List<EventListener> listeners, int port, Configuration conf) {
  this.port = port;
  server = new Server(port);
  ServletContextHandler servletContextHandler = new ServletContextHandler();
  ServletHolder servletHolder = new ServletHolder(AdminServlet.class);
  servletContextHandler.addServlet(servletHolder, "/*");

  for(EventListener listener:listeners) {
    servletContextHandler.addEventListener(listener);
  }

  ServletHolder confServletHolder = new ServletHolder(ConfServlet.class);
  servletContextHandler.addServlet(confServletHolder, "/conf");
  servletContextHandler.getServletContext()
      .setAttribute(ConfServlet.CONF_CONTEXT_ATTRIBUTE, conf);

  ResourceHandler resourceHandler = new ResourceHandler();
  resourceHandler.setDirectoriesListed(true);
  URL url = this.getClass().getResource(RESOURCE_DIR);
  try {
    resourceHandler.setBaseResource(Resource.newResource(url.toString()));
  } catch (IOException e) {
    LOGGER.error("Got exception while setBaseResource for Sentry Service web UI", e);
  }
  resourceHandler.setWelcomeFiles(new String[]{WELCOME_PAGE});
  ContextHandler contextHandler= new ContextHandler();
  contextHandler.setHandler(resourceHandler);

  ContextHandlerCollection contextHandlerCollection = new ContextHandlerCollection();
  contextHandlerCollection.setHandlers(new Handler[]{contextHandler, servletContextHandler});

  String authMethod = conf.get(ServerConfig.SENTRY_WEB_SECURITY_TYPE);
  if (!ServerConfig.SENTRY_WEB_SECURITY_TYPE_NONE.equals(authMethod)) {
    /**
     * SentryAuthFilter is a subclass of AuthenticationFilter and
     * AuthenticationFilter tagged as private and unstable interface:
     * While there are not guarantees that this interface will not change,
     * it is fairly stable and used by other projects (ie - Oozie)
     */
    FilterHolder filterHolder = servletContextHandler.addFilter(SentryAuthFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
    filterHolder.setInitParameters(loadWebAuthenticationConf(conf));
  }

  server.setHandler(contextHandlerCollection);
}
 
Example 20
Source File: JettyEmbeddedContainer.java    From gravitee-management-rest-api with Apache License 2.0 3 votes vote down vote up
protected ServletContextHandler configureAPI(String apiContextPath, String applicationName, Class<? extends GlobalAuthenticationConfigurerAdapter> securityConfigurationClass) {
    final ServletContextHandler childContext = new ServletContextHandler(server, apiContextPath, ServletContextHandler.SESSIONS);

    final ServletHolder servletHolder = new ServletHolder(ServletContainer.class);
    servletHolder.setInitParameter("javax.ws.rs.Application", applicationName);
    servletHolder.setInitOrder(0);
    childContext.addServlet(servletHolder, "/*");

    AnnotationConfigWebApplicationContext webApplicationContext = new AnnotationConfigWebApplicationContext();
    webApplicationContext.register(securityConfigurationClass);

    webApplicationContext.setEnvironment((ConfigurableEnvironment) applicationContext.getEnvironment());
    webApplicationContext.setParent(applicationContext);

    childContext.addEventListener(new ContextLoaderListener(webApplicationContext));

    // Spring Security filter
    childContext.addFilter(new FilterHolder(new DelegatingFilterProxy("springSecurityFilterChain")),"/*", EnumSet.allOf(DispatcherType.class));
    return childContext;


}