Java Code Examples for org.springframework.web.context.ContextLoaderListener

The following examples show how to use org.springframework.web.context.ContextLoaderListener. 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: micro-integrator   Source File: Starter.java    License: Apache License 2.0 6 votes vote down vote up
public void startPeopleService() throws Exception {
    final File base = createBaseDirectory();
    log.info("Using base folder: " + base.getAbsolutePath());

    final Tomcat tomcat = new Tomcat();
    tomcat.setPort(8080);
    tomcat.setBaseDir(base.getAbsolutePath());

    Context context = tomcat.addContext("/", base.getAbsolutePath());
    Tomcat.addServlet(context, "CXFServlet", new CXFServlet());

    context.addServletMapping("/rest/*", "CXFServlet");
    context.addApplicationListener(ContextLoaderListener.class.getName());
    context.setLoader(new WebappLoader(Thread.currentThread().getContextClassLoader()));

    context.addParameter("contextClass", AnnotationConfigWebApplicationContext.class.getName());
    context.addParameter("contextConfigLocation", AppConfig.class.getName());

    tomcat.start();
    tomcat.getServer().await();
}
 
Example 2
Source Project: micro-integrator   Source File: Server.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
    final File base = createBaseDirectory();
    log.info("Using base folder: " + base.getAbsolutePath());

    final Tomcat tomcat = new Tomcat();
    tomcat.setPort(8080);
    tomcat.setBaseDir(base.getAbsolutePath());

    Context context = tomcat.addContext("/", base.getAbsolutePath());
    Tomcat.addServlet(context, "CXFServlet", new CXFServlet());

    context.addServletMapping("/rest/*", "CXFServlet");
    context.addApplicationListener(ContextLoaderListener.class.getName());
    context.setLoader(new WebappLoader(Thread.currentThread().getContextClassLoader()));

    context.addParameter("contextClass", AnnotationConfigWebApplicationContext.class.getName());
    context.addParameter("contextConfigLocation", MusicConfig.class.getName());

    tomcat.start();
    tomcat.getServer().await();
}
 
Example 3
Source Project: tutorials   Source File: WebInitializer.java    License: MIT License 6 votes vote down vote up
public void onStartup(ServletContext container) throws ServletException {

        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(ApplicationConfiguration.class);
        // ctx.register(ThymeleafConfiguration.class);
        // ctx.register(FreemarkerConfiguration.class);
        // ctx.register(GroovyConfiguration.class);
        // ctx.register(JadeTemplateConfiguration.class);
        // ctx.register(PushConfiguration.class);
        ctx.register(EmailConfiguration.class);
        // ctx.setServletContext(container);
        
        // Manage the lifecycle of the root application context
        container.addListener(new ContextLoaderListener(ctx));

        ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(ctx));

        servlet.setLoadOnStartup(1);
        servlet.addMapping("/");
    }
 
Example 4
Source Project: spring-analysis-note   Source File: Spr8510Tests.java    License: MIT License 6 votes vote down vote up
@Test
public void abstractRefreshableWAC_respectsProgrammaticConfigLocations() {
	XmlWebApplicationContext ctx = new XmlWebApplicationContext();
	ctx.setConfigLocation("programmatic.xml");
	ContextLoaderListener cll = new ContextLoaderListener(ctx);

	MockServletContext sc = new MockServletContext();

	try {
		cll.contextInitialized(new ServletContextEvent(sc));
		fail("expected exception");
	}
	catch (Throwable t) {
		// assert that an attempt was made to load the correct XML
		assertTrue(t.getMessage(), t.getMessage().endsWith(
				"Could not open ServletContext resource [/programmatic.xml]"));
	}
}
 
Example 5
Source Project: spring-analysis-note   Source File: Spr8510Tests.java    License: MIT License 6 votes vote down vote up
/**
 * If a contextConfigLocation init-param has been specified for the ContextLoaderListener,
 * then it should take precedence. This is generally not a recommended practice, but
 * when it does happen, the init-param should be considered more specific than the
 * programmatic configuration, given that it still quite possibly externalized in
 * hybrid web.xml + WebApplicationInitializer cases.
 */
