List of usage examples for javax.servlet ServletContextEvent ServletContextEvent
public ServletContextEvent(ServletContext source)
From source file:org.hdiv.hateoas.jackson.AbstractHDIVTestCase.java
protected 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); }/* w w w. j a v a 2s. co 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(); }
From source file:org.jvnet.hudson.test.HudsonTestCase.java
protected void setUp() throws Exception { env.pin();//from w w w . j a va2s . c om recipe(); AbstractProject.WORKSPACE.toString(); hudson = newHudson(); hudson.setNoUsageStatistics(true); // collecting usage stats from tests are pointless. hudson.setCrumbIssuer(((CrumbIssuerDescriptor<CrumbIssuer>) hudson.getDescriptor(TestCrumbIssuer.class)) .newInstance(null, null)); hudson.servletContext.setAttribute("app", hudson); hudson.servletContext.setAttribute("version", "?"); WebAppMain.installExpressionFactory(new ServletContextEvent(hudson.servletContext)); // set a default JDK to be the one that the harness is using. hudson.getJDKs().add(new JDK("default", System.getProperty("java.home"))); // load updates from local proxy to avoid network traffic. final String updateCenterUrl = "http://localhost:" + JavaNetReverseProxy.getInstance().localPort + "/"; hudson.getUpdateCenter().configure(new UpdateCenterConfiguration() { public String getUpdateCenterUrl() { return updateCenterUrl; } }); DownloadService.neverUpdate = true; // cause all the descriptors to reload. // ideally we'd like to reset them to properly emulate the behavior, but that's not possible. Mailer.descriptor().setHudsonUrl(null); for (Descriptor d : hudson.getExtensionList(Descriptor.class)) d.load(); }
From source file:org.jvnet.hudson.test.JenkinsRule.java
/** * Override to set up your specific external resource. * @throws Throwable if setup fails (which will disable {@code after} *//*from w ww .j a v a 2 s.co m*/ public void before() throws Throwable { if (Functions.isWindows()) { // JENKINS-4409. // URLConnection caches handles to jar files by default, // and it prevents delete temporary directories on Windows. // Disables caching here. // Though defaultUseCache is a static field, // its setter and getter are provided as instance methods. URLConnection aConnection = new File(".").toURI().toURL().openConnection(); origDefaultUseCache = aConnection.getDefaultUseCaches(); aConnection.setDefaultUseCaches(false); } // Not ideal (https://github.com/junit-team/junit/issues/116) but basically works. if (Boolean.getBoolean("ignore.random.failures")) { RandomlyFails rf = testDescription.getAnnotation(RandomlyFails.class); if (rf != null) { throw new AssumptionViolatedException("Known to randomly fail: " + rf.value()); } } env = new TestEnvironment(testDescription); env.pin(); recipe(); AbstractProject.WORKSPACE.toString(); User.clear(); try { jenkins = hudson = newHudson(); } catch (Exception e) { // if Hudson instance fails to initialize, it leaves the instance field non-empty and break all the rest of the tests, so clean that up. Field f = Jenkins.class.getDeclaredField("theInstance"); f.setAccessible(true); f.set(null, null); throw e; } jenkins.setNoUsageStatistics(true); // collecting usage stats from tests are pointless. jenkins.setCrumbIssuer(new TestCrumbIssuer()); jenkins.servletContext.setAttribute("app", jenkins); jenkins.servletContext.setAttribute("version", "?"); WebAppMain.installExpressionFactory(new ServletContextEvent(jenkins.servletContext)); // set a default JDK to be the one that the harness is using. jenkins.getJDKs().add(new JDK("default", System.getProperty("java.home"))); configureUpdateCenter(); // expose the test instance as a part of URL tree. // this allows tests to use a part of the URL space for itself. jenkins.getActions().add(this); JenkinsLocationConfiguration.get().setUrl(getURL().toString()); setUpTimeout(); }
From source file:org.opennms.web.rest.AbstractSpringJerseyRestTestCase.java
@Before public void setUp() throws Throwable { beforeServletStart();//ww w . jav a2s . com DaoTestConfigBean bean = new DaoTestConfigBean(); bean.afterPropertiesSet(); MockDatabase db = new MockDatabase(true); DataSourceFactory.setInstance(db); setServletContext(new MockServletContext("file:src/main/webapp")); getServletContext().addInitParameter("contextConfigLocation", "classpath:/org/opennms/web/rest/applicationContext-test.xml " + "classpath:/META-INF/opennms/applicationContext-commonConfigs.xml " + "classpath:/META-INF/opennms/applicationContext-soa.xml " + "classpath*:/META-INF/opennms/component-service.xml " + "classpath*:/META-INF/opennms/component-dao.xml " + "classpath:/META-INF/opennms/applicationContext-reportingCore.xml " + "classpath:/META-INF/opennms/applicationContext-databasePopulator.xml " + "classpath:/org/opennms/web/svclayer/applicationContext-svclayer.xml " + "classpath:/META-INF/opennms/applicationContext-mockEventProxy.xml " + "classpath:/applicationContext-jersey-test.xml " + "classpath:/META-INF/opennms/applicationContext-reporting.xml " + "classpath:/META-INF/opennms/applicationContext-mock-usergroup.xml " + "classpath:/META-INF/opennms/applicationContext-minimal-conf.xml " + "/WEB-INF/applicationContext-spring-security.xml " + "/WEB-INF/applicationContext-jersey.xml"); getServletContext().addInitParameter("parentContextKey", "daoContext"); ServletContextEvent e = new ServletContextEvent(getServletContext()); setContextListener(new ContextLoaderListener()); getContextListener().contextInitialized(e); getServletContext().setContextPath(contextPath); setServletConfig(new MockServletConfig(getServletContext(), "dispatcher")); getServletConfig().addInitParameter("com.sun.jersey.config.property.resourceConfigClass", "com.sun.jersey.api.core.PackagesResourceConfig"); getServletConfig().addInitParameter("com.sun.jersey.config.property.packages", "org.opennms.web.rest"); try { MockFilterConfig filterConfig = new MockFilterConfig(getServletContext(), "openSessionInViewFilter"); setFilter(new OpenSessionInViewFilter()); getFilter().init(filterConfig); setDispatcher(new SpringServlet()); getDispatcher().init(getServletConfig()); } catch (ServletException se) { throw se.getRootCause(); } setWebAppContext(WebApplicationContextUtils.getWebApplicationContext(getServletContext())); afterServletStart(); System.err.println("------------------------------------------------------------------------------"); }
From source file:org.ops4j.pax.web.service.jetty.internal.HttpServiceContext.java
/** * If the listener is a servlet conetx listener and the context is already started, notify the servlet context * listener about the fact that context is started. This has to be done separately as the listener could be added * after the context is already started, case when servlet context listeners are not notified anymore. * * @param listener to be notified.//from w w w . ja v a2 s . c om */ @Override public void addEventListener(final EventListener listener) { super.addEventListener(listener); if (isStarted() && listener instanceof ServletContextListener) { try { ContextClassLoaderUtils.doWithClassLoader(getClassLoader(), new Callable<Void>() { public Void call() { ((ServletContextListener) listener).contextInitialized(new ServletContextEvent(_scontext)); return null; } }); } catch (Exception e) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } LOG.error("Ignored exception during listener registration", e); } } }
From source file:org.polymap.service.geoserver.GeoServerWms.java
public void destroy() { log.debug("destroy(): ..."); super.destroy(); if (dispatcher != null) { ClassLoader threadLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(context.cl); try {//w w w . j a v a 2s . c om // listeners ServletContextEvent ev = new ServletContextEvent(context); for (ServletContextListener loader : loaders) { loader.contextDestroyed(ev); } loaders = null; // dispatcher dispatcher.destroy(); dispatcher = null; context.destroy(); context = null; } catch (IOException e) { log.warn("", e); } finally { Thread.currentThread().setContextClassLoader(threadLoader); } } }
From source file:org.polymap.service.geoserver.GeoServerWms.java
protected void initGeoServer() throws Exception { context = new PluginServletContext(getServletContext()); log.debug("initGeoServer(): contextPath=" + context.getContextPath()); ClassLoader threadLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(context.cl); try {/*from w w w . j a v a 2 s .com*/ File cacheDir = GeoServerPlugin.getDefault().getCacheDir(); dataDir = new File(cacheDir, Stringer.on(map.getLabel()).toFilename("_").toString()); log.debug(" dataDir=" + dataDir.getAbsolutePath()); dataDir.mkdirs(); FileUtils.forceDeleteOnExit(dataDir); // web.xml context.setAttribute("serviceStrategy", "SPEED"); context.setAttribute("contextConfigLocation", "classpath*:/applicationContext.xml classpath*:/applicationSecurityContext.xml"); context.setAttribute("enableVersioning", "false"); context.setAttribute("GEOSERVER_DATA_DIR", dataDir.getAbsoluteFile()); try { servers.set(this); loaders.add(new LoggingStartupContextListener()); loaders.add(new ContextLoaderListener()); ServletContextEvent ev = new ServletContextEvent(context); for (Object loader : loaders) { ((ServletContextListener) loader).contextInitialized(ev); } } finally { servers.set(null); } dispatcher = new DispatcherServlet(); log.debug("Dispatcher: " + dispatcher.getClass().getClassLoader()); dispatcher.init(new ServletConfig() { public String getInitParameter(String name) { return GeoServerWms.this.getInitParameter(name); } public Enumeration getInitParameterNames() { return GeoServerWms.this.getInitParameterNames(); } public ServletContext getServletContext() { return context; } public String getServletName() { return "dispatcher"; } }); } finally { Thread.currentThread().setContextClassLoader(threadLoader); } }
From source file:org.seasar.cubby.plugins.guice.CubbyModuleTest.java
@Test public void configure() throws Exception { final HttpServletRequest request = createNiceMock(HttpServletRequest.class); final HttpServletResponse response = createNiceMock(HttpServletResponse.class); final ServletContext servletContext = createNiceMock(ServletContext.class); expect(servletContext.getInitParameter("cubby.guice.module")).andStubReturn(TestModule.class.getName()); final Hashtable<String, Object> attributes = new Hashtable<String, Object>(); expect(servletContext.getAttribute((String) anyObject())).andStubAnswer(new IAnswer<Object>() { public Object answer() throws Throwable { return attributes.get(getCurrentArguments()[0]); }/*from w w w . jav a 2s . com*/ }); servletContext.setAttribute((String) anyObject(), anyObject()); expectLastCall().andAnswer(new IAnswer<Void>() { public Void answer() throws Throwable { attributes.put((String) getCurrentArguments()[0], getCurrentArguments()[1]); return null; } }); replay(servletContext); final CubbyGuiceServletContextListener cubbyGuiceServletContextListener = new CubbyGuiceServletContextListener(); cubbyGuiceServletContextListener.contextInitialized(new ServletContextEvent(servletContext)); final GuiceFilter guiceFilter = new GuiceFilter(); guiceFilter.init(new FilterConfig() { public String getFilterName() { return "guice"; } public String getInitParameter(final String name) { return null; } @SuppressWarnings("unchecked") public Enumeration getInitParameterNames() { return new Vector<String>().elements(); } public ServletContext getServletContext() { return servletContext; } }); final FilterChain chain = new FilterChain() { public void doFilter(final ServletRequest request, final ServletResponse response) throws IOException, ServletException { final PluginRegistry pluginRegistry = PluginRegistry.getInstance(); final GuicePlugin guicePlugin = new GuicePlugin(); try { guicePlugin.initialize(servletContext); guicePlugin.ready(); pluginRegistry.register(guicePlugin); } catch (final Exception e) { throw new ServletException(e); } final Injector injector = guicePlugin.getInjector(); System.out.println(injector); final PathResolverProvider pathResolverProvider = ProviderFactory.get(PathResolverProvider.class); final PathResolver pathResolver = pathResolverProvider.getPathResolver(); System.out.println(pathResolver); final PathTemplateParser pathTemplateParser = injector.getInstance(PathTemplateParser.class); System.out.println(pathTemplateParser); assertTrue(pathTemplateParser instanceof MyPathTemplateParser); final ContainerProvider containerProvider = ProviderFactory.get(ContainerProvider.class); final Container container = containerProvider.getContainer(); final Foo foo = container.lookup(Foo.class); System.out.println(foo); System.out.println(foo.pathResolver); assertSame(pathResolver, foo.pathResolver); try { final Baz baz = injector.getInstance(Baz.class); System.out.println(baz); fail(); } catch (final ConfigurationException e) { // ok } final ConverterProvider converterProvider = ProviderFactory.get(ConverterProvider.class); System.out.println(converterProvider); System.out.println(converterProvider.getConverter(BigDecimalConverter.class)); final FileUpload fileUpload1 = injector.getInstance(FileUpload.class); System.out.println(fileUpload1); System.out.println(fileUpload1.getFileItemFactory()); final FileUpload fileUpload2 = injector.getInstance(FileUpload.class); System.out.println(fileUpload2); System.out.println(fileUpload2.getFileItemFactory()); assertNotSame(fileUpload1, fileUpload2); assertNotSame(fileUpload1.getFileItemFactory(), fileUpload2.getFileItemFactory()); } }; guiceFilter.doFilter(request, response, chain); cubbyGuiceServletContextListener.contextDestroyed(new ServletContextEvent(servletContext)); ThreadContext.remove(); }
From source file:org.springframework.cloud.netflix.eureka.server.EurekaServerInitializerConfiguration.java
@Override public void start() { discoveryManagerIntitializer().init(); new Thread(new Runnable() { @Override/*from ww w . ja va 2 s .c om*/ public void run() { try { new EurekaBootStrap() { @Override protected void initEurekaEnvironment() { try { if (System.getProperty("log4j.configuration") == null) { System.setProperty("log4j.configuration", new ClassPathResource("log4j.properties", Log4JLoggingSystem.class) .getURL().toString()); } } catch (IOException e) { // ignore } LoggingConfiguration.getInstance().configure(); EurekaServerConfigurationManager.getInstance().setConfiguration(eurekaServerConfig); XmlXStream.getInstance().setMarshallingStrategy( new DataCenterAwareMarshallingStrategy(applicationContext)); JsonXStream.getInstance().setMarshallingStrategy( new DataCenterAwareMarshallingStrategy(applicationContext)); // PeerAwareInstanceRegistry.getInstance(); applicationContext.publishEvent(new EurekaRegistryAvailableEvent(eurekaServerConfig)); } }.contextInitialized(new ServletContextEvent(servletContext)); logger.info("Started Eureka Server"); running = true; applicationContext.publishEvent(new EurekaServerStartedEvent(eurekaServerConfig)); } catch (Exception e) { // Help! logger.error("Could not initialize Eureka servlet context", e); } } }).start(); }
From source file:org.springframework.web.util.Log4jWebConfigurerTests.java
@Test public void testLog4jConfigListener() { Log4jConfigListener listener = new Log4jConfigListener(); MockServletContext sc = new MockServletContext("", new FileSystemResourceLoader()); sc.addInitParameter(Log4jWebConfigurer.CONFIG_LOCATION_PARAM, RELATIVE_PATH); listener.contextInitialized(new ServletContextEvent(sc)); try {/*from w w w. ja v a 2 s . c o m*/ assertLogOutput(); } finally { listener.contextDestroyed(new ServletContextEvent(sc)); } assertTrue(MockLog4jAppender.closeCalled); }