Java 类javax.servlet.ServletContextListener 实例源码

项目:springboot-shiro-cas-mybatis    文件:CasLoggerContextInitializer.java   
/**
 * Prepares the logger context. Locates the context and
 * sets the configuration file.
 * @return the logger context
 */
private ServletContextListener prepareAndgetContextListener() {
    try {
        if (StringUtils.isNotBlank(this.loggerContextPackageName)) {
            final Collection<URL> set = ClasspathHelper.forPackage(this.loggerContextPackageName);
            final Reflections reflections = new Reflections(new ConfigurationBuilder().addUrls(set).setScanners(new SubTypesScanner()));
            final Set<Class<? extends ServletContextListener>> subTypesOf = reflections.getSubTypesOf(ServletContextListener.class);
            final ServletContextListener loggingContext = subTypesOf.iterator().next().newInstance();
            this.context.setInitParameter(this.logConfigurationField, this.logConfigurationFile.getURI().toString());
            return loggingContext;
        }
        return null;
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}
项目:lemon    文件:ProxyServletListener.java   
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);
    }
}
项目:lams    文件:ServletContextImpl.java   
@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));
}
项目:marathon-auth-plugin    文件:ServletContextHandler.java   
@Override
public void callContextInitialized(ServletContextListener l, ServletContextEvent e)
{
    try
    {
        //toggle state of the dynamic API so that the listener cannot use it
        if(isProgrammaticListener(l))
            this.getServletContext().setEnabled(false);

        super.callContextInitialized(l, e);
    }
    finally
    {
        //untoggle the state of the dynamic API
        this.getServletContext().setEnabled(true);
    }
}
项目:spring4-understanding    文件:ContextLoaderTests.java   
@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));
}
项目:spring4-understanding    文件:ContextLoaderTests.java   
@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);
    }
}
项目:puzzle    文件:PluginServletManager.java   
private void newListenerInstance(){
    if(listenerMetadatas.isEmpty()){
        return;
    }
    ClassLoader classloader= pluginContext.getClassLoader();
    try {
        for(String lisenterClass: listenerMetadatas){
            Class<?> clazz = classloader.loadClass(lisenterClass);
            EventListener listener = (EventListener)clazz.newInstance();
            injectComponentAware(listener);
            if(listener instanceof ServletContextListener){
                ((ServletContextListener)listener).contextInitialized(new ServletContextEvent(getServletContext()));
            }
            listenerIntances.add(listener);
        }
        PluginWebInstanceRepository.registerListeners(listenerIntances);
        logger.info("Complete to new and register listener instance");

    } catch (Exception e) {
        throw new PuzzleException("New Plugin ["+pluginContext.getName()+"] Listener instance failure",e);
    } 
}
项目:adeptj-modules    文件:ShiroActivator.java   
/**
 * Initializes the Shiro Security Framework.
 */
@Override
public void start(BundleContext context) throws Exception {
    cacheProviderTracker = new CacheProviderTracker(context, CacheProvider.class);
    cacheProviderTracker.open();
    // Register the Shiro EnvironmentLoaderListener first.
    Dictionary<String, Object> shiroListenerProps = new Hashtable<>();
    shiroListenerProps.put(Constants.SERVICE_VENDOR, "AdeptJ");
    shiroListenerProps.put("osgi.http.whiteboard.listener", "true");
    servRegShiroListener = context.registerService(ServletContextListener.class, new ExtEnvironmentLoaderListener(),
            shiroListenerProps);
    // Now Register the ShiroFilter.
    Dictionary<String, Object> shiroFilterProps = new Hashtable<>();
    shiroFilterProps.put(Constants.SERVICE_VENDOR, "AdeptJ");
    shiroFilterProps.put("osgi.http.whiteboard.filter.name", "Shiro Filter");
    shiroFilterProps.put("osgi.http.whiteboard.filter.pattern", "/*");
    shiroFilterProps.put("osgi.http.whiteboard.filter.asyncSupported", "true");
    shiroFilterProps.put("osgi.http.whiteboard.filter.dispatcher",
            new String[] { "REQUEST", "INCLUDE", "FORWARD", "ASYNC", "ERROR" });
    servRegShiroFilter = context.registerService(Filter.class, new ShiroFilter(), shiroFilterProps);
}
项目:cas4.1.9    文件:CasLoggerContextInitializer.java   
/**
 * Prepares the logger context. Locates the context and
 * sets the configuration file.
 * @return the logger context
 */
