Example usage for javax.servlet ServletContextEvent ServletContextEvent

List of usage examples for javax.servlet ServletContextEvent ServletContextEvent

Introduction

In this page you can find the example usage for javax.servlet ServletContextEvent ServletContextEvent.

Prototype

public ServletContextEvent(ServletContext source) 

Source Link

Document

Construct a ServletContextEvent from the given context.

Usage

From source file:net.lightbody.bmp.proxy.jetty.jetty.servlet.WebApplicationContext.java

/** Start the Web Application.
 * @exception IOException //  w  w  w .  j  ava 2s .  co m
 */
protected void doStart() throws Exception {
    if (isStarted())
        return;

    // save context classloader
    Thread thread = Thread.currentThread();
    ClassLoader lastContextLoader = thread.getContextClassLoader();

    MultiException mex = null;
    try {
        // Find the webapp
        resolveWebApp();

        // Get the handler
        getServletHandler();

        _configurations = loadConfigurations();

        // initialize the classloader            
        configureClassPath();
        initClassLoader(true);
        thread.setContextClassLoader(getClassLoader());
        initialize();

        // Do the default configuration
        configureDefaults();

        // Set classpath for Jasper.
        Map.Entry entry = _webAppHandler.getHolderEntry("test.jsp");
        if (entry != null) {
            ServletHolder jspHolder = (ServletHolder) entry.getValue();
            if (jspHolder != null && jspHolder.getInitParameter("classpath") == null) {
                String fileClassPath = getFileClassPath();
                jspHolder.setInitParameter("classpath", fileClassPath);
                if (log.isDebugEnabled())
                    log.debug("Set classpath=" + fileClassPath + " for " + jspHolder);
            }
        }

        // configure webapp
        configureWebApp();

        // If we have servlets, don't init them yet
        _webAppHandler.setAutoInitializeServlets(false);

        // Start handlers
        super.doStart();

        mex = new MultiException();
        // Context listeners
        if (_contextListeners != null && _webAppHandler != null) {
            ServletContextEvent event = new ServletContextEvent(getServletContext());
            for (int i = 0; i < LazyList.size(_contextListeners); i++) {
                try {
                    ((ServletContextListener) LazyList.get(_contextListeners, i)).contextInitialized(event);
                } catch (Exception ex) {
                    mex.add(ex);
                }
            }
        }

        // OK to Initialize servlets now
        if (_webAppHandler != null && _webAppHandler.isStarted()) {
            try {
                _webAppHandler.initializeServlets();
            } catch (Exception ex) {
                mex.add(ex);
            }
        }
    } catch (Exception e) {
        log.warn("Configuration error on " + _war, e);
        throw e;
    } finally {
        thread.setContextClassLoader(lastContextLoader);
    }

    if (mex != null)
        mex.ifExceptionThrow();
}

From source file:net.lightbody.bmp.proxy.jetty.jetty.servlet.WebApplicationContext.java

/** Stop the web application.
 * Handlers for resource, servlet, filter and security are removed
 * as they are recreated and configured by any subsequent call to start().
 * @exception InterruptedException /*from www .  j a  v  a  2 s  . c  om*/
 */
protected void doStop() throws Exception {
    MultiException mex = new MultiException();

    Thread thread = Thread.currentThread();
    ClassLoader lastContextLoader = thread.getContextClassLoader();

    try {
        // Context listeners
        if (_contextListeners != null) {
            if (_webAppHandler != null) {
                ServletContextEvent event = new ServletContextEvent(getServletContext());

                for (int i = LazyList.size(_contextListeners); i-- > 0;) {
                    try {
                        ((ServletContextListener) LazyList.get(_contextListeners, i)).contextDestroyed(event);
                    } catch (Exception e) {
                        mex.add(e);
                    }
                }
            }
        }
        _contextListeners = null;

        // Stop the context
        try {
            super.doStop();
        } catch (Exception e) {
            mex.add(e);
        }

        // clean up
        clearSecurityConstraints();

        if (_webAppHandler != null)
            removeHandler(_webAppHandler);
        _webAppHandler = null;

        if (_errorPages != null)
            _errorPages.clear();
        _errorPages = null;

        _webApp = null;
        _webInf = null;

        _configurations = null;

    } finally {
        thread.setContextClassLoader(lastContextLoader);
    }

    if (mex != null)
        mex.ifExceptionThrow();
}

From source file:org.ireland.jnetty.webapp.WebApp.java

/**
 * Adds the listener object.//from   w  ww.ja v  a  2 s.  c om
 */
