List of usage examples for org.springframework.context.support GenericApplicationContext setClassLoader
@Override public void setClassLoader(@Nullable ClassLoader classLoader)
From source file:grails.spring.BeanBuilder.java
/** * Register a set of beans with the given bean registry. Most * application contexts are bean registries. *///from w ww. j av a2s .c om public void registerBeans(BeanDefinitionRegistry registry) { finalizeDeferredProperties(); if (registry instanceof GenericApplicationContext) { GenericApplicationContext ctx = (GenericApplicationContext) registry; ctx.setClassLoader(classLoader); ctx.getBeanFactory().setBeanClassLoader(classLoader); } springConfig.registerBeansWithRegistry(registry); }
From source file:org.craftercms.engine.service.context.SiteContextFactory.java
protected ConfigurableApplicationContext getApplicationContext(SiteContext siteContext, URLClassLoader classLoader, HierarchicalConfiguration config, String[] applicationContextPaths, ResourceLoader resourceLoader) { try {//from w w w. j a v a 2s. com List<Resource> resources = new ArrayList<>(); for (String path : applicationContextPaths) { Resource resource = resourceLoader.getResource(path); if (resource.exists()) { resources.add(resource); } } if (CollectionUtils.isNotEmpty(resources)) { String siteName = siteContext.getSiteName(); logger.info("--------------------------------------------------"); logger.info("<Loading application context for site: " + siteName + ">"); logger.info("--------------------------------------------------"); GenericApplicationContext appContext = new GenericApplicationContext(mainApplicationContext); appContext.setClassLoader(classLoader); if (config != null) { MutablePropertySources propertySources = appContext.getEnvironment().getPropertySources(); propertySources.addFirst(new ApacheCommonsConfiguration2PropertySource("siteConfig", config)); } XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(appContext); reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD); for (Resource resource : resources) { reader.loadBeanDefinitions(resource); } appContext.refresh(); logger.info("--------------------------------------------------"); logger.info("</Loading application context for site: " + siteName + ">"); logger.info("--------------------------------------------------"); return appContext; } else { return null; } } catch (Exception e) { throw new SiteContextCreationException( "Unable to load application context for site '" + siteContext.getSiteName() + "'", e); } }
From source file:org.jahia.services.render.webflow.WebflowDispatcherScript.java
/** * Execute the script and return the result as a string * * @param resource resource to display//from w w w .ja v a 2s. co m * @param context * @return the rendered resource * @throws org.jahia.services.render.RenderException * */ public String execute(Resource resource, RenderContext context) throws RenderException { final View view = getView(); if (view == null) { throw new RenderException("View not found for : " + resource); } else { if (logger.isDebugEnabled()) { logger.debug("View '" + view + "' resolved for resource: " + resource); } } String identifier; try { identifier = resource.getNode().getIdentifier(); } catch (RepositoryException e) { throw new RenderException(e); } String identifierNoDashes = StringUtils.replace(identifier, "-", "_"); if (!view.getKey().equals("default")) { identifierNoDashes += "__" + view.getKey(); } HttpServletRequest request; HttpServletResponse response = context.getResponse(); @SuppressWarnings("unchecked") final Map<String, List<String>> parameters = (Map<String, List<String>>) context.getRequest() .getAttribute("actionParameters"); if (xssFilteringEnabled && parameters != null) { final Map<String, String[]> m = Maps.transformEntries(parameters, new Maps.EntryTransformer<String, List<String>, String[]>() { @Override public String[] transformEntry(@Nullable String key, @Nullable List<String> value) { return value != null ? value.toArray(new String[value.size()]) : null; } }); request = new WebflowHttpServletRequestWrapper(context.getRequest(), m, identifierNoDashes); } else { request = new WebflowHttpServletRequestWrapper(context.getRequest(), new HashMap<>(context.getRequest().getParameterMap()), identifierNoDashes); } String s = (String) request.getSession().getAttribute("webflowResponse" + identifierNoDashes); if (s != null) { request.getSession().removeAttribute("webflowResponse" + identifierNoDashes); return s; } // skip aggregation for potentials fragments under the webflow boolean aggregationSkippedForWebflow = false; if (!AggregateFilter.skipAggregation(context.getRequest())) { aggregationSkippedForWebflow = true; context.getRequest().setAttribute(AggregateFilter.SKIP_AGGREGATION, true); } flowPath = MODULE_PREFIX_PATTERN.matcher(view.getPath()).replaceFirst(""); RequestDispatcher rd = request.getRequestDispatcher("/flow/" + flowPath); Object oldModule = request.getAttribute("currentModule"); request.setAttribute("currentModule", view.getModule()); if (logger.isDebugEnabled()) { dumpRequestAttributes(request); } StringResponseWrapper responseWrapper = new StringResponseWrapper(response); try { FlowDefinitionRegistry reg = ((FlowDefinitionRegistry) view.getModule().getContext() .getBean("jahiaFlowRegistry")); final GenericApplicationContext applicationContext = (GenericApplicationContext) reg .getFlowDefinition(flowPath).getApplicationContext(); applicationContext.setClassLoader(view.getModule().getClassLoader()); applicationContext.setResourceLoader(new ResourceLoader() { @Override public org.springframework.core.io.Resource getResource(String location) { return applicationContext.getParent().getResource("/" + flowPath + "/" + location); } @Override public ClassLoader getClassLoader() { return view.getModule().getClassLoader(); } }); rd.include(request, responseWrapper); String redirect = responseWrapper.getRedirect(); if (redirect != null && context.getRedirect() == null) { // if we have an absolute redirect, set it and move on if (redirect.startsWith("http:/") || redirect.startsWith("https://")) { context.setRedirect(responseWrapper.getRedirect()); } else { while (redirect != null) { final String qs = StringUtils.substringAfter(responseWrapper.getRedirect(), "?"); final Map<String, String[]> params = new HashMap<String, String[]>(); if (!StringUtils.isEmpty(qs)) { params.put("webflowexecution" + identifierNoDashes, new String[] { StringUtils .substringAfterLast(qs, "webflowexecution" + identifierNoDashes + "=") }); } HttpServletRequestWrapper requestWrapper = new HttpServletRequestWrapper(request) { @Override public String getMethod() { return "GET"; } @SuppressWarnings("rawtypes") @Override public Map getParameterMap() { return params; } @Override public String getParameter(String name) { return params.containsKey(name) ? params.get(name)[0] : null; } @Override public Enumeration getParameterNames() { return new Vector(params.keySet()).elements(); } @Override public String[] getParameterValues(String name) { return params.get(name); } @Override public Object getAttribute(String name) { if (WebUtils.FORWARD_QUERY_STRING_ATTRIBUTE.equals(name)) { return qs; } return super.getAttribute(name); } @Override public String getQueryString() { return qs; } }; rd = requestWrapper.getRequestDispatcher("/flow/" + flowPath + "?" + qs); responseWrapper = new StringResponseWrapper(response); rd.include(requestWrapper, responseWrapper); String oldRedirect = redirect; redirect = responseWrapper.getRedirect(); if (redirect != null) { // if we have an absolute redirect, exit the loop if (redirect.startsWith("http://") || redirect.startsWith("https://")) { context.setRedirect(redirect); break; } } else if (request.getMethod().equals("POST")) { // set the redirect to the last non-null one request.getSession().setAttribute("webflowResponse" + identifierNoDashes, responseWrapper.getString()); context.setRedirect(oldRedirect); } } } } } catch (ServletException e) { throw new RenderException(e.getRootCause() != null ? e.getRootCause() : e); } catch (IOException e) { throw new RenderException(e); } finally { request.setAttribute("currentModule", oldModule); } try { if (aggregationSkippedForWebflow) { request.removeAttribute(AggregateFilter.SKIP_AGGREGATION); } return responseWrapper.getString(); } catch (IOException e) { throw new RenderException(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 {//from w ww . j a v 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); } }
From source file:org.opennms.install.Installer.java
/** * <p>install</p>//from ww w . j a va2 s . co m * * @param argv an array of {@link java.lang.String} objects. * @throws java.lang.Exception if any. */ public void install(final String[] argv) throws Exception { printHeader(); loadProperties(); parseArguments(argv); final boolean doDatabase = (m_update_database || m_do_inserts || m_update_iplike || m_update_unicode || m_fix_constraint); if (!doDatabase && m_tomcat_conf == null && !m_install_webapp && m_library_search_path == null) { usage(options, m_commandLine, "Nothing to do. Use -h for help.", null); System.exit(1); } if (doDatabase) { final File cfgFile = ConfigFileConstants .getFile(ConfigFileConstants.OPENNMS_DATASOURCE_CONFIG_FILE_NAME); InputStream is = new FileInputStream(cfgFile); final JdbcDataSource adminDsConfig = new DataSourceConfigurationFactory(is) .getJdbcDataSource(ADMIN_DATA_SOURCE_NAME); final DataSource adminDs = new SimpleDataSource(adminDsConfig); is.close(); is = new FileInputStream(cfgFile); final JdbcDataSource dsConfig = new DataSourceConfigurationFactory(is) .getJdbcDataSource(OPENNMS_DATA_SOURCE_NAME); final DataSource ds = new SimpleDataSource(dsConfig); is.close(); m_installerDb.setForce(m_force); m_installerDb.setIgnoreNotNull(m_ignore_not_null); m_installerDb.setNoRevert(m_do_not_revert); m_installerDb.setAdminDataSource(adminDs); m_installerDb.setPostgresOpennmsUser(dsConfig.getUserName()); m_installerDb.setDataSource(ds); m_installerDb.setDatabaseName(dsConfig.getDatabaseName()); m_migrator.setDataSource(ds); m_migrator.setAdminDataSource(adminDs); m_migrator.setValidateDatabaseVersion(!m_ignore_database_version); m_migration.setDatabaseName(dsConfig.getDatabaseName()); m_migration.setSchemaName(dsConfig.getSchemaName()); m_migration.setAdminUser(adminDsConfig.getUserName()); m_migration.setAdminPassword(adminDsConfig.getPassword()); m_migration.setDatabaseUser(dsConfig.getUserName()); m_migration.setDatabasePassword(dsConfig.getPassword()); m_migration.setChangeLog("changelog.xml"); } checkIPv6(); /* * Make sure we can execute the rrdtool binary when the * JniRrdStrategy is enabled. */ boolean using_jni_rrd_strategy = System.getProperty("org.opennms.rrd.strategyClass", "") .contains("JniRrdStrategy"); if (using_jni_rrd_strategy) { File rrd_binary = new File(System.getProperty("rrd.binary")); if (!rrd_binary.canExecute()) { throw new Exception("Cannot execute the rrdtool binary '" + rrd_binary.getAbsolutePath() + "' required by the current RRD strategy. Update the rrd.binary field in opennms.properties appropriately."); } } /* * make sure we can load the ICMP library before we go any farther */ if (!Boolean.getBoolean("skip-native")) { String icmp_path = findLibrary("jicmp", m_library_search_path, false); String icmp6_path = findLibrary("jicmp6", m_library_search_path, false); String jrrd_path = findLibrary("jrrd", m_library_search_path, false); String jrrd2_path = findLibrary("jrrd2", m_library_search_path, false); writeLibraryConfig(icmp_path, icmp6_path, jrrd_path, jrrd2_path); } /* * Everything needs to use the administrative data source until we * verify that the opennms database is created below (and where we * create it if it doesn't already exist). */ verifyFilesAndDirectories(); if (m_install_webapp) { checkWebappOldOpennmsDir(); checkServerXmlOldOpennmsContext(); } if (m_update_database || m_fix_constraint) { // OLDINSTALL m_installerDb.readTables(); } m_installerDb.disconnect(); if (doDatabase) { m_migrator.validateDatabaseVersion(); System.out.println( String.format("* using '%s' as the PostgreSQL user for OpenNMS", m_migration.getAdminUser())); System.out.println(String.format("* using '%s' as the PostgreSQL database name for OpenNMS", m_migration.getDatabaseName())); if (m_migration.getSchemaName() != null) { System.out.println(String.format("* using '%s' as the PostgreSQL schema name for OpenNMS", m_migration.getSchemaName())); } } if (m_update_database) { m_migrator.prepareDatabase(m_migration); } if (doDatabase) { m_installerDb.checkUnicode(); } handleConfigurationChanges(); final GenericApplicationContext context = new GenericApplicationContext(); context.setClassLoader(Bootstrap.loadClasses(new File(m_opennms_home), true)); if (m_update_database) { m_installerDb.databaseSetUser(); m_installerDb.disconnect(); for (final Resource resource : context.getResources("classpath*:/changelog.xml")) { System.out.println("- Running migration for changelog: " + resource.getDescription()); m_migration.setAccessor(new ExistingResourceAccessor(resource)); m_migrator.migrate(m_migration); } } if (m_update_unicode) { System.out.println("WARNING: the -U option is deprecated, it does nothing now"); } if (m_do_vacuum) { m_installerDb.vacuumDatabase(m_do_full_vacuum); } if (m_install_webapp) { installWebApp(); } if (m_tomcat_conf != null) { updateTomcatConf(); } if (m_update_iplike) { m_installerDb.updateIplike(); } if (m_update_database && m_remove_database) { m_installerDb.disconnect(); m_installerDb.databaseRemoveDB(); } if (doDatabase) { m_installerDb.disconnect(); } if (m_update_database) { createConfiguredFile(); } System.out.println(); System.out.println("Installer completed successfully!"); if (!m_skip_upgrade_tools) { System.setProperty("opennms.manager.class", "org.opennms.upgrade.support.Upgrade"); Bootstrap.main(new String[] {}); } context.close(); }
From source file:org.pentaho.platform.plugin.services.pluginmgr.DefaultPluginManager.java
/** * Initializes a bean factory for serving up instance of plugin classes. * * @return an instance of the factory that allows callers to continue to define more beans on it programmatically */// www . j a v a 2 s. c o m protected void initializeBeanFactory(final IPlatformPlugin plugin, final ClassLoader loader) throws PlatformPluginRegistrationException { if (!(loader instanceof PluginClassLoader)) { logger.warn( "Can't determine plugin dir to load spring file because classloader is not of type PluginClassLoader. " //$NON-NLS-1$ + "This is since we are probably in a unit test"); //$NON-NLS-1$ return; } // // Get the native factory (the factory that comes preconfigured via either Spring bean files or via JUnit test // BeanFactory nativeBeanFactory = getNativeBeanFactory(plugin, loader); // // Now create the definable factory for accepting old style bean definitions from IPluginProvider // GenericApplicationContext beanFactory = null; if (nativeBeanFactory != null && nativeBeanFactory instanceof GenericApplicationContext) { beanFactory = (GenericApplicationContext) nativeBeanFactory; } else { beanFactory = new GenericApplicationContext(); beanFactory.setClassLoader(loader); beanFactory.getBeanFactory().setBeanClassLoader(loader); if (nativeBeanFactory != null) { beanFactory.getBeanFactory().setParentBeanFactory(nativeBeanFactory); } } beanFactoryMap.put(plugin.getId(), beanFactory); // // Register any beans defined via the pluginProvider // // we do not have to synchronize on the bean set here because the // map that backs the set is never modified after the plugin has // been made available to the plugin manager for (PluginBeanDefinition def : plugin.getBeans()) { // register by classname if id is null def.setBeanId((def.getBeanId() == null) ? def.getClassname() : def.getBeanId()); assertUnique(plugin.getId(), def.getBeanId()); // defining plugin beans the old way through the plugin provider ifc supports only prototype scope BeanDefinition beanDef = BeanDefinitionBuilder.rootBeanDefinition(def.getClassname()) .setScope(BeanDefinition.SCOPE_PROTOTYPE).getBeanDefinition(); beanFactory.registerBeanDefinition(def.getBeanId(), beanDef); } StandaloneSpringPentahoObjectFactory pentahoFactory = new StandaloneSpringPentahoObjectFactory( "Plugin Factory ( " + plugin.getId() + " )"); pentahoFactory.init(null, beanFactory); }
From source file:org.springframework.context.groovy.GroovyBeanDefinitionReader.java
/** * Register a set of beans with the given bean registry. Most * application contexts are bean registries. */// w w w .j a va2s. co m public void registerBeans(BeanDefinitionRegistry registry) { finalizeDeferredProperties(); if (registry instanceof GenericApplicationContext) { GenericApplicationContext ctx = (GenericApplicationContext) registry; ctx.setClassLoader(this.classLoader); ctx.getBeanFactory().setBeanClassLoader(this.classLoader); } springConfig.registerBeansWithRegistry(registry); }