List of usage examples for org.springframework.context.support GenericApplicationContext GenericApplicationContext
public GenericApplicationContext()
From source file:org.apache.ignite.internal.util.spring.IgniteSpringHelperImpl.java
/** * @param stream Input stream containing Spring XML configuration. * @return Context.//from ww w . j a v a2 s .c o m * @throws IgniteCheckedException In case of error. */ private ApplicationContext initContext(InputStream stream) throws IgniteCheckedException { GenericApplicationContext springCtx; try { springCtx = new GenericApplicationContext(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(springCtx); reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD); reader.loadBeanDefinitions(new InputStreamResource(stream)); springCtx.refresh(); } catch (BeansException e) { if (X.hasCause(e, ClassNotFoundException.class)) throw new IgniteCheckedException( "Failed to instantiate Spring XML application context " + "(make sure all classes used in Spring configuration are present at CLASSPATH) ", e); else throw new IgniteCheckedException( "Failed to instantiate Spring XML application context" + ", err=" + e.getMessage() + ']', e); } return springCtx; }
From source file:org.apache.ignite.internal.util.spring.IgniteSpringHelperImpl.java
/** * @param url XML file URL./*from w w w .j a va2 s . co m*/ * @return Context. * @throws IgniteCheckedException In case of error. */ private ApplicationContext initContext(URL url) throws IgniteCheckedException { GenericApplicationContext springCtx; try { springCtx = new GenericApplicationContext(); new XmlBeanDefinitionReader(springCtx).loadBeanDefinitions(new UrlResource(url)); springCtx.refresh(); } catch (BeansException e) { if (X.hasCause(e, ClassNotFoundException.class)) throw new IgniteCheckedException("Failed to instantiate Spring XML application context " + "(make sure all classes used in Spring configuration are present at CLASSPATH) " + "[springUrl=" + url + ']', e); else throw new IgniteCheckedException("Failed to instantiate Spring XML application context [springUrl=" + url + ", err=" + e.getMessage() + ']', e); } return springCtx; }
From source file:org.apache.ignite.internal.util.spring.IgniteSpringHelperImpl.java
/** * Prepares Spring context./*w w w. j a va 2 s . c o m*/ * * @param excludedProps Properties to be excluded. * @return application context. */ private static GenericApplicationContext prepareSpringContext(final String... excludedProps) { GenericApplicationContext springCtx = new GenericApplicationContext(); if (excludedProps.length > 0) { final List<String> excludedPropsList = Arrays.asList(excludedProps); BeanFactoryPostProcessor postProc = new BeanFactoryPostProcessor() { /** * @param def Registered BeanDefinition. * @throws BeansException in case of errors. */ private void processNested(BeanDefinition def) throws BeansException { Iterator<PropertyValue> iterVals = def.getPropertyValues().getPropertyValueList().iterator(); while (iterVals.hasNext()) { PropertyValue val = iterVals.next(); if (excludedPropsList.contains(val.getName())) { iterVals.remove(); continue; } if (val.getValue() instanceof Iterable) { Iterator iterNested = ((Iterable) val.getValue()).iterator(); while (iterNested.hasNext()) { Object item = iterNested.next(); if (item instanceof BeanDefinitionHolder) { BeanDefinitionHolder h = (BeanDefinitionHolder) item; try { if (h.getBeanDefinition().getBeanClassName() != null) Class.forName(h.getBeanDefinition().getBeanClassName()); processNested(h.getBeanDefinition()); } catch (ClassNotFoundException ignored) { iterNested.remove(); } } } } } } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { for (String beanName : beanFactory.getBeanDefinitionNames()) { try { BeanDefinition def = beanFactory.getBeanDefinition(beanName); if (def.getBeanClassName() != null) Class.forName(def.getBeanClassName()); processNested(def); } catch (ClassNotFoundException ignored) { ((BeanDefinitionRegistry) beanFactory).removeBeanDefinition(beanName); } } } }; springCtx.addBeanFactoryPostProcessor(postProc); } return springCtx; }
From source file:org.apache.synapse.mediators.spring.SpringMediator.java
private synchronized void buildAppContext(MessageContext synCtx) { log.debug("Creating Spring ApplicationContext from property key : " + configKey); GenericApplicationContext appContext = new GenericApplicationContext(); XmlBeanDefinitionReader xbdr = new XmlBeanDefinitionReader(appContext); xbdr.setValidating(false);//www. ja v a 2s . c o m xbdr.loadBeanDefinitions(new InputStreamResource( Util.getStreamSource(synCtx.getConfiguration().getProperty(configKey)).getInputStream())); appContext.refresh(); this.appContext = appContext; }
From source file:org.gridgain.grid.GridFactory.java
/** * Starts all grids specified within given Spring XML configuration file URL. If grid with given name * is already started, then exception is thrown. In this case all instances that may * have been started so far will be stopped too. * <p>//ww w. j a v a 2s . com * Usually Spring XML configuration file will contain only one Grid definition. Note that * Grid configuration bean(s) is retrieved form configuration file by type, so the name of * the Grid configuration bean is ignored. * * @param springCfgUrl Spring XML configuration file URL. This cannot be {@code null}. * @param ctx Optional Spring application context. * @return Started grid. If Spring configuration contains multiple grid instances, * then the 1st found instance is returned. * @throws GridException If grid could not be started or configuration * read. This exception will be thrown also if grid with given name has already * been started or Spring XML configuration file is invalid. */ // Warning is due to Spring. public static Grid start(URL springCfgUrl, @Nullable ApplicationContext ctx) throws GridException { A.notNull(springCfgUrl, "springCfgUrl"); boolean isLog4jUsed = GridFactory.class.getClassLoader() .getResource("org/apache/log4j/Appender.class") != null; Object rootLog = null; Object nullApp = null; if (isLog4jUsed) try { // Add no-op logger to remove no-appender warning. Class logCls = Class.forName("org.apache.log4j.Logger"); rootLog = logCls.getMethod("getRootLogger").invoke(logCls); nullApp = Class.forName("org.apache.log4j.varia.NullAppender").newInstance(); Class appCls = Class.forName("org.apache.log4j.Appender"); rootLog.getClass().getMethod("addAppender", appCls).invoke(rootLog, nullApp); } catch (Exception e) { throw new GridException("Failed to add no-op logger for Log4j.", e); } GenericApplicationContext springCtx; try { springCtx = new GenericApplicationContext(); new XmlBeanDefinitionReader(springCtx).loadBeanDefinitions(new UrlResource(springCfgUrl)); springCtx.refresh(); } catch (BeansException e) { throw new GridException("Failed to instantiate Spring XML application context [springUrl=" + springCfgUrl + ", err=" + e.getMessage() + ']', e); } Map<String, GridConfiguration> cfgMap; try { cfgMap = springCtx.getBeansOfType(GridConfiguration.class); } catch (BeansException e) { throw new GridException( "Failed to instantiate bean [type=" + GridConfiguration.class + ", err=" + e.getMessage() + ']', e); } if (cfgMap == null) throw new GridException("Failed to find a single grid factory configuration in: " + springCfgUrl); if (isLog4jUsed) { try { // Remove previously added no-op logger. Class appenderCls = Class.forName("org.apache.log4j.Appender"); rootLog.getClass().getMethod("removeAppender", appenderCls).invoke(rootLog, nullApp); } catch (Exception e) { throw new GridException("Failed to remove previously added no-op logger for Log4j.", e); } } if (cfgMap.isEmpty()) throw new GridException("Can't find grid factory configuration in: " + springCfgUrl); List<GridNamedInstance> grids = new ArrayList<GridNamedInstance>(cfgMap.size()); try { for (GridConfiguration cfg : cfgMap.values()) { assert cfg != null; // Use either user defined context or our one. GridNamedInstance grid = start0(cfg, ctx == null ? springCtx : ctx); // Add it if it was not stopped during startup. if (grid != null) grids.add(grid); } } catch (GridException e) { // Stop all instances started so far. for (GridNamedInstance grid : grids) { try { grid.stop(true, false); } catch (Exception e1) { U.error(grid.log, "Error when stopping grid: " + grid, e1); } } throw e; } // Return the first grid started. GridNamedInstance res = !grids.isEmpty() ? grids.get(0) : null; return res != null ? res.grid() : null; }
From source file:org.gridgain.grid.kernal.processors.spring.GridSpringProcessorImpl.java
/** {@inheritDoc} */ @Override//from w w w. ja v a2 s .com 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 w w . java2s . co m*/ */ 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 w w w . ja v a 2 s .co m*/ * @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 2s .c o m*/ 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.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 . j av a2s . 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); } }