Search in sources :

Example 11 with ServletContextEvent

use of jakarta.servlet.ServletContextEvent in project tomcat by apache.

the class StandardContext method listenerStop.

/**
 * Send an application stop event to all interested listeners.
 * @return <code>true</code> if all events were sent successfully,
 * or <code>false</code> otherwise.
 */
public boolean listenerStop() {
    if (log.isDebugEnabled()) {
        log.debug("Sending application stop events");
    }
    boolean ok = true;
    Object[] listeners = getApplicationLifecycleListeners();
    if (listeners != null && listeners.length > 0) {
        ServletContextEvent event = new ServletContextEvent(getServletContext());
        ServletContextEvent tldEvent = null;
        if (noPluggabilityServletContext != null) {
            tldEvent = new ServletContextEvent(noPluggabilityServletContext);
        }
        for (int i = 0; i < listeners.length; i++) {
            int j = (listeners.length - 1) - i;
            if (listeners[j] == null) {
                continue;
            }
            if (listeners[j] instanceof ServletContextListener) {
                ServletContextListener listener = (ServletContextListener) listeners[j];
                try {
                    fireContainerEvent("beforeContextDestroyed", listener);
                    if (noPluggabilityListeners.contains(listener)) {
                        listener.contextDestroyed(tldEvent);
                    } else {
                        listener.contextDestroyed(event);
                    }
                    fireContainerEvent("afterContextDestroyed", listener);
                } catch (Throwable t) {
                    ExceptionUtils.handleThrowable(t);
                    fireContainerEvent("afterContextDestroyed", listener);
                    getLogger().error(sm.getString("standardContext.listenerStop", listeners[j].getClass().getName()), t);
                    ok = false;
                }
            }
            try {
                if (getInstanceManager() != null) {
                    getInstanceManager().destroyInstance(listeners[j]);
                }
            } catch (Throwable t) {
                t = ExceptionUtils.unwrapInvocationTargetException(t);
                ExceptionUtils.handleThrowable(t);
                getLogger().error(sm.getString("standardContext.listenerStop", listeners[j].getClass().getName()), t);
                ok = false;
            }
        }
    }
    // Annotation processing
    listeners = getApplicationEventListeners();
    if (listeners != null) {
        for (int i = 0; i < listeners.length; i++) {
            int j = (listeners.length - 1) - i;
            if (listeners[j] == null) {
                continue;
            }
            try {
                if (getInstanceManager() != null) {
                    getInstanceManager().destroyInstance(listeners[j]);
                }
            } catch (Throwable t) {
                t = ExceptionUtils.unwrapInvocationTargetException(t);
                ExceptionUtils.handleThrowable(t);
                getLogger().error(sm.getString("standardContext.listenerStop", listeners[j].getClass().getName()), t);
                ok = false;
            }
        }
    }
    setApplicationEventListeners(null);
    setApplicationLifecycleListeners(null);
    noPluggabilityServletContext = null;
    noPluggabilityListeners.clear();
    return ok;
}
Also used : ServletContextListener(jakarta.servlet.ServletContextListener) ServletContextEvent(jakarta.servlet.ServletContextEvent) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint)

Example 12 with ServletContextEvent

use of jakarta.servlet.ServletContextEvent in project tomcat by apache.

the class StandardContext method listenerStart.

/**
 * Configure the set of instantiated application event listeners
 * for this Context.
 * @return <code>true</code> if all listeners wre
 * initialized successfully, or <code>false</code> otherwise.
 */
public boolean listenerStart() {
    if (log.isDebugEnabled()) {
        log.debug("Configuring application event listeners");
    }
    // Instantiate the required listeners
    String[] listeners = findApplicationListeners();
    Object[] results = new Object[listeners.length];
    boolean ok = true;
    for (int i = 0; i < results.length; i++) {
        if (getLogger().isDebugEnabled()) {
            getLogger().debug(" Configuring event listener class '" + listeners[i] + "'");
        }
        try {
            String listener = listeners[i];
            results[i] = getInstanceManager().newInstance(listener);
        } catch (Throwable t) {
            t = ExceptionUtils.unwrapInvocationTargetException(t);
            ExceptionUtils.handleThrowable(t);
            getLogger().error(sm.getString("standardContext.applicationListener", listeners[i]), t);
            ok = false;
        }
    }
    if (!ok) {
        getLogger().error(sm.getString("standardContext.applicationSkipped"));
        return false;
    }
    // Sort listeners in two arrays
    List<Object> eventListeners = new ArrayList<>();
    List<Object> lifecycleListeners = new ArrayList<>();
    for (Object result : results) {
        if ((result instanceof ServletContextAttributeListener) || (result instanceof ServletRequestAttributeListener) || (result instanceof ServletRequestListener) || (result instanceof HttpSessionIdListener) || (result instanceof HttpSessionAttributeListener)) {
            eventListeners.add(result);
        }
        if ((result instanceof ServletContextListener) || (result instanceof HttpSessionListener)) {
            lifecycleListeners.add(result);
        }
    }
    // Listener instances may have been added directly to this Context by
    // ServletContextInitializers and other code via the pluggability APIs.
    // Put them these listeners after the ones defined in web.xml and/or
    // annotations then overwrite the list of instances with the new, full
    // list.
    eventListeners.addAll(Arrays.asList(getApplicationEventListeners()));
    setApplicationEventListeners(eventListeners.toArray());
    for (Object lifecycleListener : getApplicationLifecycleListeners()) {
        lifecycleListeners.add(lifecycleListener);
        if (lifecycleListener instanceof ServletContextListener) {
            noPluggabilityListeners.add(lifecycleListener);
        }
    }
    setApplicationLifecycleListeners(lifecycleListeners.toArray());
    if (getLogger().isDebugEnabled()) {
        getLogger().debug("Sending application start events");
    }
    // Ensure context is not null
    getServletContext();
    context.setNewServletContextListenerAllowed(false);
    Object[] instances = getApplicationLifecycleListeners();
    if (instances == null || instances.length == 0) {
        return ok;
    }
    ServletContextEvent event = new ServletContextEvent(getServletContext());
    ServletContextEvent tldEvent = null;
    if (noPluggabilityListeners.size() > 0) {
        noPluggabilityServletContext = new NoPluggabilityServletContext(getServletContext());
        tldEvent = new ServletContextEvent(noPluggabilityServletContext);
    }
    for (Object instance : instances) {
        if (!(instance instanceof ServletContextListener)) {
            continue;
        }
        ServletContextListener listener = (ServletContextListener) instance;
        try {
            fireContainerEvent("beforeContextInitialized", listener);
            if (noPluggabilityListeners.contains(listener)) {
                listener.contextInitialized(tldEvent);
            } else {
                listener.contextInitialized(event);
            }
            fireContainerEvent("afterContextInitialized", listener);
        } catch (Throwable t) {
            ExceptionUtils.handleThrowable(t);
            fireContainerEvent("afterContextInitialized", listener);
            getLogger().error(sm.getString("standardContext.listenerStart", instance.getClass().getName()), t);
            ok = false;
        }
    }
    return ok;
}
Also used : ServletContextAttributeListener(jakarta.servlet.ServletContextAttributeListener) ServletRequestAttributeListener(jakarta.servlet.ServletRequestAttributeListener) HttpSessionListener(jakarta.servlet.http.HttpSessionListener) ServletContextListener(jakarta.servlet.ServletContextListener) ServletRequestListener(jakarta.servlet.ServletRequestListener) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint) HttpSessionAttributeListener(jakarta.servlet.http.HttpSessionAttributeListener) HttpSessionIdListener(jakarta.servlet.http.HttpSessionIdListener) ServletContextEvent(jakarta.servlet.ServletContextEvent)

