Java Code Examples for javax.servlet.ServletContextEvent

The following examples show how to use javax.servlet.ServletContextEvent. These examples are extracted from open source projects. 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
@Override
   public void contextInitialized(ServletContextEvent event) {
       try {
       	// Birt must generate messages in here, because it has no struts like EMM
       	// Messages are then available via I18nString
       	DBMessagesResource dbMessagesResource = new DBMessagesResource();
   		dbMessagesResource.init();
   		
   		ServletContext servletContext = event.getServletContext();
   		if (ConfigService.getInstance().getBooleanValue(ConfigValue.IsLiveInstance)) {
   			createMessagesPropertiesFiles(servletContext);
   		}
	} catch (Exception e) {
		logger.error("MessagesPropertiesGeneratorContextListener init: " + e.getMessage(), e);
	}
}
 
Example 2
Source Project: java-technology-stack   Source File: ContextLoaderTests.java    License: 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 3
@Override
public void contextInitialized(ServletContextEvent event) {
	ServletContext servletContext = event.getServletContext();
	WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
	configService = webApplicationContext.getBean("ConfigService", ConfigService.class);
	
	
	if (servletContext.getAttribute(ExtensionConstants.EXTENSION_SYSTEM_APPLICATION_SCOPE_ATTRIBUTE) != null) {
		logger.fatal ("Extension system already initialized for the application context");
	} else {
		try {
			ExtensionSystemImpl extensionSystem = createExtensionSystem( servletContext);
			servletContext.setAttribute(ExtensionConstants.EXTENSION_SYSTEM_APPLICATION_SCOPE_ATTRIBUTE, extensionSystem);
			
			extensionSystem.startUp();
		} catch (Exception e) {
			logger.fatal("Error initializing extension system", e);				
		}
	}
}
 
Example 4
Source Project: java-technology-stack   Source File: Spr8510Tests.java    License: MIT License 6 votes vote down vote up
/**
 * 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");

	try {
		cll.contextInitialized(new ServletContextEvent(sc));
		fail("expected exception");
	}
	catch (Throwable t) {
		// assert that an attempt was made to load the correct XML
		assertTrue(t.getMessage(), t.getMessage().endsWith(
				"Could not open ServletContext resource [/from-init-param.xml]"));
	}
}
 
Example 5
Source Project: Tomcat8-Source-Read   Source File: TesterTldListener.java    License: MIT License 6 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent sce) {

    ServletContext sc = sce.getServletContext();
    servletContext = sc;

    // Try and use one of the Servlet 3.0 methods that should be blocked
    try {
        sc.getEffectiveMajorVersion();
        log.append("FAIL-01");
    } catch (UnsupportedOperationException uoe) {
        log.append("PASS-01");
    } catch (Exception e) {
        log.append("FAIL-02");
    }
}
 
Example 6
Source Project: quarkus-http   Source File: DeploymentManagerImpl.java    License: 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 7
Source Project: Tomcat8-Source-Read   Source File: TesterEchoServer.java    License: MIT License 6 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent sce) {
    super.contextInitialized(sce);
    ServerContainer sc =
            (ServerContainer) sce.getServletContext().getAttribute(
                    Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE);
    try {
        sc.addEndpoint(Async.class);
        sc.addEndpoint(Basic.class);
        sc.addEndpoint(BasicLimitLow.class);
        sc.addEndpoint(BasicLimitHigh.class);
        sc.addEndpoint(WriterError.class);
        sc.addEndpoint(RootEcho.class);
    } catch (DeploymentException e) {
        throw new IllegalStateException(e);
    }
}
 
Example 8
@Override
public final void contextInitialized(final ServletContextEvent servletContextEvent) {
	try {
		final WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContextEvent.getServletContext());
		final StartupJobExecutionService executionService = webApplicationContext.getBean("StartupJobExecutionService", StartupJobExecutionService.class);
		
		if(LOGGER.isInfoEnabled()) {
			LOGGER.info("Starting execution of startup jobs");
		}
		
		final ExecutionResult result = executionService.executeAllPendingJobs();
		
		logResult(result);
	} catch (final Exception e) {
		LOGGER.error("Error processing startup jobs", e);
	}
}
 
Example 9
Source Project: myspring   Source File: ContextLoaderListener.java    License: MIT License 6 votes vote down vote up
/**
     * context初始化.
     */
    @Override
    public void contextInitialized(ServletContextEvent event) {
    	System.out.println("contextInitialized");
    	
    	ServletContext servletContext = event.getServletContext();
    	
    	if (null == this.context) {
    		
    		//配置的application文件路径
    		String cfgFile = servletContext.getInitParameter("contextConfigLocation");
    		
			this.context = new WebApplicationContext(cfgFile);
			
			//存入上下文,后面servlet会取用
			servletContext.setAttribute(ROOT_CXT_ATTR, this.context);
		}
    	
    	//源码中是在这里初始化context,调用refresh方法的,我们在上面new的时候先做了
//        initWebApplicationContext(this.context);
    }
 