private ServletContextListener prepareAndgetContextListener() {
    try {
        if (StringUtils.isNotBlank(this.loggerContextPackageName)) {
            final Collection<URL> set = ClasspathHelper.forPackage(this.loggerContextPackageName);
            final Reflections reflections = new Reflections(new ConfigurationBuilder().addUrls(set).setScanners(new SubTypesScanner()));
            final Set<Class<? extends ServletContextListener>> subTypesOf = reflections.getSubTypesOf(ServletContextListener.class);
            final ServletContextListener loggingContext = subTypesOf.iterator().next().newInstance();
            this.context.setInitParameter(this.logConfigurationField, this.logConfigurationFile.getURI().toString());
            return loggingContext;
        }
        return null;
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}
项目:micro-server    文件:BootFrontEndApplicationConfigurator.java   
@Override
public void onStartup(ServletContext webappContext) throws ServletException {

    ModuleDataExtractor extractor = new ModuleDataExtractor(module);
    environment.assureModule(module);
    String fullRestResource = "/" + module.getContext() + "/*";

    ServerData serverData = new ServerData(environment.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);

}
项目:micro-server    文件:Module.java   
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)
                                                       .flatMapI(Plugin::servletContextListeners)
                                                       .map(fn -> fn.apply(data))
                                                       .to().listX();

    return listeners.plusAll(list);
}
项目:micro-server    文件:ServletContextListenerConfigurer.java   
public void addListeners(ServletContext webappContext) {

    serverData.getRootContext()
            .getBeansOfType(ServletContextListener.class)
            .values()

            .stream()

            .peek(this::logListener)
            .forEach(listener -> webappContext.addListener(listener));
    listenerData.forEach(it -> webappContext.addListener(it));

    serverData.getRootContext()
            .getBeansOfType(ServletRequestListener.class)
            .values()
            .stream()
            .peek(this::logListener)
            .forEach(listener -> webappContext.addListener(listener));
    listenerRequestData.forEach(it -> webappContext.addListener(it));

}
项目:asity    文件:ServletServerHttpExchangeTest.java   
@Override
protected void startServer(int port, final Action<ServerHttpExchange> requestAction) throws
  Exception {
  server = new Server();
  ServerConnector connector = new ServerConnector(server);
  connector.setPort(port);
  server.addConnector(connector);
  ServletContextHandler handler = new ServletContextHandler();
  handler.addEventListener(new ServletContextListener() {
    @Override
    public void contextInitialized(ServletContextEvent event) {
      ServletContext context = event.getServletContext();
      Servlet servlet = new AsityServlet().onhttp(requestAction);
      ServletRegistration.Dynamic reg = context.addServlet(AsityServlet.class.getName(), servlet);
      reg.setAsyncSupported(true);
      reg.addMapping(TEST_URI);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
    }
  });
  server.setHandler(handler);
  server.start();
}
项目:resteasy-spring-boot    文件:ResteasyAutoConfigurationTest.java   
private void testServletContextListener(ServletContext servletContext) throws Exception {
    ResteasyAutoConfiguration resteasyAutoConfiguration = new ResteasyAutoConfiguration();
    BeanFactoryPostProcessor beanFactoryPostProcessor = ResteasyAutoConfiguration.springBeanProcessor();
    ServletContextListener servletContextListener = resteasyAutoConfiguration.resteasyBootstrapListener(beanFactoryPostProcessor);
    Assert.assertNotNull(servletContextListener);

    ServletContextEvent sce = new ServletContextEvent(servletContext);
    servletContextListener.contextInitialized(sce);

    ResteasyProviderFactory servletContextProviderFactory = (ResteasyProviderFactory) servletContext.getAttribute(ResteasyProviderFactory.class.getName());
    Dispatcher servletContextDispatcher = (Dispatcher) servletContext.getAttribute(Dispatcher.class.getName());
    Registry servletContextRegistry = (Registry) servletContext.getAttribute(Registry.class.getName());

    Assert.assertNotNull(servletContextProviderFactory);
    Assert.assertNotNull(servletContextDispatcher);
    Assert.assertNotNull(servletContextRegistry);

    // Exercising fully cobertura branch coverage
    servletContextListener.contextDestroyed(sce);
    ServletContextListener servletContextListener2 = resteasyAutoConfiguration.resteasyBootstrapListener(beanFactoryPostProcessor);
    servletContextListener2.contextDestroyed(sce);
}
项目:osgi.ee    文件:OurServletContext.java   
/**
 * Init method called by the main servlet when the wrapping servlet is initialized. This means that the context is
 * taken into service by the system.
 *
 * @param parent The parent servlet context. Just for some delegation actions
 */
