List of usage examples for org.springframework.context.support GenericApplicationContext refresh
@Override public void refresh() throws BeansException, IllegalStateException
From source file:org.gridgain.grid.kernal.processors.spring.GridSpringProcessorImpl.java
/** {@inheritDoc} */ @Override//from ww w .jav a2s .c o m public Map<Class<?>, Object> loadBeans(URL cfgUrl, Class<?>... beanClasses) throws GridException { assert beanClasses.length > 0; GenericApplicationContext springCtx; try { springCtx = new GenericApplicationContext(); new XmlBeanDefinitionReader(springCtx).loadBeanDefinitions(new UrlResource(cfgUrl)); springCtx.refresh(); } catch (BeansException e) { if (X.hasCause(e, ClassNotFoundException.class)) throw new GridException("Failed to instantiate Spring XML application context " + "(make sure all classes used in Spring configuration are present at CLASSPATH) " + "[springUrl=" + cfgUrl + ']', e); else throw new GridException("Failed to instantiate Spring XML application context [springUrl=" + cfgUrl + ", err=" + e.getMessage() + ']', e); } Map<Class<?>, Object> beans = new HashMap<>(); for (Class<?> cls : beanClasses) beans.put(cls, bean(springCtx, cls)); return beans; }
From source file:org.gridgain.grid.kernal.processors.spring.GridSpringProcessorImpl.java
/** * Creates Spring application context. Optionally excluded properties can be specified, * it means that if such a property is found in {@link GridConfiguration} * then it is removed before the bean is instantiated. * For example, {@code streamerConfiguration} can be excluded from the configs that Visor uses. * * @param cfgUrl Resource where config file is located. * @param excludedProps Properties to be excluded. * @return Spring application context.// w ww. j av a 2 s .c om */ public static ApplicationContext applicationContext(URL cfgUrl, final String... excludedProps) { GenericApplicationContext springCtx = new GenericApplicationContext(); BeanFactoryPostProcessor postProc = new BeanFactoryPostProcessor() { @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { for (String beanName : beanFactory.getBeanDefinitionNames()) { BeanDefinition def = beanFactory.getBeanDefinition(beanName); if (def.getBeanClassName() != null) { try { Class.forName(def.getBeanClassName()); } catch (ClassNotFoundException ignored) { ((BeanDefinitionRegistry) beanFactory).removeBeanDefinition(beanName); continue; } } MutablePropertyValues vals = def.getPropertyValues(); for (PropertyValue val : new ArrayList<>(vals.getPropertyValueList())) { for (String excludedProp : excludedProps) { if (val.getName().equals(excludedProp)) vals.removePropertyValue(val); } } } } }; springCtx.addBeanFactoryPostProcessor(postProc); new XmlBeanDefinitionReader(springCtx).loadBeanDefinitions(new UrlResource(cfgUrl)); springCtx.refresh(); return springCtx; }
From source file:org.gridgain.grid.loaders.glassfish.GridGlassfishLoader.java
/** * Starts all grids with given properties. * * @param props Startup properties./*from ww w. j a v a 2s.c om*/ * @throws ServerLifecycleException Thrown in case of startup fails. */ @SuppressWarnings({ "unchecked" }) private void start(Properties props) throws ServerLifecycleException { GridLogger log = new GridJclLogger(LogFactory.getLog("GridGain")); if (props != null) cfgFile = props.getProperty(cfgFilePathParam); if (cfgFile == null) throw new ServerLifecycleException("Failed to read property: " + cfgFilePathParam); ctxClsLdr = Thread.currentThread().getContextClassLoader(); // Set thread context classloader because Spring use it for loading classes. Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); URL cfgUrl = U.resolveGridGainUrl(cfgFile); if (cfgUrl == null) throw new ServerLifecycleException("Failed to find Spring configuration file (path provided should be " + "either absolute, relative to GRIDGAIN_HOME, or relative to META-INF folder): " + cfgFile); GenericApplicationContext springCtx; try { springCtx = new GenericApplicationContext(); XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(springCtx); xmlReader.loadBeanDefinitions(new UrlResource(cfgUrl)); springCtx.refresh(); } catch (BeansException e) { throw new ServerLifecycleException( "Failed to instantiate Spring XML application context: " + e.getMessage(), e); } Map cfgMap; try { // Note: Spring is not generics-friendly. cfgMap = springCtx.getBeansOfType(GridConfiguration.class); } catch (BeansException e) { throw new ServerLifecycleException( "Failed to instantiate bean [type=" + GridConfiguration.class + ", err=" + e.getMessage() + ']', e); } if (cfgMap == null) throw new ServerLifecycleException("Failed to find a single grid factory configuration in: " + cfgUrl); if (cfgMap.isEmpty()) throw new ServerLifecycleException("Can't find grid factory configuration in: " + cfgUrl); try { for (GridConfiguration cfg : (Collection<GridConfiguration>) cfgMap.values()) { assert cfg != null; GridConfigurationAdapter adapter = new GridConfigurationAdapter(cfg); // Set Glassfish logger. if (cfg.getGridLogger() == null) adapter.setGridLogger(log); Grid grid = G.start(adapter, springCtx); // Test if grid is not null - started properly. if (grid != null) gridNames.add(grid.name()); } } catch (GridException e) { // Stop started grids only. for (String name : gridNames) G.stop(name, true); throw new ServerLifecycleException("Failed to start GridGain.", e); } }
From source file:org.gridgain.grid.loaders.websphere.GridWebsphereLoader.java
/** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override/*from w w w . j a v a 2 s . c om*/ public void initialize(Properties properties) throws Exception { GridLogger log = new GridJclLogger(LogFactory.getLog("GridGain")); cfgFile = properties.getProperty(cfgFilePathParam); if (cfgFile == null) throw new IllegalArgumentException("Failed to read property: " + cfgFilePathParam); String workMgrName = properties.getProperty(workMgrParam); URL cfgUrl = U.resolveGridGainUrl(cfgFile); if (cfgUrl == null) throw new IllegalArgumentException("Failed to find Spring configuration file (path provided should be " + "either absolute, relative to GRIDGAIN_HOME, or relative to META-INF folder): " + cfgFile); GenericApplicationContext springCtx; try { springCtx = new GenericApplicationContext(); XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(springCtx); xmlReader.loadBeanDefinitions(new UrlResource(cfgUrl)); springCtx.refresh(); } catch (BeansException e) { throw new IllegalArgumentException( "Failed to instantiate Spring XML application context: " + e.getMessage(), e); } Map cfgMap; try { // Note: Spring is not generics-friendly. cfgMap = springCtx.getBeansOfType(GridConfiguration.class); } catch (BeansException e) { throw new IllegalArgumentException( "Failed to instantiate bean [type=" + GridConfiguration.class + ", err=" + e.getMessage() + ']', e); } if (cfgMap == null) throw new IllegalArgumentException("Failed to find a single grid factory configuration in: " + cfgUrl); if (cfgMap.isEmpty()) throw new IllegalArgumentException("Can't find grid factory configuration in: " + cfgUrl); try { ExecutorService execSvc = null; MBeanServer mbeanSrvr = null; for (GridConfiguration cfg : (Collection<GridConfiguration>) cfgMap.values()) { assert cfg != null; GridConfigurationAdapter adapter = new GridConfigurationAdapter(cfg); // Set WebSphere logger. if (cfg.getGridLogger() == null) adapter.setGridLogger(log); if (cfg.getExecutorService() == null) { if (execSvc == null) { if (workMgrName != null) execSvc = new GridThreadWorkManagerExecutor(workMgrName); else { // Obtain/create singleton. J2EEServiceManager j2eeMgr = J2EEServiceManager.getSelf(); // Start it if was not started before. j2eeMgr.start(); // Create new configuration. CommonJWorkManagerConfiguration workMgrCfg = j2eeMgr .createCommonJWorkManagerConfiguration(); workMgrCfg.setName("GridGain"); workMgrCfg.setJNDIName("wm/gridgain"); // Set worker. execSvc = new GridThreadWorkManagerExecutor(j2eeMgr.getCommonJWorkManager(workMgrCfg)); } } adapter.setExecutorService(execSvc); } if (cfg.getMBeanServer() == null) { if (mbeanSrvr == null) mbeanSrvr = AdminServiceFactory.getMBeanFactory().getMBeanServer(); adapter.setMBeanServer(mbeanSrvr); } Grid grid = G.start(adapter, springCtx); // Test if grid is not null - started properly. if (grid != null) gridNames.add(grid.name()); } } catch (GridException e) { // Stop started grids only. for (String name : gridNames) G.stop(name, true); throw new IllegalArgumentException("Failed to start GridGain.", e); } }
From source file:org.hyperic.hq.context.IntegrationTestContextLoader.java
public ApplicationContext loadContext(final String... locations) throws Exception { if (logger.isDebugEnabled()) { logger.debug("Loading ApplicationContext for locations [" + StringUtils.arrayToCommaDelimitedString(locations) + "]."); } //EO if logger is enabled final GenericApplicationContext context = new ProxyingGenericApplicationContext(); //verify sigar's resources existence & load native libraries configureSigar(context, logger);// www .j a va 2s . c om //clean previous application context (if exists) and create a new one Bootstrap.setAppContext(context); try { //initialize the application context delegateLoader.createBeanDefinitionReader(context).loadBeanDefinitions(locations); AnnotationConfigUtils.registerAnnotationConfigProcessors(context); context.refresh(); context.registerShutdownHook(); return context; } catch (Throwable t) { logger.error("An Error had occured during the applicationContext creation, disposing!"); Bootstrap.dispose(); throw (Exception) t; } //EO catch block }
From source file:org.lilyproject.runtime.module.build.ModuleBuilder.java
private Module buildInt(ModuleConfig cfg, ClassLoader classLoader, LilyRuntime runtime) throws ArtifactNotFoundException, MalformedURLException { infolog.info("Starting module " + cfg.getId() + " - " + cfg.getLocation()); ClassLoader previousContextClassLoader = Thread.currentThread().getContextClassLoader(); try {/* w w w .ja va2 s . c o m*/ Thread.currentThread().setContextClassLoader(classLoader); GenericApplicationContext applicationContext = new GenericApplicationContext(); applicationContext.setDisplayName(cfg.getId()); applicationContext.setClassLoader(classLoader); // Note: before loading any beans in the spring container: // * the spring build context needs access to the module, for possible injection & module-protocol resolving during bean initialization // * the module also needs to have the reference to the applicationcontext, as there might be beans trying to get while initializing ModuleImpl module = new ModuleImpl(classLoader, applicationContext, cfg.getDefinition(), cfg.getModuleSource()); SpringBuildContext springBuildContext = new SpringBuildContext(runtime, module, classLoader); SPRING_BUILD_CONTEXT.set(springBuildContext); XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(applicationContext); xmlReader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD); xmlReader.setBeanClassLoader(classLoader); for (ModuleSource.SpringConfigEntry entry : cfg.getModuleSource().getSpringConfigs(runtime.getMode())) { InputStream is = entry.getStream(); try { xmlReader.loadBeanDefinitions(new InputStreamResource(is, entry.getLocation() + " in " + cfg.getDefinition().getFile().getAbsolutePath())); } finally { IOUtils.closeQuietly(is, entry.getLocation()); } } applicationContext.refresh(); // Handle the service exports for (SpringBuildContext.JavaServiceExport entry : springBuildContext.getExportedJavaServices()) { Class serviceType = entry.serviceType; if (!serviceType.isInterface()) { throw new LilyRTException("Exported service is not an interface: " + serviceType.getName()); } String beanName = entry.beanName; Object component; try { component = applicationContext.getBean(beanName); } catch (NoSuchBeanDefinitionException e) { throw new LilyRTException("Bean not found for service to export, service type " + serviceType.getName() + ", bean name " + beanName, e); } if (!serviceType.isAssignableFrom(component.getClass())) { throw new LilyRTException( "Exported service does not implemented specified type interface. Bean = " + beanName + ", interface = " + serviceType.getName()); } infolog.debug(" exporting bean " + beanName + " for service " + serviceType.getName()); Object service = shieldJavaService(serviceType, component, module, classLoader); runtime.getJavaServiceManager().addService(serviceType, cfg.getId(), entry.name, service); } module.start(); return module; } catch (Throwable e) { // TODO module source and classloader handle might need disposing! // especially important if the lily runtime is launched as part of a longer-living VM throw new LilyRTException( "Error constructing module defined at " + cfg.getDefinition().getFile().getAbsolutePath(), e); } finally { Thread.currentThread().setContextClassLoader(previousContextClassLoader); SPRING_BUILD_CONTEXT.set(null); } }
From source file:org.marketcetera.util.spring.SpringUtilsTest.java
@Test public void propertiesConfigurerStringSet() { GenericApplicationContext context = new GenericApplicationContext( new FileSystemXmlApplicationContext(TEST_SPRING_FILE)); SpringUtils.addPropertiesConfigurer(context, TEST_CONFIGURER_BEAN, TEST_PROPERTIES_FILE_BEAN); SpringUtils.addStringBean(context, TEST_NAME_BEAN, "${" + TEST_NAME_PROP + "}"); context.refresh(); assertEquals(TEST_VALUE_PROP, context.getBean(TEST_NAME_BEAN)); }
From source file:org.marketcetera.util.spring.SpringUtilsTest.java
@Test public void propertiesConfigurerStringUnset() { GenericApplicationContext context = new GenericApplicationContext( new FileSystemXmlApplicationContext(TEST_SPRING_FILE)); SpringUtils.addPropertiesConfigurer(context, TEST_CONFIGURER_BEAN, TEST_PROPERTIES_FILE_BEAN); SpringUtils.addStringBean(context, TEST_NAME_BEAN, "${" + TEST_NAME_PROP_BLANK + "}"); context.refresh(); assertEquals(StringUtils.EMPTY, context.getBean(TEST_NAME_BEAN)); }
From source file:org.marketcetera.util.spring.SpringUtilsTest.java
@Test public void propertiesConfigurerList() { GenericApplicationContext context = new GenericApplicationContext( new FileSystemXmlApplicationContext(TEST_SPRING_FILE)); SpringUtils.addPropertiesConfigurer(context, TEST_CONFIGURER_BEAN, TEST_PROPERTIES_FILES_BEAN); SpringUtils.addStringBean(context, TEST_NAME_BEAN, "${" + TEST_NAME_PROP + "}"); context.refresh(); assertEquals(TEST_VALUE_PROP_OVERRIDE, context.getBean(TEST_NAME_BEAN)); }
From source file:org.openadaptor.spring.SpringAdaptor.java
private ListableBeanFactory createBeanFactory() { if (configUrls.isEmpty() && !ignoreConfigUrls) { throw new RuntimeException("no config urls specified"); }/*w ww .j ava 2 s.co m*/ GenericApplicationContext context = getInternalContext(); //Changed to make failure to load OPENADAPTOR_SPRING_CONFIG non-fatal. try { loadBeanDefinitions("classpath:" + ResourceUtil.getResourcePath(this, "", OPENADAPTOR_SPRING_CONFIG), context); } catch (BeanDefinitionStoreException bdse) { Throwable cause = bdse.getCause(); log.warn("Resource " + OPENADAPTOR_SPRING_CONFIG + " was not loaded. Reason: " + cause.getClass().getName()); } for (Iterator iter = configUrls.iterator(); iter.hasNext();) { String configUrl = (String) iter.next(); loadBeanDefinitions(configUrl, context); } configureProperties(context, propsUrls); context.refresh(); setComponentIds(context); configureMBeanServer(context); return context; }