Example 10
Source Project: spring-analysis-note   Source File: Spr8510Tests.java    License: MIT License 6 votes vote down vote up
/**
 * If setConfigLocation has not been called explicitly against the application context,
 * then fall back to the ContextLoaderListener init-param if present.
 */
@Test
public void abstractRefreshableWAC_fallsBackToInitParam() {
	XmlWebApplicationContext ctx = new XmlWebApplicationContext();
	//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");

	try {
		cll.contextInitialized(new ServletContextEvent(sc));
		fail("expected exception");
	}
	catch (Throwable t) {
		// assert that an attempt was made to load the correct XML
		assertTrue(t.getMessage().endsWith(
				"Could not open ServletContext resource [/from-init-param.xml]"));
	}
}
 
Example 11
Source Project: java-technology-stack   Source File: ContextLoaderTests.java    License: 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 12
Source Project: Tomcat8-Source-Read   Source File: DrawboardContextListener.java    License: MIT License 5 votes vote down vote up
@Override
public void contextDestroyed(ServletContextEvent sce) {
    // Shutdown our room.
    Room room = DrawboardEndpoint.getRoom(false);
    if (room != null) {
        room.shutdown();
    }
}
 
Example 13
Source Project: Tomcat8-Source-Read   Source File: SessionListener.java    License: MIT License 5 votes vote down vote up
/**
 * Record the fact that this web application has been initialized.
 *
 * @param event
 *            The servlet context event
 */
@Override
public void contextInitialized(ServletContextEvent event) {

    this.context = event.getServletContext();
    log("contextInitialized()");

}
 
Example 14
Source Project: Tomcat8-Source-Read   Source File: ContextListener.java    License: MIT License 5 votes vote down vote up
/**
 * Record the fact that this web application has been initialized.
 *
 * @param event The servlet context event
 */
@Override
public void contextInitialized(ServletContextEvent event) {

    this.context = event.getServletContext();
    log("contextInitialized()");

}
 
Example 15
Source Project: Tomcat8-Source-Read   Source File: SessionListener.java    License: MIT License 5 votes vote down vote up
/**
 * Record the fact that this web application has been destroyed.
 *
 * @param event
 *            The servlet context event
 */
@Override
public void contextDestroyed(ServletContextEvent event) {

    log("contextDestroyed()");
    this.context = null;

}
 
Example 16
Source Project: Tomcat8-Source-Read   Source File: ContextListener.java    License: MIT License 5 votes vote down vote up
/**
 * Record the fact that this web application has been destroyed.
 *
 * @param event The servlet context event
 */
@Override
public void contextDestroyed(ServletContextEvent event) {

    log("contextDestroyed()");
    this.context = null;

}
 
Example 17
Source Project: MeetingFilm   Source File: ConfigListener.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent evt) {
    ServletContext sc = evt.getServletContext();

    //项目发布,当前运行环境的绝对路径
    conf.put("realPath", sc.getRealPath("/").replaceFirst("/", ""));

    //servletContextPath,默认""
    conf.put("contextPath", sc.getContextPath());
}
 