@Test
public void abstractRefreshableWAC_respectsInitParam_overProgrammaticConfigLocations() {
	XmlWebApplicationContext ctx = new XmlWebApplicationContext();
	ctx.setConfigLocation("programmatic.xml");
	ContextLoaderListener cll = new ContextLoaderListener(ctx);

	MockServletContext sc = new MockServletContext();
	sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml");

	try {
		cll.contextInitialized(new ServletContextEvent(sc));
		fail("expected exception");
	}
	catch (Throwable t) {
		// assert that an attempt was made to load the correct XML
		assertTrue(t.getMessage(), t.getMessage().endsWith(
				"Could not open ServletContext resource [/from-init-param.xml]"));
	}
}
 
Example 6
Source Project: spring-analysis-note   Source File: Spr8510Tests.java    License: MIT License 6 votes vote down vote up
/**
 * If setConfigLocation has not been called explicitly against the application context,
 * then fall back to the ContextLoaderListener init-param if present.
 */
@Test
public void abstractRefreshableWAC_fallsBackToInitParam() {
	XmlWebApplicationContext ctx = new XmlWebApplicationContext();
	//ctx.setConfigLocation("programmatic.xml"); // nothing set programmatically
	ContextLoaderListener cll = new ContextLoaderListener(ctx);

	MockServletContext sc = new MockServletContext();
	sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml");

	try {
		cll.contextInitialized(new ServletContextEvent(sc));
		fail("expected exception");
	}
	catch (Throwable t) {
		// assert that an attempt was made to load the correct XML
		assertTrue(t.getMessage().endsWith(
				"Could not open ServletContext resource [/from-init-param.xml]"));
	}
}
 
Example 7
Source Project: spring-analysis-note   Source File: Spr8510Tests.java    License: MIT License 6 votes vote down vote up
/**
 * Ensure that any custom default locations are still respected.
 */
@Test
public void customAbstractRefreshableWAC_fallsBackToInitParam() {
	XmlWebApplicationContext ctx = new XmlWebApplicationContext() {
		@Override
		protected String[] getDefaultConfigLocations() {
			return new String[] { "/WEB-INF/custom.xml" };
		}
	};
	//ctx.setConfigLocation("programmatic.xml"); // nothing set programmatically
	ContextLoaderListener cll = new ContextLoaderListener(ctx);

	MockServletContext sc = new MockServletContext();
	sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml");

	try {
		cll.contextInitialized(new ServletContextEvent(sc));
		fail("expected exception");
	}
	catch (Throwable t) {
		// assert that an attempt was made to load the correct XML
		System.out.println(t.getMessage());
		assertTrue(t.getMessage().endsWith(
				"Could not open ServletContext resource [/from-init-param.xml]"));
	}
}
 
Example 8
Source Project: spring-analysis-note   Source File: Spr8510Tests.java    License: MIT License 6 votes vote down vote up
/**
 * If context config locations have been specified neither against the application
 * context nor the context loader listener, then fall back to default values.
 */
@Test
public void abstractRefreshableWAC_fallsBackToConventionBasedNaming() {
	XmlWebApplicationContext ctx = new XmlWebApplicationContext();
	//ctx.setConfigLocation("programmatic.xml"); // nothing set programmatically
	ContextLoaderListener cll = new ContextLoaderListener(ctx);

	MockServletContext sc = new MockServletContext();
	// no init-param set
	//sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml");

	try {
		cll.contextInitialized(new ServletContextEvent(sc));
		fail("expected exception");
	}
	catch (Throwable t) {
		// assert that an attempt was made to load the correct XML
		System.out.println(t.getMessage());
		assertTrue(t.getMessage().endsWith(
				"Could not open ServletContext resource [/WEB-INF/applicationContext.xml]"));
	}
}
 
