javax.servlet.ServletContextListener Java Examples

The following examples show how to use javax.servlet.ServletContextListener. 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: ContextLoaderTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testContextLoaderListenerWithDefaultContext() {
	MockServletContext sc = new MockServletContext("");
	sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM,
			"/org/springframework/web/context/WEB-INF/applicationContext.xml " +
			"/org/springframework/web/context/WEB-INF/context-addition.xml");
	ServletContextListener listener = new ContextLoaderListener();
	ServletContextEvent event = new ServletContextEvent(sc);
	listener.contextInitialized(event);
	WebApplicationContext context = (WebApplicationContext) sc.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
	assertTrue("Correct WebApplicationContext exposed in ServletContext", context instanceof XmlWebApplicationContext);
	assertTrue(WebApplicationContextUtils.getRequiredWebApplicationContext(sc) instanceof XmlWebApplicationContext);
	LifecycleBean lb = (LifecycleBean) context.getBean("lifecycle");
	assertTrue("Has father", context.containsBean("father"));
	assertTrue("Has rod", context.containsBean("rod"));
	assertTrue("Has kerry", context.containsBean("kerry"));
	assertTrue("Not destroyed", !lb.isDestroyed());
	assertFalse(context.containsBean("beans1.bean1"));
	assertFalse(context.containsBean("beans1.bean2"));
	listener.contextDestroyed(event);
	assertTrue("Destroyed", lb.isDestroyed());
	assertNull(sc.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE));
	assertNull(WebApplicationContextUtils.getWebApplicationContext(sc));
}
 
Example #2
Source File: DefaultWebApplication.java    From piranha with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Initialize the servlet container initializers.
 */
@Override
public void initializeInitializers() {
    boolean error = false;
    for (ServletContainerInitializer initializer : initializers) {
        try {
            initializer.onStartup(annotationManager.getAnnotatedClasses(), this);
        } catch (Throwable t) {
            LOGGER.log(WARNING, t,  () -> "Initializer " + initializer.getClass().getName() + " failing onStartup");
            error = true;
        }
    }
    if (!error) {
        @SuppressWarnings("unchecked")
        List<ServletContextListener> listeners = (List<ServletContextListener>) contextListeners.clone();
        listeners.stream().forEach((listener) -> {
            listener.contextInitialized(new ServletContextEvent(this));
        });
    } else {
        status = ERROR;
    }
}
 
Example #3
Source File: DefaultWebApplication.java    From piranha with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Create the listener.
 *
 * @param <T> the type.
 * @param clazz the class of the listener to create.
 * @return the listener.
 * @throws ServletException when it fails to create the listener.
 */
@Override
public <T extends EventListener> T createListener(Class<T> clazz) throws ServletException {
    T result = objectInstanceManager.createListener(clazz);
    boolean ok = false;
    if (result instanceof ServletContextListener || result instanceof ServletContextAttributeListener || result instanceof ServletRequestListener
            || result instanceof ServletRequestAttributeListener || result instanceof HttpSessionAttributeListener
            || result instanceof HttpSessionIdListener || result instanceof HttpSessionListener) {
        ok = true;
    }

    if (!ok) {
        LOGGER.log(WARNING, "Unable to create listener: {0}", clazz);
        throw new IllegalArgumentException("Invalid type");
    }

    return result;
}
 
Example #4
Source File: DefaultWebApplication.java    From piranha with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Add the listener.
 *
 * @param <T> the type.
 * @param listener the listener
 */
@Override
public <T extends EventListener> void addListener(T listener) {
    if (listener instanceof ServletContextListener) {
        contextListeners.add((ServletContextListener) listener);
    }
    if (listener instanceof ServletContextAttributeListener) {
        contextAttributeListeners.add((ServletContextAttributeListener) listener);
    }
    if (listener instanceof ServletRequestListener) {
        requestListeners.add((ServletRequestListener) listener);
    }
    if (listener instanceof ServletRequestAttributeListener) {
        httpRequestManager.addListener((ServletRequestAttributeListener) listener);
    }
    if (listener instanceof HttpSessionAttributeListener) {
        httpSessionManager.addListener(listener);
    }
    if (listener instanceof HttpSessionIdListener) {
        httpSessionManager.addListener(listener);
    }
    if (listener instanceof HttpSessionListener) {
        httpSessionManager.addListener(listener);
    }
}
 
