Search in sources :

Example 1 with ServletContextListener

use of javax.servlet.ServletContextListener 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(javax.servlet.ServletContextListener) ServletContextEvent(javax.servlet.ServletContextEvent) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint)

Example 2 with ServletContextListener

use of javax.servlet.ServletContextListener 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
    ArrayList<Object> eventListeners = new ArrayList<>();
    ArrayList<Object> lifecycleListeners = new ArrayList<>();
    for (int i = 0; i < results.length; i++) {
        if ((results[i] instanceof ServletContextAttributeListener) || (results[i] instanceof ServletRequestAttributeListener) || (results[i] instanceof ServletRequestListener) || (results[i] instanceof HttpSessionIdListener) || (results[i] instanceof HttpSessionAttributeListener)) {
            eventListeners.add(results[i]);
        }
        if ((results[i] instanceof ServletContextListener) || (results[i] instanceof HttpSessionListener)) {
            lifecycleListeners.add(results[i]);
        }
    }
    // list.
    for (Object eventListener : getApplicationEventListeners()) {
        eventListeners.add(eventListener);
    }
    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 (int i = 0; i < instances.length; i++) {
        if (!(instances[i] instanceof ServletContextListener))
            continue;
        ServletContextListener listener = (ServletContextListener) instances[i];
        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", instances[i].getClass().getName()), t);
            ok = false;
        }
    }
    return (ok);
}
Also used : ServletContextAttributeListener(javax.servlet.ServletContextAttributeListener) ServletRequestAttributeListener(javax.servlet.ServletRequestAttributeListener) HttpSessionListener(javax.servlet.http.HttpSessionListener) ServletContextListener(javax.servlet.ServletContextListener) ServletRequestListener(javax.servlet.ServletRequestListener) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint) HttpSessionAttributeListener(javax.servlet.http.HttpSessionAttributeListener) HttpSessionIdListener(javax.servlet.http.HttpSessionIdListener) ServletContextEvent(javax.servlet.ServletContextEvent)

Example 3 with ServletContextListener

use of javax.servlet.ServletContextListener in project dropwizard by dropwizard.

the class ServletEnvironmentTest method addsServletListeners.

@Test
public void addsServletListeners() throws Exception {
    final ServletContextListener listener = mock(ServletContextListener.class);
    environment.addServletListeners(listener);
    verify(handler).addEventListener(listener);
}
Also used : ServletContextListener(javax.servlet.ServletContextListener) Test(org.junit.Test)

Example 4 with ServletContextListener

use of javax.servlet.ServletContextListener in project jetty.project by eclipse.

the class ContextHandler method stopContext.

/* ------------------------------------------------------------ */
protected void stopContext() throws Exception {
    //stop all the handler hierarchy
    super.doStop();
    //Call the context listeners
    ServletContextEvent event = new ServletContextEvent(_scontext);
    Collections.reverse(_destroySerletContextListeners);
    MultiException ex = new MultiException();
    for (ServletContextListener listener : _destroySerletContextListeners) {
        try {
            callContextDestroyed(listener, event);
        } catch (Exception x) {
            ex.add(x);
        }
    }
    ex.ifExceptionThrow();
}
Also used : ServletContextListener(javax.servlet.ServletContextListener) MultiException(org.eclipse.jetty.util.MultiException) ServletContextEvent(javax.servlet.ServletContextEvent) ServletException(javax.servlet.ServletException) MultiException(org.eclipse.jetty.util.MultiException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException)

Example 5 with ServletContextListener

use of javax.servlet.ServletContextListener in project jetty.project by eclipse.

the class TestJNDI method testThreadContextClassloaderAndCurrentContext.