private void addListenerObject(Object listenerObj, boolean start) {

    // ServletContextListener
    if (listenerObj instanceof ServletContextListener) {
        ServletContextListener scListener = (ServletContextListener) listenerObj;
        _contextListeners.add(scListener);

        // ? ServletContextEvent#contextInitialized 
        if (start) {
            ServletContextEvent event = new ServletContextEvent(this);

            try {
                scListener.contextInitialized(event);
            } catch (Exception e) {
                e.printStackTrace();
                log.debug(e.toString(), e);
            }
        }
    }

    // ServletContextAttributeListener
    if (listenerObj instanceof ServletContextAttributeListener)
        addAttributeListener((ServletContextAttributeListener) listenerObj);

    // ServletRequestListener
    if (listenerObj instanceof ServletRequestListener) {
        _requestListeners.add((ServletRequestListener) listenerObj);
    }

    // ServletRequestAttributeListener
    if (listenerObj instanceof ServletRequestAttributeListener) {
        _requestAttributeListeners.add((ServletRequestAttributeListener) listenerObj);
    }

    // HttpSessionListener
    if (listenerObj instanceof HttpSessionListener)
        getSessionManager().addListener((HttpSessionListener) listenerObj);

    // HttpSessionListener
    if (listenerObj instanceof HttpSessionAttributeListener)
        getSessionManager().addAttributeListener((HttpSessionAttributeListener) listenerObj);

    // HttpSessionActivationListener
    if (listenerObj instanceof HttpSessionActivationListener)
        getSessionManager().addActivationListener((HttpSessionActivationListener) listenerObj);
}

From source file:org.ireland.jnetty.webapp.WebApp.java

/**
 * ?publish ContextInitialized Event /*from  w  w w  .ja  va 2 s  .  c o  m*/
 */
protected void publishContextInitializedEvent() {
    log.debug("publish ContextInitialized Event");

    // ?ServletContextListener#contextInitialized
    ServletContextEvent event = new ServletContextEvent(this);

    for (int i = 0; i < _contextListeners.size(); i++) {
        ServletContextListener listener = _contextListeners.get(i);

        try {
            listener.contextInitialized(event);
        } catch (Exception e) {
            log.warn(e.toString(), e);
        }
    }
}

From source file:org.ireland.jnetty.webapp.WebApp.java

/**
 * Stops the webApp.//w w w .  j a  v  a 2 s  . co m
 */
public void stop() {

    long beginStop = System.currentTimeMillis();

    clearCache();

    ServletContextEvent event = new ServletContextEvent(this);

    SessionManager sessionManager = _sessionManager;
    _sessionManager = null;

    if (sessionManager != null) {
        sessionManager.close();
    }

    if (_servletManager != null)
        _servletManager.destroy();
    if (_filterManager != null)
        _filterManager.destroy();

    // server/10g8 -- webApp listeners after session

    // ? ServletContextListener#contextDestroyed
    publishContextDestroyedEvent(event);

}

From source file:org.apache.catalina.core.StandardContext.java

/**
 * 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.
 *//*from  w  w w  .  ja v  a2s .c om*/
public boolean listenerStart() {

    if (log.isDebugEnabled())
        log.debug("Configuring application event listeners");

    // Instantiate the required listeners
    ClassLoader loader = getLoader().getClassLoader();
    String listeners[] = findApplicationListeners();
    Object results[] = new Object[listeners.length];
    boolean ok = true;
    for (int i = 0; i < results.length; i++) {
        if (log.isDebugEnabled())
            log.debug(" Configuring event listener class '" + listeners[i] + "'");
        try {
            Class clazz = loader.loadClass(listeners[i]);
            results[i] = clazz.newInstance();
        } catch (Throwable t) {
            getServletContext().log(sm.getString("standardContext.applicationListener", listeners[i]), t);
            ok = false;
        }
    }
    if (!ok) {
        log.error(sm.getString("standardContext.applicationSkipped"));
        return (false);
    }

    // Sort listeners in two arrays
    ArrayList eventListeners = new ArrayList();
    ArrayList 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 HttpSessionAttributeListener)) {
            eventListeners.add(results[i]);
        }
        if ((results[i] instanceof ServletContextListener) || (results[i] instanceof HttpSessionListener)) {
            lifecycleListeners.add(results[i]);
        }
    }

    setApplicationEventListeners(eventListeners.toArray());
    setApplicationLifecycleListeners(lifecycleListeners.toArray());

    // Send application start events

    if (log.isDebugEnabled())
        log.debug("Sending application start events");

    Object instances[] = getApplicationLifecycleListeners();
    if (instances == null)
        return (ok);
    ServletContextEvent event = new ServletContextEvent(getServletContext());
    for (int i = 0; i < instances.length; i++) {
        if (instances[i] == null)
            continue;
        if (!(instances[i] instanceof ServletContextListener))
            continue;
        ServletContextListener listener = (ServletContextListener) instances[i];
        try {
            fireContainerEvent("beforeContextInitialized", listener);
            listener.contextInitialized(event);
            fireContainerEvent("afterContextInitialized", listener);
        } catch (Throwable t) {
            fireContainerEvent("afterContextInitialized", listener);
            getServletContext()
                    .log(sm.getString("standardContext.listenerStart", instances[i].getClass().getName()), t);
            ok = false;
        }
    }
    return (ok);

}