Example #5
Source File: ProxyServletListener.java    From lemon with Apache License 2.0 6 votes vote down vote up
public void contextInitialized(ServletContextEvent sce) {
    ctx = WebApplicationContextUtils.getWebApplicationContext(sce
            .getServletContext());

    if (ctx == null) {
        logger.warn("cannot find applicationContext");

        return;
    }

    Collection<ServletContextListener> servletContextListeners = ctx
            .getBeansOfType(ServletContextListener.class).values();

    for (ServletContextListener servletContextListener : servletContextListeners) {
        servletContextListener.contextInitialized(sce);
    }
}
 
Example #6
Source File: ContextLoaderTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testContextLoaderWithInvalidContext() throws Exception {
	MockServletContext sc = new MockServletContext("");
	sc.addInitParameter(ContextLoader.CONTEXT_CLASS_PARAM,
			"org.springframework.web.context.support.InvalidWebApplicationContext");
	ServletContextListener listener = new ContextLoaderListener();
	ServletContextEvent event = new ServletContextEvent(sc);
	try {
		listener.contextInitialized(event);
		fail("Should have thrown ApplicationContextException");
	}
	catch (ApplicationContextException ex) {
		// expected
		assertTrue(ex.getCause() instanceof ClassNotFoundException);
	}
}
 
Example #7
Source File: BootFrontEndApplicationConfigurator.java    From micro-server with Apache License 2.0 6 votes vote down vote up
@Override
public void onStartup(ServletContext webappContext) throws ServletException {
	
	ModuleDataExtractor extractor = new ModuleDataExtractor(module);
	microserverEnvironment.assureModule(module);
	String fullRestResource = "/" + module.getContext() + "/*";

	ServerData serverData = new ServerData(microserverEnvironment.getModuleBean(module).getPort(),
			Arrays.asList(),
			rootContext, fullRestResource, module);
	List<FilterData> filterDataList = extractor.createFilteredDataList(serverData);
	List<ServletData> servletDataList = extractor.createServletDataList(serverData);
	new ServletConfigurer(serverData, LinkedListX.fromIterable(servletDataList)).addServlets(webappContext);

	new FilterConfigurer(serverData, LinkedListX.fromIterable(filterDataList)).addFilters(webappContext);
	PersistentList<ServletContextListener> servletContextListenerData = LinkedListX.fromIterable(module.getListeners(serverData)).filter(i->!(i instanceof ContextLoader));
    PersistentList<ServletRequestListener> servletRequestListenerData =	LinkedListX.fromIterable(module.getRequestListeners(serverData));
	
	new ServletContextListenerConfigurer(serverData, servletContextListenerData, servletRequestListenerData).addListeners(webappContext);
	
}
 
Example #8
Source File: ContextLoaderTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testContextLoaderListenerWithDefaultContext() {
	MockServletContext sc = new MockServletContext("");
	sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM,
			"/org/springframework/web/context/WEB-INF/applicationContext.xml " +
			"/org/springframework/web/context/WEB-INF/context-addition.xml");
	ServletContextListener listener = new ContextLoaderListener();
	ServletContextEvent event = new ServletContextEvent(sc);
	listener.contextInitialized(event);
	String contextAttr = WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE;
	WebApplicationContext context = (WebApplicationContext) sc.getAttribute(contextAttr);
	assertTrue("Correct WebApplicationContext exposed in ServletContext", context instanceof XmlWebApplicationContext);
	assertTrue(WebApplicationContextUtils.getRequiredWebApplicationContext(sc) instanceof XmlWebApplicationContext);
	LifecycleBean lb = (LifecycleBean) context.getBean("lifecycle");
	assertTrue("Has father", context.containsBean("father"));
	assertTrue("Has rod", context.containsBean("rod"));
	assertTrue("Has kerry", context.containsBean("kerry"));
	assertTrue("Not destroyed", !lb.isDestroyed());
	assertFalse(context.containsBean("beans1.bean1"));
	assertFalse(context.containsBean("beans1.bean2"));
	listener.contextDestroyed(event);
	assertTrue("Destroyed", lb.isDestroyed());
	assertNull(sc.getAttribute(contextAttr));
	assertNull(WebApplicationContextUtils.getWebApplicationContext(sc));
}
 