Example 13 with ServletContextEvent

use of jakarta.servlet.ServletContextEvent in project spring-framework by spring-projects.

the class Spr8510Tests method customAbstractRefreshableWAC_fallsBackToInitParam.

/**
 * 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");
    assertThatExceptionOfType(Throwable.class).isThrownBy(() -> cll.contextInitialized(new ServletContextEvent(sc))).withMessageEndingWith("Could not open ServletContext resource [/from-init-param.xml]");
}
Also used : ContextLoaderListener(org.springframework.web.context.ContextLoaderListener) MockServletContext(org.springframework.web.testfixture.servlet.MockServletContext) ServletContextEvent(jakarta.servlet.ServletContextEvent) Test(org.junit.jupiter.api.Test)

Example 14 with ServletContextEvent

use of jakarta.servlet.ServletContextEvent in project spring-framework by spring-projects.

the class Spr8510Tests method abstractRefreshableWAC_respectsInitParam_overProgrammaticConfigLocations.

/**
 * 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");
    assertThatExceptionOfType(Throwable.class).isThrownBy(() -> cll.contextInitialized(new ServletContextEvent(sc))).withMessageEndingWith("Could not open ServletContext resource [/from-init-param.xml]");
}
Also used : ContextLoaderListener(org.springframework.web.context.ContextLoaderListener) MockServletContext(org.springframework.web.testfixture.servlet.MockServletContext) ServletContextEvent(jakarta.servlet.ServletContextEvent) Test(org.junit.jupiter.api.Test)

Example 15 with ServletContextEvent

use of jakarta.servlet.ServletContextEvent in project spring-framework by spring-projects.

the class Spr8510Tests method genericWAC.

/**
 * 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()));
}
Also used : ClassPathBeanDefinitionScanner(org.springframework.context.annotation.ClassPathBeanDefinitionScanner) ContextLoaderListener(org.springframework.web.context.ContextLoaderListener) ServletContextEvent(jakarta.servlet.ServletContextEvent) MockServletContext(org.springframework.web.testfixture.servlet.MockServletContext) Test(org.junit.jupiter.api.Test)

Aggregations

ServletContextEvent (jakarta.servlet.ServletContextEvent)28 Test (org.junit.jupiter.api.Test)25 MockServletContext (org.springframework.web.testfixture.servlet.MockServletContext)21 ServletContextListener (jakarta.servlet.ServletContextListener)10 XmlWebApplicationContext (org.springframework.web.context.support.XmlWebApplicationContext)8 SimpleWebApplicationContext (org.springframework.web.servlet.SimpleWebApplicationContext)8 TestBean (org.springframework.beans.testfixture.beans.TestBean)6 ContextLoaderListener (org.springframework.web.context.ContextLoaderListener)6 ServletContext (jakarta.servlet.ServletContext)3 SecurityConstraint (org.apache.tomcat.util.descriptor.web.SecurityConstraint)2 ServletContextAttributeListener (jakarta.servlet.ServletContextAttributeListener)1 Dynamic (jakarta.servlet.ServletRegistration.Dynamic)1 ServletRequestAttributeListener (jakarta.servlet.ServletRequestAttributeListener)1 ServletRequestListener (jakarta.servlet.ServletRequestListener)1 HttpSessionAttributeListener (jakarta.servlet.http.HttpSessionAttributeListener)1 HttpSessionIdListener (jakarta.servlet.http.HttpSessionIdListener)1 HttpSessionListener (jakarta.servlet.http.HttpSessionListener)1 IOException (java.io.IOException)1 Method (java.lang.reflect.Method)1 InetAddress (java.net.InetAddress)1