Example 9
Source Project: java-technology-stack   Source File: Spr8510Tests.java    License: MIT License 6 votes vote down vote up
@Test
public void abstractRefreshableWAC_respectsProgrammaticConfigLocations() {
	XmlWebApplicationContext ctx = new XmlWebApplicationContext();
	ctx.setConfigLocation("programmatic.xml");
	ContextLoaderListener cll = new ContextLoaderListener(ctx);

	MockServletContext sc = new MockServletContext();

	try {
		cll.contextInitialized(new ServletContextEvent(sc));
		fail("expected exception");
	}
	catch (Throwable t) {
		// assert that an attempt was made to load the correct XML
		assertTrue(t.getMessage(), t.getMessage().endsWith(
				"Could not open ServletContext resource [/programmatic.xml]"));
	}
}
 
Example 10
Source Project: java-technology-stack   Source File: Spr8510Tests.java    License: MIT License 6 votes vote down vote up
/**
 * If a contextConfigLocation init-param has been specified for the ContextLoaderListener,
 * then it should take precedence. This is generally not a recommended practice, but
 * when it does happen, the init-param should be considered more specific than the
 * programmatic configuration, given that it still quite possibly externalized in
 * hybrid web.xml + WebApplicationInitializer cases.
 */
@Test
public void abstractRefreshableWAC_respectsInitParam_overProgrammaticConfigLocations() {
	XmlWebApplicationContext ctx = new XmlWebApplicationContext();
	ctx.setConfigLocation("programmatic.xml");
	ContextLoaderListener cll = new ContextLoaderListener(ctx);

	MockServletContext sc = new MockServletContext();
	sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml");

	try {
		cll.contextInitialized(new ServletContextEvent(sc));
		fail("expected exception");
	}
	catch (Throwable t) {
		// assert that an attempt was made to load the correct XML
		assertTrue(t.getMessage(), t.getMessage().endsWith(
				"Could not open ServletContext resource [/from-init-param.xml]"));
	}
}
 
Example 11
Source Project: java-technology-stack   Source File: Spr8510Tests.java    License: MIT License 6 votes vote down vote up
/**
 * If setConfigLocation has not been called explicitly against the application context,
 * then fall back to the ContextLoaderListener init-param if present.
 */
@Test
public void abstractRefreshableWAC_fallsBackToInitParam() {
	XmlWebApplicationContext ctx = new XmlWebApplicationContext();
	//ctx.setConfigLocation("programmatic.xml"); // nothing set programmatically
	ContextLoaderListener cll = new ContextLoaderListener(ctx);

	MockServletContext sc = new MockServletContext();
	sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml");

	try {
		cll.contextInitialized(new ServletContextEvent(sc));
		fail("expected exception");
	}
	catch (Throwable t) {
		// assert that an attempt was made to load the correct XML
		assertTrue(t.getMessage().endsWith(
				"Could not open ServletContext resource [/from-init-param.xml]"));
	}
}
 
Example 12
Source Project: java-technology-stack   Source File: Spr8510Tests.java    License: MIT License 6 votes vote down vote up
/**
 * If context config locations have been specified neither against the application
 * context nor the context loader listener, then fall back to default values.
 */
@Test
public void abstractRefreshableWAC_fallsBackToConventionBasedNaming() {
	XmlWebApplicationContext ctx = new XmlWebApplicationContext();
	//ctx.setConfigLocation("programmatic.xml"); // nothing set programmatically
	ContextLoaderListener cll = new ContextLoaderListener(ctx);

	MockServletContext sc = new MockServletContext();
	// no init-param set
	//sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml");

	try {
		cll.contextInitialized(new ServletContextEvent(sc));
		fail("expected exception");
	}
	catch (Throwable t) {
		// assert that an attempt was made to load the correct XML
		System.out.println(t.getMessage());
		assertTrue(t.getMessage().endsWith(
				"Could not open ServletContext resource [/WEB-INF/applicationContext.xml]"));
	}
}
 