Example #9
Source File: ContextLoaderTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testContextLoaderWithInvalidContext() throws Exception {
	MockServletContext sc = new MockServletContext("");
	sc.addInitParameter(ContextLoader.CONTEXT_CLASS_PARAM,
			"org.springframework.web.context.support.InvalidWebApplicationContext");
	ServletContextListener listener = new ContextLoaderListener();
	ServletContextEvent event = new ServletContextEvent(sc);
	try {
		listener.contextInitialized(event);
		fail("Should have thrown ApplicationContextException");
	}
	catch (ApplicationContextException ex) {
		// expected
		assertTrue(ex.getCause() instanceof ClassNotFoundException);
	}
}
 
Example #10
Source File: DeploymentManagerImpl.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Override
public void undeploy() {
    try {
        deployment.createThreadSetupAction(new ThreadSetupHandler.Action<Void, Object>() {
            @Override
            public Void call(HttpServerExchange exchange, Object ignore) throws ServletException {
                for(ServletContextListener listener : deployment.getDeploymentInfo().getDeploymentCompleteListeners()) {
                    try {
                        listener.contextDestroyed(new ServletContextEvent(deployment.getServletContext()));
                    } catch (Throwable t) {
                        UndertowServletLogger.REQUEST_LOGGER.failedToDestroy(listener, t);
                    }
                }
                deployment.destroy();
                deployment = null;
                state = State.UNDEPLOYED;
                return null;
            }
        }).call(null, null);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}
 
Example #11
Source File: ApplicationListeners.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
public void contextInitialized() {
    if(!started) {
        return;
    }
    //new listeners can be added here, so we don't use an iterator
    final ServletContextEvent event = new ServletContextEvent(servletContext);
    for (int i = 0; i < servletContextListeners.length; ++i) {
        ManagedListener listener = servletContextListeners[i];
        IN_PROGRAMATIC_SC_LISTENER_INVOCATION.set(listener.isProgramatic() ? PROGRAMATIC_LISTENER : DECLARED_LISTENER);
        try {
            this.<ServletContextListener>get(listener).contextInitialized(event);
        } finally {
            IN_PROGRAMATIC_SC_LISTENER_INVOCATION.remove();
        }
    }
}
 
Example #12
Source File: BootFrontEndApplicationConfigurator.java    From micro-server with Apache License 2.0 6 votes vote down vote up
@Override
public void onStartup(ServletContext webappContext) throws ServletException {
	
	ModuleDataExtractor extractor = new ModuleDataExtractor(module);
	microserverEnvironment.assureModule(module);
	String fullRestResource = "/" + module.getContext() + "/*";

	ServerData serverData = new ServerData(microserverEnvironment.getModuleBean(module).getPort(),
			Arrays.asList(),
			rootContext, fullRestResource, module);
	List<FilterData> filterDataList = extractor.createFilteredDataList(serverData);
	List<ServletData> servletDataList = extractor.createServletDataList(serverData);
	new ServletConfigurer(serverData, LinkedListX.fromIterable(servletDataList)).addServlets(webappContext);

	new FilterConfigurer(serverData, LinkedListX.fromIterable(filterDataList)).addFilters(webappContext);
	PersistentList<ServletContextListener> servletContextListenerData = LinkedListX.fromIterable(module.getListeners(serverData)).filter(i->!(i instanceof ContextLoader));
    PersistentList<ServletRequestListener> servletRequestListenerData =	LinkedListX.fromIterable(module.getRequestListeners(serverData));
	
	new ServletContextListenerConfigurer(serverData, servletContextListenerData, servletRequestListenerData).addListeners(webappContext);
	
}
 
Example #13
Source File: ServletContextImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void addListener(final Class<? extends EventListener> listenerClass) {
    ensureNotInitialized();
    ensureNotProgramaticListener();
    if (ApplicationListeners.listenerState() != NO_LISTENER
            && ServletContextListener.class.isAssignableFrom(listenerClass)) {
        throw UndertowServletMessages.MESSAGES.cannotAddServletContextListener();
    }
    InstanceFactory<? extends EventListener> factory = null;
    try {
        factory = deploymentInfo.getClassIntrospecter().createInstanceFactory(listenerClass);
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
    final ListenerInfo listener = new ListenerInfo(listenerClass, factory);
    deploymentInfo.addListener(listener);
    deployment.getApplicationListeners().addListener(new ManagedListener(listener, true));
}
 
Example #14
Source File: ApplicationListeners.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public void contextInitialized() {
    if(!started) {
        return;
    }
    //new listeners can be added here, so we don't use an iterator
    final ServletContextEvent event = new ServletContextEvent(servletContext);
    for (int i = 0; i < servletContextListeners.length; ++i) {
        ManagedListener listener = servletContextListeners[i];
        IN_PROGRAMATIC_SC_LISTENER_INVOCATION.set(listener.isProgramatic() ? PROGRAMATIC_LISTENER : DECLARED_LISTENER);
        try {
            this.<ServletContextListener>get(listener).contextInitialized(event);
        } finally {
            IN_PROGRAMATIC_SC_LISTENER_INVOCATION.remove();
        }
    }
}
 
Example #15
Source File: Module.java    From micro-server with 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 #16
Source File: ContextLoaderTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testContextLoaderWithInvalidContext() throws Exception {
	MockServletContext sc = new MockServletContext("");
	sc.addInitParameter(ContextLoader.CONTEXT_CLASS_PARAM,
			"org.springframework.web.context.support.InvalidWebApplicationContext");
	ServletContextListener listener = new ContextLoaderListener();
	ServletContextEvent event = new ServletContextEvent(sc);
	try {
		listener.contextInitialized(event);
		fail("Should have thrown ApplicationContextException");
	}
	catch (ApplicationContextException ex) {
		// expected
		assertTrue(ex.getCause() instanceof ClassNotFoundException);
	}
}
 
Example #17
Source File: DeploymentManagerImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void undeploy() {
    try {
        deployment.createThreadSetupAction(new ThreadSetupHandler.Action<Void, Object>() {
            @Override
            public Void call(HttpServerExchange exchange, Object ignore) throws ServletException {
                for(ServletContextListener listener : deployment.getDeploymentInfo().getDeploymentCompleteListeners()) {
                    try {
                        listener.contextDestroyed(new ServletContextEvent(deployment.getServletContext()));
                    } catch (Throwable t) {
                        UndertowServletLogger.REQUEST_LOGGER.failedToDestroy(listener, t);
                    }
                }
                deployment.destroy();
                deployment = null;
                state = State.UNDEPLOYED;
                return null;
            }
        }).call(null, null);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}
 
Example #18
Source File: ContextLoaderTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testContextLoaderListenerWithDefaultContext() {
	MockServletContext sc = new MockServletContext("");
	sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM,
			"/org/springframework/web/context/WEB-INF/applicationContext.xml " +
			"/org/springframework/web/context/WEB-INF/context-addition.xml");
	ServletContextListener listener = new ContextLoaderListener();
	ServletContextEvent event = new ServletContextEvent(sc);
	listener.contextInitialized(event);
	String contextAttr = WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE;
	WebApplicationContext context = (WebApplicationContext) sc.getAttribute(contextAttr);
	assertTrue("Correct WebApplicationContext exposed in ServletContext", context instanceof XmlWebApplicationContext);
	assertTrue(WebApplicationContextUtils.getRequiredWebApplicationContext(sc) instanceof XmlWebApplicationContext);
	LifecycleBean lb = (LifecycleBean) context.getBean("lifecycle");
	assertTrue("Has father", context.containsBean("father"));
	assertTrue("Has rod", context.containsBean("rod"));
	assertTrue("Has kerry", context.containsBean("kerry"));
	assertTrue("Not destroyed", !lb.isDestroyed());
	assertFalse(context.containsBean("beans1.bean1"));
	assertFalse(context.containsBean("beans1.bean2"));
	listener.contextDestroyed(event);
	assertTrue("Destroyed", lb.isDestroyed());
	assertNull(sc.getAttribute(contextAttr));
	assertNull(WebApplicationContextUtils.getWebApplicationContext(sc));
}
 
Example #19
Source File: ListenerRunnerTest.java    From micro-server with Apache License 2.0 5 votes vote down vote up
@Before
public void startServer(){
	List<ServletContextListener> listeners = Arrays.asList(new ConfiguredListener());
	server = new MicroserverApp( ListenerRunnerTest.class, ConfigurableModule.builder().context("listener-app").listeners(listeners ).build());
	server.start();

}
 
Example #20
Source File: AllData.java    From micro-server with Apache License 2.0 5 votes vote down vote up
public AllData(ServerData serverData, PersistentList<FilterData> filterDataList,
                  PersistentList<ServletData> servletDataList,
                  PersistentList<ServletContextListener> servletContextListeners,
                  PersistentList<ServletRequestListener> servletRequestListeners  ) {

	this.servletContextListeners = Seq.fromIterable(UsefulStaticMethods.either(servletContextListeners, new ArrayList<ServletContextListener>()));

	this.servletRequestListeners = Seq.fromIterable(UsefulStaticMethods.either(servletRequestListeners, new ArrayList<ServletRequestListener>()));

	this.filterDataList = Seq.fromIterable(UsefulStaticMethods.either(filterDataList, new ArrayList<FilterData>()));
	this.servletDataList = Seq.fromIterable(UsefulStaticMethods.either(servletDataList, new ArrayList<ServletData>()));
	this.serverData = serverData;
}
 
Example #21
Source File: SecureJettyMixin.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
public SecureJettyMixin( @This HasIdentity meAsIdentity,
                         @Service Server jettyServer,
                         @Service Iterable<ServiceReference<ServletContextListener>> contextListeners,
                         @Service Iterable<ServiceReference<Servlet>> servlets,
                         @Service Iterable<ServiceReference<Filter>> filters,
                         @Optional @Service MBeanServer mBeanServer )
{
    super( meAsIdentity.identity().get(), jettyServer, contextListeners, servlets, filters, mBeanServer );
}
 
Example #22
Source File: ConfigurableModule.java    From micro-server with Apache License 2.0 5 votes vote down vote up
@Override
public List<ServletContextListener> getListeners(ServerData data) {
    if (listeners != null)
        return ListX.fromIterable((concat(this.listeners, extract(() -> Module.super.getListeners(data)))));

    return Module.super.getListeners(data);
}
 
Example #23
Source File: CdiPlugin.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isEEComponent(final Class<?> impl) {
    return Servlet.class.isAssignableFrom(impl)
            || Filter.class.isAssignableFrom(impl)
            || ServletContextListener.class.isAssignableFrom(impl)
            || JspTag.class.isAssignableFrom(impl);
}
 
Example #24
Source File: AllData.java    From micro-server with Apache License 2.0 5 votes vote down vote up
public AllData(ServerData serverData, List<FilterData> filterDataList,
			List<ServletData> servletDataList,
			List<ServletContextListener> servletContextListeners,
			List<ServletRequestListener> servletRequestListeners  ) {

	this.servletContextListeners = Seq.fromIterable(UsefulStaticMethods.either(servletContextListeners, new ArrayList<ServletContextListener>()));

	this.servletRequestListeners = Seq.fromIterable(UsefulStaticMethods.either(servletRequestListeners, new ArrayList<ServletRequestListener>()));

	this.filterDataList = Seq.fromIterable(UsefulStaticMethods.either(filterDataList, new ArrayList<FilterData>()));
	this.servletDataList = Seq.fromIterable(UsefulStaticMethods.either(servletDataList, new ArrayList<ServletData>()));
	this.serverData = serverData;
}
 
Example #25
Source File: NexusBundleExtender.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void start(final BundleContext ctx) {
  context = ctx;

  listener = new NexusContextListener(this);

  final Dictionary<String, Object> listenerProperties = new Hashtable<>();
  listenerProperties.put("name", "nexus");

  // register our listener; the bootstrap code will call us back with the servlet context
  ctx.registerService(ServletContextListener.class, listener, listenerProperties);
}
 
Example #26
Source File: ContextLoaderTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testContextLoaderWithDefaultContextAndParent() throws Exception {
	MockServletContext sc = new MockServletContext("");
	sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM,
			"/org/springframework/web/context/WEB-INF/applicationContext.xml "
					+ "/org/springframework/web/context/WEB-INF/context-addition.xml");
	sc.addInitParameter(ContextLoader.LOCATOR_FACTORY_SELECTOR_PARAM,
			"classpath:org/springframework/web/context/ref1.xml");
	sc.addInitParameter(ContextLoader.LOCATOR_FACTORY_KEY_PARAM, "a.qualified.name.of.some.sort");
	ServletContextListener listener = new ContextLoaderListener();
	ServletContextEvent event = new ServletContextEvent(sc);
	listener.contextInitialized(event);
	WebApplicationContext context = (WebApplicationContext) sc.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
	assertTrue("Correct WebApplicationContext exposed in ServletContext",
			context instanceof XmlWebApplicationContext);
	LifecycleBean lb = (LifecycleBean) context.getBean("lifecycle");
	assertTrue("Has father", context.containsBean("father"));
	assertTrue("Has rod", context.containsBean("rod"));
	assertTrue("Has kerry", context.containsBean("kerry"));
	assertTrue("Not destroyed", !lb.isDestroyed());
	assertTrue(context.containsBean("beans1.bean1"));
	assertTrue(context.isTypeMatch("beans1.bean1", org.springframework.beans.factory.access.TestBean.class));
	assertTrue(context.containsBean("beans1.bean2"));
	assertTrue(context.isTypeMatch("beans1.bean2", org.springframework.beans.factory.access.TestBean.class));
	listener.contextDestroyed(event);
	assertTrue("Destroyed", lb.isDestroyed());
}
 
Example #27
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 #28
Source File: ContextLoaderTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testContextLoaderWithDefaultLocation() throws Exception {
	MockServletContext sc = new MockServletContext("");
	ServletContextListener listener = new ContextLoaderListener();
	ServletContextEvent event = new ServletContextEvent(sc);
	try {
		listener.contextInitialized(event);
		fail("Should have thrown BeanDefinitionStoreException");
	}
	catch (BeanDefinitionStoreException ex) {
		// expected
		assertTrue(ex.getCause() instanceof IOException);
		assertTrue(ex.getCause().getMessage().contains("/WEB-INF/applicationContext.xml"));
	}
}
 
Example #29
Source File: ContextLoaderTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testContextLoaderWithCustomContext() throws Exception {
	MockServletContext sc = new MockServletContext("");
	sc.addInitParameter(ContextLoader.CONTEXT_CLASS_PARAM,
			"org.springframework.web.servlet.SimpleWebApplicationContext");
	ServletContextListener listener = new ContextLoaderListener();
	ServletContextEvent event = new ServletContextEvent(sc);
	listener.contextInitialized(event);
	WebApplicationContext wc = (WebApplicationContext) sc.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
	assertTrue("Correct WebApplicationContext exposed in ServletContext", wc instanceof SimpleWebApplicationContext);
}
 
Example #30
Source File: ContextLoaderTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testContextLoaderWithInvalidLocation() throws Exception {
	MockServletContext sc = new MockServletContext("");
	sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "/WEB-INF/myContext.xml");
	ServletContextListener listener = new ContextLoaderListener();
	ServletContextEvent event = new ServletContextEvent(sc);
	try {
		listener.contextInitialized(event);
		fail("Should have thrown BeanDefinitionStoreException");
	}
	catch (BeanDefinitionStoreException ex) {
		// expected
		assertTrue(ex.getCause() instanceof FileNotFoundException);
	}
}