void init(ServletContext parent) {
    // Set up the tracking of event listeners.
    BundleContext bc = getOwner().getBundleContext();
    delegate = parent;
    Collection<Class<? extends EventListener>> toTrack = Arrays.asList(HttpSessionListener.class,
            ServletRequestListener.class, HttpSessionAttributeListener.class, ServletRequestAttributeListener.class,
            ServletContextListener.class);
    Collection<String> objectFilters = toTrack.stream().
            map((c) -> "(" + Constants.OBJECTCLASS + "=" + c.getName() + ")").collect(Collectors.toList());
    String filterString = "|" + String.join("", objectFilters);
    eventListenerTracker = startTracking(filterString,
            new Tracker<EventListener, EventListener>(bc, getContextPath(), (e) -> e, (e) -> { /* No destruct */}));
    // Initialize the servlets.
    ServletContextEvent event = new ServletContextEvent(this);
    call(ServletContextListener.class, (l) -> l.contextInitialized(event));
    servlets.values().forEach((s) -> init(s));
    // And the filters.
    filters.values().forEach((f) -> init(f));
    // Set up the tracking of servlets and filters.
    servletTracker = startTracking(Constants.OBJECTCLASS + "=" + Servlet.class.getName(),
            new Tracker<Servlet, String>(bc, getContextPath(), this::addServlet, this::removeServlet));
    filterTracker = startTracking(Constants.OBJECTCLASS + "=" + Filter.class.getName(),
            new Tracker<Filter, String>(bc, getContextPath(), this::addFilter, this::removeFilter));
}
项目:class-guard    文件:ContextLoaderTests.java   
@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));
}
项目:class-guard    文件:ContextLoaderTests.java   
@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);
    }
}
项目:vibe-java-platform    文件:AtmosphereServerHttpExchangeTest.java   
@Override
protected void startServer() throws Exception {
    server = new Server();
    ServerConnector connector = new ServerConnector(server);
    connector.setPort(port);
    server.addConnector(connector);
    ServletContextHandler handler = new ServletContextHandler();
    handler.addEventListener(new ServletContextListener() {
        @Override
        public void contextInitialized(ServletContextEvent event) {
            ServletContext context = event.getServletContext();
            Servlet servlet = new VibeAtmosphereServlet().onhttp(performer.serverAction());
            ServletRegistration.Dynamic reg = context.addServlet(VibeAtmosphereServlet.class.getName(), servlet);
            reg.setAsyncSupported(true);
            reg.setInitParameter(ApplicationConfig.DISABLE_ATMOSPHEREINTERCEPTOR, Boolean.TRUE.toString());
            reg.addMapping("/test");
        }

        @Override
        public void contextDestroyed(ServletContextEvent sce) {}
    });
    server.setHandler(handler);
    server.start();
}
项目:vibe-java-platform    文件:AtmosphereServerWebSocketTest.java   
@Override
protected void startServer() throws Exception {
    server = new Server();
    ServerConnector connector = new ServerConnector(server);
    connector.setPort(port);
    server.addConnector(connector);
    ServletContextHandler handler = new ServletContextHandler();
    handler.addEventListener(new ServletContextListener() {
        @Override
        public void contextInitialized(ServletContextEvent event) {
            ServletContext context = event.getServletContext();
            Servlet servlet = new VibeAtmosphereServlet().onwebsocket(performer.serverAction());
            ServletRegistration.Dynamic reg = context.addServlet(VibeAtmosphereServlet.class.getName(), servlet);
            reg.setAsyncSupported(true);
            reg.setInitParameter(ApplicationConfig.DISABLE_ATMOSPHEREINTERCEPTOR, Boolean.TRUE.toString());
            reg.addMapping("/test");
        }

        @Override
        public void contextDestroyed(ServletContextEvent sce) {}
    });
    server.setHandler(handler);
    server.start();
}
项目:vibe-java-platform    文件:ServletServerHttpExchangeTest.java   
@Override
protected void startServer() throws Exception {
    server = new Server();
    ServerConnector connector = new ServerConnector(server);
    connector.setPort(port);
    server.addConnector(connector);
    ServletContextHandler handler = new ServletContextHandler();
    handler.addEventListener(new ServletContextListener() {
        @Override
        public void contextInitialized(ServletContextEvent event) {
            ServletContext context = event.getServletContext();
            Servlet servlet = new VibeServlet().onhttp(performer.serverAction());
            ServletRegistration.Dynamic reg = context.addServlet(VibeServlet.class.getName(), servlet);
            reg.setAsyncSupported(true);
            reg.addMapping("/test");
        }

        @Override
        public void contextDestroyed(ServletContextEvent sce) {}
    });
    server.setHandler(handler);
    server.start();
}
项目:tomee    文件:WebContext.java   
private static boolean isWeb(final Class<?> beanClass) {
    if (Servlet.class.isAssignableFrom(beanClass)
        || Filter.class.isAssignableFrom(beanClass)) {
        return true;
    }
    if (EventListener.class.isAssignableFrom(beanClass)) {
        return HttpSessionAttributeListener.class.isAssignableFrom(beanClass)
               || ServletContextListener.class.isAssignableFrom(beanClass)
               || ServletRequestListener.class.isAssignableFrom(beanClass)
               || ServletContextAttributeListener.class.isAssignableFrom(beanClass)
               || HttpSessionListener.class.isAssignableFrom(beanClass)
               || HttpSessionBindingListener.class.isAssignableFrom(beanClass)
               || HttpSessionActivationListener.class.isAssignableFrom(beanClass)
               || HttpSessionIdListener.class.isAssignableFrom(beanClass)
               || ServletRequestAttributeListener.class.isAssignableFrom(beanClass);
    }

    return false;
}
项目:tomcat7    文件:ApplicationContext.java   
@Override
public <T extends EventListener> void addListener(T t) {
    if (!context.getState().equals(LifecycleState.STARTING_PREP)) {
        throw new IllegalStateException(
                sm.getString("applicationContext.addListener.ise",
                        getContextPath()));
    }

    boolean match = false;
    if (t instanceof ServletContextAttributeListener ||
            t instanceof ServletRequestListener ||
            t instanceof ServletRequestAttributeListener ||
            t instanceof HttpSessionAttributeListener) {
        context.addApplicationEventListener(t);
        match = true;
    }

    if (t instanceof HttpSessionListener
            || (t instanceof ServletContextListener &&
                    newServletContextListenerAllowed)) {
        // Add listener directly to the list of instances rather than to
        // the list of class names.
        context.addApplicationLifecycleListener(t);
        match = true;
    }

    if (match) return;

    if (t instanceof ServletContextListener) {
        throw new IllegalArgumentException(sm.getString(
                "applicationContext.addListener.iae.sclNotAllowed",
                t.getClass().getName()));
    } else {
        throw new IllegalArgumentException(sm.getString(
                "applicationContext.addListener.iae.wrongType",
                t.getClass().getName()));
    }
}
项目:lemon    文件:ProxyServletListener.java   
public void contextDestroyed(ServletContextEvent sce) {
    if (ctx == null) {
        logger.warn("cannot find applicationContext");

        return;
    }

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

    for (ServletContextListener servletContextListener : servletContextListeners) {
        servletContextListener.contextDestroyed(sce);
    }
}
项目:lams    文件:ServletContextImpl.java   
@Override
public <T extends EventListener> void addListener(final T t) {
    ensureNotInitialized();
    ensureNotProgramaticListener();
    if (ApplicationListeners.listenerState() != NO_LISTENER &&
            ServletContextListener.class.isAssignableFrom(t.getClass())) {
        throw UndertowServletMessages.MESSAGES.cannotAddServletContextListener();
    }
    ListenerInfo listener = new ListenerInfo(t.getClass(), new ImmediateInstanceFactory<EventListener>(t));
    deploymentInfo.addListener(listener);
    deployment.getApplicationListeners().addListener(new ManagedListener(listener, true));
}
项目:lams    文件:ApplicationListeners.java   
public void contextInitialized() {
    //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();
        }
    }
}
项目:lams    文件:ApplicationListeners.java   
public void contextDestroyed() {
    final ServletContextEvent event = new ServletContextEvent(servletContext);
    for (int i = servletContextListeners.length - 1; i >= 0; --i) {
        ManagedListener listener = servletContextListeners[i];
        try {
            this.<ServletContextListener>get(listener).contextDestroyed(event);
        } catch (Exception e) {
            UndertowServletLogger.REQUEST_LOGGER.errorInvokingListener("contextDestroyed", listener.getListenerInfo().getListenerClass(), e);
        }
    }
}
项目:jerrydog    文件: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.
 */