Example 13
Source Project: Spring   Source File: WebAppInitializer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
	public void onStartup(ServletContext servletContext) {
		final AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
		context.register(WebConfig.class);

		servletContext.addListener(new ContextLoaderListener(context));

		final ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcherServlet", new DispatcherServlet(context));
		dispatcher.setLoadOnStartup(1);

		dispatcher.addMapping("/");
		dispatcher.addMapping("*.html");
		dispatcher.addMapping("*.pdf");
		dispatcher.addMapping("*.json");

//		dispatcher.setInitParameter("contextConfigLocation", "com.spring4.application.configuration.ApplicationConfig");
//		dispatcher.setInitParameter("contextClass", "org.springframework.web.context.support.AnnotationConfigWebApplicationContext");
	}
 
Example 14
@Override
public void onStartup(ServletContext container) {
    // Create the 'root' Spring application context
    AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
    // Register application config
    rootContext.register(AppConfig.class);

    // Manage the lifecycle of the root application context
    container.addListener(new ContextLoaderListener(rootContext));

    // Register Encoding Filter
    addEncodingFilter(container);

    // Register Logging Filter
    addLoggingFilter(container);

    // Register and map the dispatcher servlet
    addServiceDispatcherServlet(container, rootContext);
}
 
Example 15
@Override public void init(ServletContextHandler handler) {
  AnnotationConfigWebApplicationContext appContext =
    new AnnotationConfigWebApplicationContext() {
      // overriding this allows us to register dependencies of TracingHandlerInterceptor
      // without passing static state to a configuration class.
      @Override protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) {
        beanFactory.registerSingleton("httpTracing", httpTracing);
        beanFactory.registerSingleton("tracingFilter", TracingFilter.create(httpTracing));
        super.loadBeanDefinitions(beanFactory);
      }
    };

  registerTestController(appContext);
  appContext.register(TracingConfig.class); // generic tracing setup
  DispatcherServlet servlet = new DispatcherServlet(appContext);
  servlet.setDispatchOptionsRequest(true);
  handler.addServlet(new ServletHolder(servlet), "/*");
  handler.addEventListener(new ContextLoaderListener(appContext));

  // add the trace filter, which lazy initializes a real tracing filter from the spring context
  addDelegatingTracingFilter(handler);
}
 
Example 16
Source Project: tutorials   Source File: MainWebAppInitializer.java    License: MIT License 6 votes vote down vote up
@Override
public void onStartup(final ServletContext sc) throws ServletException {

    // Create the 'root' Spring application context
    final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
    root.register(WebConfig.class);

    // Manages the lifecycle of the root application context
    sc.addListener(new ContextLoaderListener(root));

    // Handles requests into the application
    final ServletRegistration.Dynamic appServlet = sc.addServlet("mvc", new DispatcherServlet(new GenericWebApplicationContext()));
    appServlet.setLoadOnStartup(1);

    final Set<String> mappingConflicts = appServlet.addMapping("/");
    if (!mappingConflicts.isEmpty()) {
        throw new IllegalStateException("'appServlet' could not be mapped to '/' due " + "to an existing mapping. This is a known issue under Tomcat versions " + "<= 7.0.14; see https://issues.apache.org/bugzilla/show_bug.cgi?id=51278");
    }
}
 
Example 17
Source Project: spring4-understanding   Source File: Spr8510Tests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void abstractRefreshableWAC_respectsProgrammaticConfigLocations() {
	XmlWebApplicationContext ctx = new XmlWebApplicationContext();
	ctx.setConfigLocation("programmatic.xml");
	ContextLoaderListener cll = new ContextLoaderListener(ctx);

	MockServletContext sc = new MockServletContext();

	try {
		cll.contextInitialized(new ServletContextEvent(sc));
		fail("expected exception");
	} catch (Throwable t) {
		// assert that an attempt was made to load the correct XML
		assertTrue(t.getMessage(), t.getMessage().endsWith(
				"Could not open ServletContext resource [/programmatic.xml]"));
	}
}
 