Example 18
Source Project: java-technology-stack   Source File: Spr8510Tests.java    License: MIT License 5 votes vote down vote up
/**
 * Ensure that ContextLoaderListener and AnnotationConfigApplicationContext interact nicely.
 */
@Test
public void annotationConfigWAC() {
	AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();

	ctx.scan("does.not.matter");

	ContextLoaderListener cll = new ContextLoaderListener(ctx);
	cll.contextInitialized(new ServletContextEvent(new MockServletContext()));
}
 
Example 19
Source Project: Tomcat8-Source-Read   Source File: TesterTldListener.java    License: MIT License 5 votes vote down vote up
@Override
public void contextDestroyed(ServletContextEvent sce) {
    // Bug 57446. Same ServletContext should be presented as at init
    if (servletContext == sce.getServletContext()) {
        log.append("PASS-02");
    } else {
        //log.append("FAIL-03");
    }
}
 
Example 20
Source Project: Tomcat8-Source-Read   Source File: TestWsWebSocketContainer.java    License: MIT License 5 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent sce) {
    super.contextInitialized(sce);
    ServerContainer sc =
            (ServerContainer) sce.getServletContext().getAttribute(
                    Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE);
    try {
        // Reset blocking state
        BlockingPojo.resetBlock();
        sc.addEndpoint(BlockingPojo.class);
    } catch (DeploymentException e) {
        throw new IllegalStateException(e);
    }
}
 
Example 21
Source Project: metrics   Source File: MetricsInitializer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent sce) {
  // Create a reporter and add it to the registry.
  // For demo purposes we use SLF4JReporter which should not be used for production systems
  SLF4JReporter reporter = SLF4JReporter.builder().withName("example").withStepSize(10).build();
  MyApp.metricRegistry.addReporter(reporter);
  sce.getServletContext().setAttribute(REPORTER_ATTRIBUTE, reporter);
}
 
Example 22
@Override
public void contextInitialized(ServletContextEvent event) {
	try {
		ServletContext servletContext = event.getServletContext();
		ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
		DBase.DATASOURCE = (DataSource) applicationContext.getBean("dataSource");
		if (DBase.DATASOURCE == null) {
			logger.error("Datasource in DBase for Backend was empty. Backend will try to create its own datasource from emm.properties data");
		}
	} catch (Exception e) {
		logger.error("Cannot set Datasource in DBase for Backend. Backend will try to create its own datasource from emm.properties data", e);
	}
}
 
Example 23
@Override
   public void contextInitialized(ServletContextEvent event) {
       try {
       	if (I18nString.MESSAGE_RESOURCES == null) {
   			DBMessagesResource dbMessagesResource = new DBMessagesResource();
   			dbMessagesResource.init();
   		}
	} catch (Exception e) {
		logger.error("I18NContextListenerForWebservice init: " + e.getMessage(), e);
	}
}
 
Example 24
Source Project: FHIR   Source File: FHIRServletContextListener.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void contextDestroyed(ServletContextEvent event) {
    if (log.isLoggable(Level.FINER)) {
        log.entering(FHIRServletContextListener.class.getName(), "contextDestroyed");
    }
    try {
        // Set our "initComplete" flag back to false.
        event.getServletContext().setAttribute(FHIR_SERVER_INIT_COMPLETE, Boolean.FALSE);

        // If we previously initialized the Kafka publisher, then shut it down now.
        if (kafkaPublisher != null) {
            kafkaPublisher.shutdown();
            kafkaPublisher = null;
        }

        // If we previously initialized the NATS publisher, then shut it down now.
        if (natsPublisher != null) {
            natsPublisher.shutdown();
            natsPublisher = null;
        }
    } catch (Exception e) {
    } finally {
        if (log.isLoggable(Level.FINER)) {
            log.exiting(FHIRServletContextListener.class.getName(), "contextDestroyed");
        }
    }
}
 