@Test
public void testThreadContextClassloaderAndCurrentContext() throws Exception {
    //create a jetty context, and start it so that its classloader it created
    //and it is the current context
    ClassLoader currentLoader = Thread.currentThread().getContextClassLoader();
    ContextHandler ch = new ContextHandler();
    URLClassLoader chLoader = new URLClassLoader(new URL[0], currentLoader);
    ch.setClassLoader(chLoader);
    Server server = new Server();
    HandlerList hl = new HandlerList();
    server.setHandler(hl);
    hl.addHandler(ch);
    //Create another one
    ContextHandler ch2 = new ContextHandler();
    URLClassLoader ch2Loader = new URLClassLoader(new URL[0], currentLoader);
    ch2.setClassLoader(ch2Loader);
    hl.addHandler(ch2);
    try {
        ch.setContextPath("/ch");
        ch.addEventListener(new ServletContextListener() {

            private Context comp;

            private Object testObj = new Object();

            public void contextInitialized(ServletContextEvent sce) {
                try {
                    InitialContext initCtx = new InitialContext();
                    Context java = (Context) initCtx.lookup("java:");
                    assertNotNull(java);
                    comp = (Context) initCtx.lookup("java:comp");
                    assertNotNull(comp);
                    Context env = ((Context) comp).createSubcontext("env");
                    assertNotNull(env);
                    env.bind("ch", testObj);
                } catch (Exception e) {
                    throw new IllegalStateException(e);
                }
            }

            public void contextDestroyed(ServletContextEvent sce) {
                try {
                    assertNotNull(comp);
                    assertEquals(testObj, comp.lookup("env/ch"));
                    comp.destroySubcontext("env");
                } catch (Exception e) {
                    throw new IllegalStateException(e);
                }
            }
        });
        //Starting the context makes it current and creates a classloader for it
        ch.start();
        ch2.setContextPath("/ch2");
        ch2.addEventListener(new ServletContextListener() {

            private Context comp;

            private Object testObj = new Object();

            public void contextInitialized(ServletContextEvent sce) {
                try {
                    InitialContext initCtx = new InitialContext();
                    comp = (Context) initCtx.lookup("java:comp");
                    assertNotNull(comp);
                    //another context's bindings should not be visible
                    Context env = ((Context) comp).createSubcontext("env");
                    try {
                        env.lookup("ch");
                        fail("java:comp/env visible from another context!");
                    } catch (NameNotFoundException e) {
                    //expected
                    }
                } catch (Exception e) {
                    throw new IllegalStateException(e);
                }
            }

            public void contextDestroyed(ServletContextEvent sce) {
                try {
                    assertNotNull(comp);
                    comp.destroySubcontext("env");
                } catch (Exception e) {
                    throw new IllegalStateException(e);
                }
            }
        });
        //make the new context the current one
        ch2.start();
    } finally {
        ch.stop();
        ch2.stop();
        Thread.currentThread().setContextClassLoader(currentLoader);
    }
}
Also used : HandlerList(org.eclipse.jetty.server.handler.HandlerList) Context(javax.naming.Context) InitialContext(javax.naming.InitialContext) NamingContext(org.eclipse.jetty.jndi.NamingContext) Server(org.eclipse.jetty.server.Server) ServletContextListener(javax.servlet.ServletContextListener) NameNotFoundException(javax.naming.NameNotFoundException) InitialContext(javax.naming.InitialContext) NamingException(javax.naming.NamingException) NameNotFoundException(javax.naming.NameNotFoundException) NameAlreadyBoundException(javax.naming.NameAlreadyBoundException) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) URLClassLoader(java.net.URLClassLoader) URLClassLoader(java.net.URLClassLoader) ServletContextEvent(javax.servlet.ServletContextEvent) Test(org.junit.Test)

Aggregations

ServletContextListener (javax.servlet.ServletContextListener)21 ServletContextEvent (javax.servlet.ServletContextEvent)19 Test (org.junit.Test)11 MockServletContext (org.springframework.mock.web.test.MockServletContext)6 IOException (java.io.IOException)5 ArrayList (java.util.ArrayList)4 ServletContext (javax.servlet.ServletContext)3 HandlerWrapper (io.undertow.server.HandlerWrapper)2 HttpHandler (io.undertow.server.HttpHandler)2 Servlet (javax.servlet.Servlet)2 ServletException (javax.servlet.ServletException)2 SecurityConstraint (org.apache.tomcat.util.descriptor.web.SecurityConstraint)2 BeanDefinitionStoreException (org.springframework.beans.factory.BeanDefinitionStoreException)2 PathTemplateHandler (io.undertow.server.handlers.PathTemplateHandler)1 PredicatedHandler (io.undertow.server.handlers.builder.PredicatedHandler)1 CachingResourceManager (io.undertow.server.handlers.resource.CachingResourceManager)1 FileResourceManager (io.undertow.server.handlers.resource.FileResourceManager)1 ResourceManager (io.undertow.server.handlers.resource.ResourceManager)1 ServerSentEventConnectionCallback (io.undertow.server.handlers.sse.ServerSentEventConnectionCallback)1 ServerSentEventHandler (io.undertow.server.handlers.sse.ServerSentEventHandler)1