Example 18
Source Project: spring4-understanding   Source File: Spr8510Tests.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * If a contextConfigLocation init-param has been specified for the ContextLoaderListener,
 * then it should take precedence. This is generally not a recommended practice, but
 * when it does happen, the init-param should be considered more specific than the
 * programmatic configuration, given that it still quite possibly externalized in
 * hybrid web.xml + WebApplicationInitializer cases.
 */
@Test
public void abstractRefreshableWAC_respectsInitParam_overProgrammaticConfigLocations() {
	XmlWebApplicationContext ctx = new XmlWebApplicationContext();
	ctx.setConfigLocation("programmatic.xml");
	ContextLoaderListener cll = new ContextLoaderListener(ctx);

	MockServletContext sc = new MockServletContext();
	sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml");

	try {
		cll.contextInitialized(new ServletContextEvent(sc));
		fail("expected exception");
	} catch (Throwable t) {
		// assert that an attempt was made to load the correct XML
		assertTrue(t.getMessage(), t.getMessage().endsWith(
				"Could not open ServletContext resource [/from-init-param.xml]"));
	}
}
 
Example 19
Source Project: spring4-understanding   Source File: Spr8510Tests.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Ensure that any custom default locations are still respected.
 */
@Test
public void customAbstractRefreshableWAC_fallsBackToInitParam() {
	XmlWebApplicationContext ctx = new XmlWebApplicationContext() {
		@Override
		protected String[] getDefaultConfigLocations() {
			return new String[] { "/WEB-INF/custom.xml" };
		}
	};
	//ctx.setConfigLocation("programmatic.xml"); // nothing set programmatically
	ContextLoaderListener cll = new ContextLoaderListener(ctx);

	MockServletContext sc = new MockServletContext();
	sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml");

	try {
		cll.contextInitialized(new ServletContextEvent(sc));
		fail("expected exception");
	} catch (Throwable t) {
		// assert that an attempt was made to load the correct XML
		System.out.println(t.getMessage());
		assertTrue(t.getMessage().endsWith(
				"Could not open ServletContext resource [/from-init-param.xml]"));
	}
}
 
Example 20
Source Project: spring4-understanding   Source File: Spr8510Tests.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * If context config locations have been specified neither against the application
 * context nor the context loader listener, then fall back to default values.
 */
@Test
public void abstractRefreshableWAC_fallsBackToConventionBasedNaming() {
	XmlWebApplicationContext ctx = new XmlWebApplicationContext();
	//ctx.setConfigLocation("programmatic.xml"); // nothing set programmatically
	ContextLoaderListener cll = new ContextLoaderListener(ctx);

	MockServletContext sc = new MockServletContext();
	// no init-param set
	//sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml");

	try {
		cll.contextInitialized(new ServletContextEvent(sc));
		fail("expected exception");
	} catch (Throwable t) {
		// assert that an attempt was made to load the correct XML
		System.out.println(t.getMessage());
		assertTrue(t.getMessage().endsWith(
				"Could not open ServletContext resource [/WEB-INF/applicationContext.xml]"));
	}
}
 
Example 21
Source Project: logging-log4j-audit   Source File: WebAppInitializer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onStartup(ServletContext servletContext) {
    servletContext.setInitParameter("applicationName", APPLICATION_NAME);
    System.setProperty("applicationName", APPLICATION_NAME);
    ProfileUtil.setActiveProfile(servletContext);
    AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
    rootContext.setDisplayName(APPLICATION_NAME);
    rootContext.register(ApplicationConfiguration.class);
    servletContext.addListener(new ContextLoaderListener(rootContext));

    // MVC Context
    AnnotationConfigWebApplicationContext mvcContext = new AnnotationConfigWebApplicationContext();
    mvcContext.register(WebMvcAppContext.class);

    ServletRegistration.Dynamic restServlet = servletContext.addServlet("restServlet", new DispatcherServlet(mvcContext));
    restServlet.setLoadOnStartup(1);
    restServlet.addMapping("/*");
}
 