Example 25
Source Project: spring-analysis-note   Source File: ContextLoaderTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testContextLoaderListenerWithLocalContextInitializers() {
	MockServletContext sc = new MockServletContext("");
	sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM,
			"org/springframework/web/context/WEB-INF/ContextLoaderTests-acc-context.xml");
	sc.addInitParameter(ContextLoader.CONTEXT_INITIALIZER_CLASSES_PARAM, StringUtils.arrayToCommaDelimitedString(
			new Object[] {TestContextInitializer.class.getName(), TestWebContextInitializer.class.getName()}));
	ContextLoaderListener listener = new ContextLoaderListener();
	listener.contextInitialized(new ServletContextEvent(sc));
	WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
	TestBean testBean = wac.getBean(TestBean.class);
	assertThat(testBean.getName(), equalTo("testName"));
	assertThat(wac.getServletContext().getAttribute("initialized"), notNullValue());
}
 
Example 26
Source Project: spring-analysis-note   Source File: ContextLoaderTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testContextLoaderListenerWithGlobalContextInitializers() {
	MockServletContext sc = new MockServletContext("");
	sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM,
			"org/springframework/web/context/WEB-INF/ContextLoaderTests-acc-context.xml");
	sc.addInitParameter(ContextLoader.GLOBAL_INITIALIZER_CLASSES_PARAM, StringUtils.arrayToCommaDelimitedString(
			new Object[] {TestContextInitializer.class.getName(), TestWebContextInitializer.class.getName()}));
	ContextLoaderListener listener = new ContextLoaderListener();
	listener.contextInitialized(new ServletContextEvent(sc));
	WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
	TestBean testBean = wac.getBean(TestBean.class);
	assertThat(testBean.getName(), equalTo("testName"));
	assertThat(wac.getServletContext().getAttribute("initialized"), notNullValue());
}
 
Example 27
Source Project: spring-analysis-note   Source File: ContextLoaderTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testContextLoaderListenerWithProgrammaticInitializers() {
	MockServletContext sc = new MockServletContext("");
	sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM,
			"org/springframework/web/context/WEB-INF/ContextLoaderTests-acc-context.xml");
	ContextLoaderListener listener = new ContextLoaderListener();
	listener.setContextInitializers(new TestContextInitializer(), new TestWebContextInitializer());
	listener.contextInitialized(new ServletContextEvent(sc));
	WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
	TestBean testBean = wac.getBean(TestBean.class);
	assertThat(testBean.getName(), equalTo("testName"));
	assertThat(wac.getServletContext().getAttribute("initialized"), notNullValue());
}
 
Example 28
Source Project: spring-analysis-note   Source File: ContextLoaderTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testContextLoaderListenerWithProgrammaticAndGlobalInitializers() {
	MockServletContext sc = new MockServletContext("");
	sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM,
			"org/springframework/web/context/WEB-INF/ContextLoaderTests-acc-context.xml");
	sc.addInitParameter(ContextLoader.GLOBAL_INITIALIZER_CLASSES_PARAM, TestWebContextInitializer.class.getName());
	ContextLoaderListener listener = new ContextLoaderListener();
	listener.setContextInitializers(new TestContextInitializer());
	listener.contextInitialized(new ServletContextEvent(sc));
	WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
	TestBean testBean = wac.getBean(TestBean.class);
	assertThat(testBean.getName(), equalTo("testName"));
	assertThat(wac.getServletContext().getAttribute("initialized"), notNullValue());
}
 
Example 29
Source Project: spring-analysis-note   Source File: ContextLoaderTests.java    License: MIT License 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);
	String contextAttr = WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE;
	WebApplicationContext wc = (WebApplicationContext) sc.getAttribute(contextAttr);
	assertTrue("Correct WebApplicationContext exposed in ServletContext",
			wc instanceof SimpleWebApplicationContext);
}
 
Example 30
Source Project: java-technology-stack   Source File: Spr8510Tests.java    License: MIT License 5 votes vote down vote up
/**
 * 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()));
}