List of usage examples for org.springframework.context.support GenericApplicationContext refresh
@Override public void refresh() throws BeansException, IllegalStateException
From source file:org.openmrs.test.StartModuleExecutionListener.java
/** * called before @BeforeTransaction methods * //from w w w . ja v a 2s. co m * @see org.springframework.test.context.support.AbstractTestExecutionListener#prepareTestInstance(org.springframework.test.context.TestContext) */ @Override public void prepareTestInstance(TestContext testContext) throws Exception { StartModule startModuleAnnotation = testContext.getTestClass().getAnnotation(StartModule.class); // if the developer listed some modules with the @StartModule annotation on the class if (startModuleAnnotation != null) { if (!lastClassRun.equals(testContext.getTestClass().getSimpleName())) { // mark this with our class so that the services are only restarted once lastClassRun = testContext.getTestClass().getSimpleName(); if (!Context.isSessionOpen()) Context.openSession(); ModuleUtil.shutdown(); // load the omods that the dev defined for this class String modulesToLoad = StringUtils.join(startModuleAnnotation.value(), " "); Properties props = BaseContextSensitiveTest.runtimeProperties; props.setProperty(ModuleConstants.RUNTIMEPROPERTY_MODULE_LIST_TO_LOAD, modulesToLoad); try { ModuleUtil.startup(props); } catch (Exception e) { System.out.println("Error while starting modules: "); e.printStackTrace(System.out); throw e; } Assert.assertTrue( "Some of the modules did not start successfully for " + testContext.getTestClass().getSimpleName() + ". Only " + ModuleFactory.getStartedModules().size() + " modules started instead of " + startModuleAnnotation.value().length, startModuleAnnotation.value().length <= ModuleFactory.getStartedModules().size()); /* * Refresh spring so the Services are recreated (aka serializer gets put into the SerializationService) * To do this, wrap the applicationContext from the testContext into a GenericApplicationContext, allowing * loading beans from moduleApplicationContext into it and then calling ctx.refresh() * This approach ensures that the application context remains consistent */ GenericApplicationContext ctx = new GenericApplicationContext(testContext.getApplicationContext()); XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx); Enumeration<URL> list = OpenmrsClassLoader.getInstance() .getResources("moduleApplicationContext.xml"); while (list.hasMoreElements()) { xmlReader.loadBeanDefinitions(new UrlResource(list.nextElement())); } //ensure that when refreshing, we use the openmrs class loader for the started modules. boolean useSystemClassLoader = Context.isUseSystemClassLoader(); Context.setUseSystemClassLoader(false); try { ctx.refresh(); } finally { Context.setUseSystemClassLoader(useSystemClassLoader); } // session is closed by the test framework //Context.closeSession(); } } }
From source file:org.openspaces.admin.application.ApplicationFileDeployment.java
private static <T> T getSpringBeanFromResource(Resource resource, Class<T> type) throws BeansException { final GenericApplicationContext context = new GenericApplicationContext(); try {// ww w . j av a2 s .c o m final XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(context); xmlReader.loadBeanDefinitions(resource); context.refresh(); return context.getBean(type); } finally { if (context.isActive()) { context.close(); } } }
From source file:org.opentripplanner.integration.benchmark.RunBenchmarkPlanMain.java
private GenericApplicationContext getApplicationContext() { GenericApplicationContext ctx = new GenericApplicationContext(); XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx); xmlReader.loadBeanDefinitions(new ClassPathResource("org/opentripplanner/application-context.xml")); Map<String, BeanDefinition> additionalBeans = getAdditionalBeans(); for (Map.Entry<String, BeanDefinition> entry : additionalBeans.entrySet()) ctx.registerBeanDefinition(entry.getKey(), entry.getValue()); ctx.refresh(); ctx.registerShutdownHook();/*from w w w . j a va 2 s. c o m*/ return ctx; }
From source file:org.pentaho.platform.plugin.services.pluginmgr.DefaultPluginManager.java
@Override public final boolean reload() { IPentahoSession session = PentahoSessionHolder.getSession(); boolean anyErrors = false; IPluginProvider pluginProvider = PentahoSystem.get(IPluginProvider.class, "IPluginProvider", session); List<IPlatformPlugin> providedPlugins = null; try {/*from w ww .j a v a 2 s . c o m*/ synchronized (registeredPlugins) { this.unloadPlugins(); } // the plugin may fail to load during getPlugins without an exception thrown if the provider // is capable of discovering the plugin fine but there are structural problems with the plugin // itself. In this case a warning should be logged by the provider, but, again, no exception // is expected. providedPlugins = pluginProvider.getPlugins(session); } catch (PlatformPluginRegistrationException e1) { String msg = Messages.getInstance().getErrorString("PluginManager.ERROR_0012_PLUGIN_DISCOVERY_FAILED"); //$NON-NLS-1$ Logger.error(getClass().toString(), msg, e1); PluginMessageLogger.add(msg); anyErrors = true; } // TODO: refresh appc context here? synchronized (providedPlugins) { for (IPlatformPlugin plugin : providedPlugins) { try { registeredPlugins.put(plugin.getId(), plugin); ClassLoader loader = setPluginClassLoader(plugin); initializeBeanFactory(plugin, loader); } catch (Throwable t) { // this has been logged already anyErrors = true; String msg = Messages.getInstance() .getErrorString("PluginManager.ERROR_0011_FAILED_TO_REGISTER_PLUGIN", plugin.getId()); //$NON-NLS-1$ Logger.error(getClass().toString(), msg, t); PluginMessageLogger.add(msg); } } registeredPlugins.clear(); for (IPlatformPlugin plugin : providedPlugins) { try { GenericApplicationContext beanFactory = beanFactoryMap.get(plugin.getId()); if (beanFactory != null) { beanFactory.refresh(); } registerPlugin(plugin); registeredPlugins.put(plugin.getId(), plugin); } catch (Throwable t) { // this has been logged already anyErrors = true; String msg = Messages.getInstance() .getErrorString("PluginManager.ERROR_0011_FAILED_TO_REGISTER_PLUGIN", plugin.getId()); //$NON-NLS-1$ Logger.error(getClass().toString(), msg, t); PluginMessageLogger.add(msg); } } } IServiceManager svcManager = PentahoSystem.get(IServiceManager.class, null); if (svcManager != null) { try { svcManager.initServices(); } catch (ServiceInitializationException e) { String msg = Messages.getInstance() .getErrorString("PluginManager.ERROR_0022_SERVICE_INITIALIZATION_FAILED"); //$NON-NLS-1$ Logger.error(getClass().toString(), msg, e); PluginMessageLogger.add(msg); } } return !anyErrors; }
From source file:org.sakaiproject.test.SakaiDependencyInjectionTests.java
@Override protected ConfigurableApplicationContext createApplicationContext(String[] locations) { if (log.isDebugEnabled()) log.debug("createApplicationContext locations=" + Arrays.asList(locations)); ComponentContainerEmulator.startComponentManagerForTest(); ConfigurableApplicationContext componentContext = (ConfigurableApplicationContext) ComponentContainerEmulator .getContainerApplicationContext(); // WARNING: Copied from the superclass! The only change is to add a // parent application context to the application context constructor. GenericApplicationContext context = new GenericApplicationContext(componentContext); customizeBeanFactory(context.getDefaultListableBeanFactory()); new XmlBeanDefinitionReader(context).loadBeanDefinitions(locations); context.refresh(); return context; }
From source file:org.springframework.amqp.rabbit.listener.DirectMessageListenerContainerIntegrationTests.java
private void testRecoverDeletedQueueGuts(boolean autoDeclare) throws Exception { CachingConnectionFactory cf = new CachingConnectionFactory("localhost"); DirectMessageListenerContainer container = new DirectMessageListenerContainer(cf); if (autoDeclare) { GenericApplicationContext context = new GenericApplicationContext(); context.getBeanFactory().registerSingleton("foo", new Queue(Q1)); RabbitAdmin admin = new RabbitAdmin(cf); admin.setApplicationContext(context); context.getBeanFactory().registerSingleton("admin", admin); context.refresh(); container.setApplicationContext(context); }//from w ww .j a v a 2s. c om container.setAutoDeclare(autoDeclare); container.setQueueNames(Q1, Q2); container.setConsumersPerQueue(2); container.setConsumersPerQueue(2); container.setMessageListener(m -> { }); container.setFailedDeclarationRetryInterval(500); container.setBeanName("deleteQauto=" + autoDeclare); container.setConsumerTagStrategy(new Tag()); container.afterPropertiesSet(); container.start(); assertTrue(consumersOnQueue(Q1, 2)); assertTrue(consumersOnQueue(Q2, 2)); assertTrue(activeConsumerCount(container, 4)); brokerRunning.deleteQueues(Q1); assertTrue(consumersOnQueue(Q2, 2)); assertTrue(activeConsumerCount(container, 2)); assertTrue(restartConsumerCount(container, 2)); RabbitAdmin admin = new RabbitAdmin(cf); if (!autoDeclare) { Thread.sleep(2000); admin.declareQueue(new Queue(Q1)); } assertTrue(consumersOnQueue(Q1, 2)); assertTrue(consumersOnQueue(Q2, 2)); assertTrue(activeConsumerCount(container, 4)); container.stop(); assertTrue(consumersOnQueue(Q1, 0)); assertTrue(consumersOnQueue(Q2, 0)); assertTrue(activeConsumerCount(container, 0)); assertEquals(0, TestUtils.getPropertyValue(container, "consumersByQueue", MultiValueMap.class).size()); cf.destroy(); }
From source file:org.springframework.amqp.rabbit.listener.DirectMessageListenerContainerTests.java
private void testRecoverDeletedQueueGuts(boolean autoDeclare) throws Exception { CachingConnectionFactory cf = new CachingConnectionFactory("localhost"); DirectMessageListenerContainer container = new DirectMessageListenerContainer(cf); if (autoDeclare) { GenericApplicationContext context = new GenericApplicationContext(); context.getBeanFactory().registerSingleton("foo", new Queue(Q1)); RabbitAdmin admin = new RabbitAdmin(cf); admin.setApplicationContext(context); context.getBeanFactory().registerSingleton("admin", admin); context.refresh(); container.setApplicationContext(context); }/*from ww w. j av a 2 s .c o m*/ container.setAutoDeclare(autoDeclare); container.setQueueNames(Q1, Q2); container.setConsumersPerQueue(2); container.setConsumersPerQueue(2); container.setMessageListener(m -> { }); container.setFailedDeclarationRetryInterval(500); container.setBeanName("deleteQauto=" + autoDeclare); container.setConsumerTagStrategy(new Tag()); container.afterPropertiesSet(); container.start(); assertTrue(consumersOnQueue(Q1, 2)); assertTrue(consumersOnQueue(Q2, 2)); assertTrue(activeConsumerCount(container, 4)); brokerRunning.getAdmin().deleteQueue(Q1); assertTrue(consumersOnQueue(Q2, 2)); assertTrue(activeConsumerCount(container, 2)); assertTrue(restartConsumerCount(container, 2)); if (!autoDeclare) { Thread.sleep(2000); brokerRunning.getAdmin().declareQueue(new Queue(Q1)); } assertTrue(consumersOnQueue(Q1, 2)); assertTrue(consumersOnQueue(Q2, 2)); assertTrue(activeConsumerCount(container, 4)); container.stop(); assertTrue(consumersOnQueue(Q1, 0)); assertTrue(consumersOnQueue(Q2, 0)); assertTrue(activeConsumerCount(container, 0)); assertEquals(0, TestUtils.getPropertyValue(container, "consumersByQueue", MultiValueMap.class).size()); cf.destroy(); }
From source file:org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainerIntegration2Tests.java
@Test public void testListenFromAnonQueue() throws Exception { AnonymousQueue queue = new AnonymousQueue(); CountDownLatch latch = new CountDownLatch(10); SimpleMessageListenerContainer container = new SimpleMessageListenerContainer( template.getConnectionFactory()); container.setMessageListener(new MessageListenerAdapter(new PojoListener(latch))); container.setQueueNames(queue.getName()); container.setConcurrentConsumers(2); GenericApplicationContext context = new GenericApplicationContext(); context.getBeanFactory().registerSingleton("foo", queue); context.refresh(); container.setApplicationContext(context); RabbitAdmin admin = new RabbitAdmin(this.template.getConnectionFactory()); admin.setApplicationContext(context); container.setRabbitAdmin(admin);/*w w w . j a v a 2 s. c o m*/ container.afterPropertiesSet(); container.start(); for (int i = 0; i < 10; i++) { template.convertAndSend(queue.getName(), i + "foo"); } assertTrue(latch.await(10, TimeUnit.SECONDS)); container.stop(); container.start(); latch = new CountDownLatch(10); container.setMessageListener(new MessageListenerAdapter(new PojoListener(latch))); for (int i = 0; i < 10; i++) { template.convertAndSend(queue.getName(), i + "foo"); } assertTrue(latch.await(10, TimeUnit.SECONDS)); container.stop(); }
From source file:org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainerIntegration2Tests.java
@Test public void testExclusive() throws Exception { Log logger = spy(TestUtils.getPropertyValue(this.template.getConnectionFactory(), "logger", Log.class)); doReturn(true).when(logger).isInfoEnabled(); new DirectFieldAccessor(this.template.getConnectionFactory()).setPropertyValue("logger", logger); CountDownLatch latch1 = new CountDownLatch(1000); SimpleMessageListenerContainer container1 = new SimpleMessageListenerContainer( template.getConnectionFactory()); container1.setMessageListener(new MessageListenerAdapter(new PojoListener(latch1))); container1.setQueueNames(queue.getName()); GenericApplicationContext context = new GenericApplicationContext(); context.getBeanFactory().registerSingleton("foo", queue); context.refresh(); container1.setApplicationContext(context); container1.setExclusive(true);//from w w w. j a v a2 s .c om container1.afterPropertiesSet(); container1.start(); int n = 0; while (n++ < 100 && container1.getActiveConsumerCount() < 1) { Thread.sleep(100); } assertTrue(n < 100); CountDownLatch latch2 = new CountDownLatch(1000); SimpleMessageListenerContainer container2 = new SimpleMessageListenerContainer( template.getConnectionFactory()); container2.setMessageListener(new MessageListenerAdapter(new PojoListener(latch2))); container2.setQueueNames(queue.getName()); container2.setApplicationContext(context); container2.setRecoveryInterval(1000); container2.setExclusive(true); // not really necessary, but likely people will make all consumers exclusive. ApplicationEventPublisher publisher = mock(ApplicationEventPublisher.class); container2.setApplicationEventPublisher(publisher); container2.afterPropertiesSet(); Log containerLogger = spy(TestUtils.getPropertyValue(container2, "logger", Log.class)); doReturn(true).when(containerLogger).isWarnEnabled(); new DirectFieldAccessor(container2).setPropertyValue("logger", containerLogger); container2.start(); for (int i = 0; i < 1000; i++) { template.convertAndSend(queue.getName(), i + "foo"); } assertTrue(latch1.await(10, TimeUnit.SECONDS)); assertEquals(1000, latch2.getCount()); container1.stop(); // container 2 should recover and process the next batch of messages for (int i = 0; i < 1000; i++) { template.convertAndSend(queue.getName(), i + "foo"); } assertTrue(latch2.await(10, TimeUnit.SECONDS)); container2.stop(); ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class); verify(logger, atLeastOnce()).info(captor.capture()); assertThat(captor.getAllValues(), contains(containsString("exclusive"))); ArgumentCaptor<ListenerContainerConsumerFailedEvent> eventCaptor = ArgumentCaptor .forClass(ListenerContainerConsumerFailedEvent.class); verify(publisher).publishEvent(eventCaptor.capture()); ListenerContainerConsumerFailedEvent event = eventCaptor.getValue(); assertEquals("Consumer raised exception, attempting restart", event.getReason()); assertFalse(event.isFatal()); assertThat(event.getThrowable(), instanceOf(AmqpIOException.class)); verify(containerLogger).warn(any()); }
From source file:org.springframework.aop.aspectj.autoproxy.AspectJAutoProxyCreatorTests.java
@Test public void testAspectsAndAdvisorNotAppliedToManySingletonsIsFastEnough() { Assume.group(TestGroup.PERFORMANCE); Assume.notLogging(factoryLog);// w w w . java 2 s.c o m GenericApplicationContext ac = new GenericApplicationContext(); new XmlBeanDefinitionReader(ac) .loadBeanDefinitions(new ClassPathResource(qName("aspectsPlusAdvisor.xml"), getClass())); for (int i = 0; i < 10000; i++) { ac.registerBeanDefinition("singleton" + i, new RootBeanDefinition(NestedTestBean.class)); } StopWatch sw = new StopWatch(); sw.start("Singleton Creation"); ac.refresh(); sw.stop(); // What's a reasonable expectation for _any_ server or developer machine load? // 8 seconds? assertStopWatchTimeLimit(sw, 8000); }