Example 22
Source Project: product-ei   Source File: Starter.java    License: Apache License 2.0 6 votes vote down vote up
public void startPeopleService() throws Exception {
    final File base = createBaseDirectory();
    log.info("Using base folder: " + base.getAbsolutePath());

    final Tomcat tomcat = new Tomcat();
    tomcat.setPort(8080);
    tomcat.setBaseDir(base.getAbsolutePath());

    Context context = tomcat.addContext("/", base.getAbsolutePath());
    Tomcat.addServlet(context, "CXFServlet", new CXFServlet());

    context.addServletMapping("/rest/*", "CXFServlet");
    context.addApplicationListener(ContextLoaderListener.class.getName());
    context.setLoader(new WebappLoader(Thread.currentThread().getContextClassLoader()));

    context.addParameter("contextClass", AnnotationConfigWebApplicationContext.class.getName());
    context.addParameter("contextConfigLocation", AppConfig.class.getName());

    tomcat.start();
    tomcat.getServer().await();
}
 
Example 23
Source Project: product-ei   Source File: Server.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
    final File base = createBaseDirectory();
    log.info("Using base folder: " + base.getAbsolutePath());

    final Tomcat tomcat = new Tomcat();
    tomcat.setPort(8080);
    tomcat.setBaseDir( base.getAbsolutePath() );

    Context context = tomcat.addContext( "/", base.getAbsolutePath() );
    Tomcat.addServlet( context, "CXFServlet", new CXFServlet() );

    context.addServletMapping( "/rest/*", "CXFServlet" );
    context.addApplicationListener( ContextLoaderListener.class.getName() );
    context.setLoader( new WebappLoader( Thread.currentThread().getContextClassLoader() ) );

    context.addParameter( "contextClass", AnnotationConfigWebApplicationContext.class.getName() );
    context.addParameter( "contextConfigLocation", MusicConfig.class.getName() );

    tomcat.start();
    tomcat.getServer().await();
}
 
Example 24
Source Project: herd   Source File: WarInitializer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Initializes the context loader listener which bootstraps Spring and provides access to the application context.
 *
 * @param servletContext the servlet context.
 */
protected void initContextLoaderListener(ServletContext servletContext)
{
    // Add the context loader listener for the base (i.e. root) Spring configuration.
    // We register all our @Configuration annotated classes with the context so Spring will load all the @Bean's via these classes.
    // We also set the application context in an application context holder before "registering" so static @Bean's
    // (e.g. PropertySourcesPlaceholderConfigurer) will have access to it since they can't take advantage of autowiring or having a class be
    // ApplicationContextAware to get it.
    AnnotationConfigWebApplicationContext contextLoaderListenerContext = new AnnotationConfigWebApplicationContext();
    ApplicationContextHolder.setApplicationContext(contextLoaderListenerContext);
    contextLoaderListenerContext
        .register(CoreSpringModuleConfig.class, DaoSpringModuleConfig.class, DaoEnvSpringModuleConfig.class, ServiceSpringModuleConfig.class,
            ServiceEnvSpringModuleConfig.class, UiSpringModuleConfig.class, UiEnvSpringModuleConfig.class, RestSpringModuleConfig.class,
            AppSpringModuleConfig.class);
    servletContext.addListener(new ContextLoaderListener(contextLoaderListenerContext));
}
 
Example 25
Source Project: micro-server   Source File: Module.java    License: Apache License 2.0 6 votes vote down vote up
default List<ServletContextListener> getListeners(ServerData data) {
    List<ServletContextListener> list = new ArrayList<>();
    if (data.getRootContext() instanceof WebApplicationContext) {
        list.add(new ContextLoaderListener(
                                           (WebApplicationContext) data.getRootContext()));
    }

    ListX<Plugin> modules = PluginLoader.INSTANCE.plugins.get();

    ListX<ServletContextListener> listeners = modules.stream()
                                                       .filter(module -> module.servletContextListeners() != null)
                                                       .concatMap(Plugin::servletContextListeners)
                                                       .map(fn -> fn.apply(data))
                                                       .to(ListX::fromIterable);

    return listeners.plusAll(list);
}
 