public boolean listenerStop() {

    if (debug >= 1)
        log("Sending application stop events");

    boolean ok = true;
    Object listeners[] = getApplicationListeners();
    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);
            log(sm.getString("standardContext.listenerStop",
                             listeners[j].getClass().getName()), t);
            ok = false;
        }
    }
    setApplicationListeners(null);
    return (ok);

}
项目:lazycat    文件:ApplicationContext.java   
@Override
public <T extends EventListener> void addListener(T t) {
    if (!context.getState().equals(LifecycleState.STARTING_PREP)) {
        throw new IllegalStateException(sm.getString("applicationContext.addListener.ise", getContextPath()));
    }

    boolean match = false;
    if (t instanceof ServletContextAttributeListener || t instanceof ServletRequestListener
            || t instanceof ServletRequestAttributeListener || t instanceof HttpSessionAttributeListener) {
        context.addApplicationEventListener(t);
        match = true;
    }

    if (t instanceof HttpSessionListener
            || (t instanceof ServletContextListener && newServletContextListenerAllowed)) {
        // Add listener directly to the list of instances rather than to
        // the list of class names.
        context.addApplicationLifecycleListener(t);
        match = true;
    }

    if (match)
        return;

    if (t instanceof ServletContextListener) {
        throw new IllegalArgumentException(
                sm.getString("applicationContext.addListener.iae.sclNotAllowed", t.getClass().getName()));
    } else {
        throw new IllegalArgumentException(
                sm.getString("applicationContext.addListener.iae.wrongType", t.getClass().getName()));
    }
}
项目:Mastering-Mesos    文件:JettyServerModule.java   
@Provides
@Singleton
ServletContextListener provideServletContextListener(Injector parentInjector) {
  return makeServletContextListener(
      parentInjector,
      Modules.combine(
          new ApiModule(),
          new H2ConsoleModule(),
          new HttpSecurityModule(),
          new ThriftModule()));
}
项目:Mastering-Mesos    文件:JettyServerModule.java   
@VisibleForTesting
static ServletContextListener makeServletContextListener(
    final Injector parentInjector,
    final Module childModule) {

  return new GuiceServletContextListener() {
    @Override
    protected Injector getInjector() {
      return parentInjector.createChildInjector(
          childModule,
          new JerseyServletModule() {
            @Override
            protected void configureServlets() {
              bind(HttpStatsFilter.class).in(Singleton.class);
              filter("*").through(HttpStatsFilter.class);

              bind(LeaderRedirectFilter.class).in(Singleton.class);
              filterRegex(allOf(LEADER_ENDPOINTS))
                  .through(LeaderRedirectFilter.class);

              bind(GuiceContainer.class).in(Singleton.class);
              filterRegex(allOf(ImmutableSet.copyOf(JAX_RS_ENDPOINTS.values())))
                  .through(GuiceContainer.class, GUICE_CONTAINER_PARAMS);

              filterRegex("/assets/scheduler(?:/.*)?").through(LeaderRedirectFilter.class);

              serve("/assets", "/assets/*")
                  .with(new DefaultServlet(), ImmutableMap.of(
                      "resourceBase", STATIC_ASSETS_ROOT,
                      "dirAllowed", "false"));

              for (Class<?> jaxRsHandler : JAX_RS_ENDPOINTS.keySet()) {
                bind(jaxRsHandler);
              }
            }
          });
    }
  };
}
项目:Mastering-Mesos    文件:JettyServerModule.java   
@Inject
HttpServerLauncher(
    ServletContextListener servletContextListener,
    Optional<String> advertisedHostOverride) {

  this.servletContextListener = requireNonNull(servletContextListener);
  this.advertisedHostOverride = requireNonNull(advertisedHostOverride);
}
项目:spring4-understanding    文件:ContextLoaderTests.java   
@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());
}
项目:spring4-understanding    文件:ContextLoaderTests.java   
@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);
}
项目:spring4-understanding    文件:ContextLoaderTests.java   
@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);
    }
}
项目:spring4-understanding    文件:ContextLoaderTests.java   
@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"));
    }
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:ServletListenerRegistrationBeanTests.java   
@Test
public void startupWithDefaults() throws Exception {
    ServletListenerRegistrationBean<ServletContextListener> bean = new ServletListenerRegistrationBean<ServletContextListener>(
            this.listener);
    bean.onStartup(this.servletContext);
    verify(this.servletContext).addListener(this.listener);
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:ServletListenerRegistrationBeanTests.java   
@Test
public void disable() throws Exception {
    ServletListenerRegistrationBean<ServletContextListener> bean = new ServletListenerRegistrationBean<ServletContextListener>(
            this.listener);
    bean.setEnabled(false);
    bean.onStartup(this.servletContext);
    verify(this.servletContext, times(0))
            .addListener(any(ServletContextListener.class));
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:EmbeddedWebApplicationContextTests.java   
@Test
public void servletContextListenerBeans() throws Exception {
    addEmbeddedServletContainerFactoryBean();
    ServletContextListener initializer = mock(ServletContextListener.class);
    this.context.registerBeanDefinition("initializerBean",
            beanDefinition(initializer));
    this.context.refresh();
    ServletContext servletContext = getEmbeddedServletContainerFactory()
            .getServletContext();
    verify(servletContext).addListener(initializer);
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:EmbeddedServletContainerServletContextListenerTests.java   
private void servletContextListenerBeanIsCalled(Class<?> configuration) {
    AnnotationConfigEmbeddedWebApplicationContext context = new AnnotationConfigEmbeddedWebApplicationContext(
            ServletContextListenerBeanConfiguration.class, configuration);
    ServletContextListener servletContextListener = context
            .getBean("servletContextListener", ServletContextListener.class);
    verify(servletContextListener).contextInitialized(any(ServletContextEvent.class));
    context.close();
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:EmbeddedServletContainerServletContextListenerTests.java   
private void registeredServletContextListenerBeanIsCalled(Class<?> configuration) {
    AnnotationConfigEmbeddedWebApplicationContext context = new AnnotationConfigEmbeddedWebApplicationContext(
            ServletListenerRegistrationBeanConfiguration.class, configuration);
    ServletContextListener servletContextListener = (ServletContextListener) context
            .getBean("registration", ServletListenerRegistrationBean.class)
            .getListener();
    verify(servletContextListener).contextInitialized(any(ServletContextEvent.class));
    context.close();
}