From source file:org.apache.catalina.core.StandardContext.java

/**
 * Send an application stop event to all interested listeners.
 * Return <code>true</code> if all events were sent successfully,
 * or <code>false</code> otherwise.
 *///  w ww  . ja v  a2  s.co m
public boolean listenerStop() {

    if (log.isDebugEnabled())
        log.debug("Sending application stop events");

    boolean ok = true;
    Object listeners[] = getApplicationLifecycleListeners();
    if (listeners == null)
        return (ok);
    ServletContextEvent event = new ServletContextEvent(getServletContext());
    for (int i = 0; i < listeners.length; i++) {
        int j = (listeners.length - 1) - i;
        if (listeners[j] == null)
            continue;
        if (!(listeners[j] instanceof ServletContextListener))
            continue;
        ServletContextListener listener = (ServletContextListener) listeners[j];
        try {
            fireContainerEvent("beforeContextDestroyed", listener);
            listener.contextDestroyed(event);
            fireContainerEvent("beforeContextDestroyed", listener);
        } catch (Throwable t) {
            fireContainerEvent("beforeContextDestroyed", listener);
            getServletContext()
                    .log(sm.getString("standardContext.listenerStop", listeners[j].getClass().getName()), t);
            ok = false;
        }
    }
    setApplicationEventListeners(null);
    setApplicationLifecycleListeners(null);
    return (ok);

}

From source file:org.geoserver.logging.LoggingStartupContextListenerTest.java

@Test
public void testLogLocationFromServletContext() throws Exception {
    File tmp = File.createTempFile("log", "tmp", new File("target"));
    tmp.delete();/*  ww w  . j  a  v  a 2  s . c om*/
    tmp.mkdirs();

    File logs = new File(tmp, "logs");
    assertTrue(logs.mkdirs());

    FileUtils.copyURLToFile(getClass().getResource("logging.xml"), new File(tmp, "logging.xml"));

    MockServletContext context = new MockServletContext();
    context.setInitParameter("GEOSERVER_DATA_DIR", tmp.getPath());
    context.setInitParameter("GEOSERVER_LOG_LOCATION", new File(tmp, "foo.log").getAbsolutePath());

    Logger logger = Logger.getRootLogger();
    assertNull("Expected geoserverlogfile to be null.  But was: " + logger.getAppender("geoserverlogfile"),
            logger.getAppender("geoserverlogfile"));

    String rel = System.getProperty(LoggingUtils.RELINQUISH_LOG4J_CONTROL);
    System.setProperty(LoggingUtils.RELINQUISH_LOG4J_CONTROL, "false");
    try {
        new LoggingStartupContextListener().contextInitialized(new ServletContextEvent(context));
    } finally {
        System.setProperty(LoggingUtils.RELINQUISH_LOG4J_CONTROL, "rel");
    }

    Appender appender = logger.getAppender("geoserverlogfile");
    assertNotNull(appender);
    assertTrue(appender instanceof FileAppender);

    assertEquals(new File(tmp, "foo.log").getCanonicalPath(), ((FileAppender) appender).getFile());
}

From source file:org.hdiv.AbstractHDIVTestCase.java

protected final void setUp() throws Exception {

    String[] files = { "/org/hdiv/config/hdiv-core-applicationContext.xml", "/org/hdiv/config/hdiv-config.xml",
            "/org/hdiv/config/hdiv-validations.xml", "/org/hdiv/config/applicationContext-test.xml",
            "/org/hdiv/config/applicationContext-extra.xml" };

    if (this.applicationContext == null) {
        this.applicationContext = new ClassPathXmlApplicationContext(files);
    }//from   w ww. j  a  v a  2 s. c  o m

    // Servlet API mock
    HttpServletRequest request = (MockHttpServletRequest) this.applicationContext.getBean("mockRequest");
    HttpSession httpSession = request.getSession();
    ServletContext servletContext = httpSession.getServletContext();
    HDIVUtil.setHttpServletRequest(request);

    // Put Spring context on ServletContext
    StaticWebApplicationContext webApplicationContext = new StaticWebApplicationContext();
    webApplicationContext.setServletContext(servletContext);
    webApplicationContext.setParent(this.applicationContext);
    servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
            webApplicationContext);

    // Initialize config
    this.config = (HDIVConfig) this.applicationContext.getBean("config");

    InitListener initListener = new InitListener();
    // Initialize ServletContext
    ServletContextEvent servletContextEvent = new ServletContextEvent(servletContext);
    initListener.contextInitialized(servletContextEvent);
    // Initialize HttpSession
    HttpSessionEvent httpSessionEvent = new HttpSessionEvent(httpSession);
    initListener.sessionCreated(httpSessionEvent);
    // Initialize request
    ServletRequestEvent requestEvent = new ServletRequestEvent(servletContext, request);
    initListener.requestInitialized(requestEvent);

    if (log.isDebugEnabled()) {
        log.debug("Hdiv test context initialized");
    }

    onSetUp();
}