Example 26
Source Project: service-autodiscovery   Source File: ServerStarter.java    License: Apache License 2.0 6 votes vote down vote up
public static void main( final String[] args ) throws Exception {
	if( args.length != 1 ) {
		System.out.println( "Please provide port number" );
		return;
	}
	
	final int port = Integer.valueOf( args[ 0 ] );
	final Server server = new Server( port );
	 
	System.setProperty( AppConfig.SERVER_PORT, Integer.toString( port ) );
	System.setProperty( AppConfig.SERVER_HOST, "localhost" );
	
		// Register and map the dispatcher servlet
		final ServletHolder servletHolder = new ServletHolder( new CXFServlet() );
		final ServletContextHandler context = new ServletContextHandler(); 		
		context.setContextPath( "/" );
		context.addServlet( servletHolder, "/" + AppConfig.CONTEXT_PATH + "/*" ); 	
		context.addEventListener( new ContextLoaderListener() );
		
		context.setInitParameter( "contextClass", AnnotationConfigWebApplicationContext.class.getName() );
		context.setInitParameter( "contextConfigLocation", AppConfig.class.getName() );
		 		
       server.setHandler( context );
       server.start();
       server.join();	
}
 
Example 27
Source Project: cxf   Source File: StatsServer.java    License: 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 28
@Override
public void initialize(AnnotationConfigWebApplicationContext applicationContext) {
	final AnnotationConfigWebApplicationContext rootCtx = new AnnotationConfigWebApplicationContext();
	rootCtx.register(TraceeInterceptorSpringConfig.class);
	final ServletContext servletContext = applicationContext.getServletContext();

	// Manage the lifecycle of the root application context
	servletContext.addListener(new ContextLoaderListener(rootCtx));

	// Create the dispatcher servlet's Spring application context
	AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
	dispatcherContext.register(TraceeInterceptorSpringConfig.class);

	// Register and map the dispatcher servlet
	ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
	dispatcher.setLoadOnStartup(1);
	dispatcher.addMapping("/");

}
 
Example 29
Source Project: tutorials   Source File: MyWebApplicationInitializer.java    License: MIT License 6 votes vote down vote up
/**
 * Register and configure all Servlet container components necessary to power the web application.
 */
@Override
public void onStartup(final ServletContext sc) throws ServletException {
    System.out.println("MyWebApplicationInitializer.onStartup()");

    // Create the 'root' Spring application context
    final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
    root.scan("com.baeldung.spring.config");
    // root.getEnvironment().setDefaultProfiles("embedded");

    sc.addListener(new ContextLoaderListener(root));

    DispatcherServlet dv = new DispatcherServlet(root);
    
    final ServletRegistration.Dynamic appServlet = sc.addServlet("mvc",dv);
    appServlet.setLoadOnStartup(1);
    final Set<String> mappingConflicts = appServlet.addMapping("/");
    if (!mappingConflicts.isEmpty()) {
        throw new IllegalStateException("'appServlet' could not be mapped to '/' due " + "to an existing mapping. This is a known issue under Tomcat versions " + "<= 7.0.14; see https://issues.apache.org/bugzilla/show_bug.cgi?id=51278");
    }
}
 
Example 30
Source Project: spring-analysis-note   Source File: Spr8510Tests.java    License: MIT License 5 votes vote down vote up
/**
 * Ensure that ContextLoaderListener and GenericWebApplicationContext interact nicely.
 */
@Test
public void genericWAC() {
	GenericWebApplicationContext ctx = new GenericWebApplicationContext();
	ContextLoaderListener cll = new ContextLoaderListener(ctx);

	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(ctx);
	scanner.scan("bogus.pkg");

	cll.contextInitialized(new ServletContextEvent(new MockServletContext()));
}