List of usage examples for org.springframework.context.support ClassPathXmlApplicationContext setParent
@Override public void setParent(@Nullable ApplicationContext parent)
From source file:gemlite.shell.service.batch.ImportService.java
/** * // w w w . ja v a 2 s .c om * @param template * @param file * @param delimiter * @param quote * @param skipable * @param columns * @param region * @param table * @param encoding * @param linesToSkip * @param dbdriver * //????? * @param dburl * @param dbuser * @param dbpsw * @param sortKey * @param where * @param pageSize * @param fetchSize * @return */ public boolean defineJob(String template, String file, String delimiter, String quote, boolean skipable, String columns, String region, String table, String encoding, int linesToSkip, String dbdriver, String dburl, String dbuser, String dbpsw, String sortKey, String where, int pageSize, int fetchSize) { BatchParameter param = new BatchParameter(template, file, delimiter, quote, skipable, columns, region, table, encoding, linesToSkip, sortKey, where, pageSize, fetchSize); if (!validParameters(param)) return false; String cacheKey = region + template; try { // ??,?db?? if (StringUtils.equals(BatchTemplateTypes.jdbcPartition.getValue(), param.getTemplate()) || StringUtils.equals(BatchTemplateTypes.jdbcpaging.getValue(), param.getTemplate())) { // ?? setDbParameter(dbdriver, dburl, dbuser, dbpsw); saveDbConfig(dbdriver, dburl, dbuser, dbpsw); } // partition,?table if (StringUtils.equals(BatchTemplateTypes.jdbcPartition.getValue(), param.getTemplate())) { DataSource dataSource = null; DatabaseType type = null; // ?? if (jobItems.containsKey(cacheKey)) { dataSource = (DataSource) (jobItems.get(cacheKey).jobContext.getBean("jdbcDataSource")); type = DatabaseType.fromMetaData(dataSource); } else { // ,??? ClassPathXmlApplicationContext jdbc = Util.initContext(true, "batch/job-context.xml", "batch/import-db-jdbc.xml"); dataSource = (DataSource) jdbc.getBean("jdbcDataSource"); type = DatabaseType.fromMetaData(dataSource); jdbc.close(); } if (converters.containsKey(type)) param.setTable(converters.get(type).converte(table, sortKey)); } String jobXMLFile = generator.generateFileJob(region, param); ClassPathXmlApplicationContext jobContext = null; if (StringUtils.equals("file", template)) { jobContext = Util.initContext(false, "batch/job-context.xml", jobXMLFile); } else { // ????db? jobContext = Util.initContext(false, "batch/job-context.xml", "batch/import-db-jdbc.xml", jobXMLFile); } jobContext.setParent(batchContext); jobContext.refresh(); if (LogUtil.getCoreLog().isDebugEnabled()) LogUtil.getCoreLog().debug("Job:" + region + " define success."); JobItem item = new JobItem(); item.attributes = param; item.job = jobContext.getBean(Job.class); item.jobContent = jobXMLFile; item.jobContext = jobContext; jobItems.put(cacheKey, item); return true; } catch (Exception e) { LogUtil.getCoreLog().info("Job define error.", e); throw new GemliteException(e); } }
From source file:org.pentaho.pat.plugin.PatLifeCycleListener.java
public void loaded() throws PluginLifecycleException { ClassLoader origContextClassloader = Thread.currentThread().getContextClassLoader(); IServiceManager serviceManager = (IServiceManager) PentahoSystem.get(IServiceManager.class, PentahoSessionHolder.getSession()); try {//from ww w .j a va 2s. c o m sessionBean = (SessionServlet) serviceManager.getServiceBean("gwt", "session.rpc"); //$NON-NLS-1$ queryBean = (QueryServlet) serviceManager.getServiceBean("gwt", "query.rpc"); //$NON-NLS-1$ discoveryBean = (DiscoveryServlet) serviceManager.getServiceBean("gwt", "discovery.rpc"); //$NON-NLS-1$ platformBean = (PlatformServlet) serviceManager.getServiceBean("gwt", "platform.rpc"); //$NON-NLS-1$ final IPluginManager pluginManager = (IPluginManager) PentahoSystem.get(IPluginManager.class, PentahoSessionHolder.getSession()); final PluginClassLoader pluginClassloader = (PluginClassLoader) pluginManager .getClassLoader(PAT_PLUGIN_NAME); final String hibernateConfigurationFile = PentahoSystem .getSystemSetting("hibernate/hibernate-settings.xml", "settings/config-file", null); //$NON-NLS-1$ final String pentahoHibConfigPath = PentahoSystem.getApplicationContext() .getSolutionPath(hibernateConfigurationFile); if (pluginClassloader == null) throw new ServiceException(Messages.getString("LifeCycleListener.NoPluginClassloader")); //$NON-NLS-1$ Thread.currentThread().setContextClassLoader(pluginClassloader); final URL contextUrl = pluginClassloader.getResource(PAT_APP_CONTEXT); final URL patHibConfigUrl = pluginClassloader.getResource(PAT_HIBERNATE_CONFIG); final URL patPluginPropertiesUrl = pluginClassloader.getResource(PAT_PLUGIN_PROPERTIES); if (patHibConfigUrl == null) throw new ServiceException("File not found: PAT Hibernate Config : " + PAT_HIBERNATE_CONFIG); else LOG.debug(PAT_PLUGIN_NAME + ": PAT Hibernate Config:" + patHibConfigUrl.toString()); if (patPluginPropertiesUrl == null) throw new ServiceException("File not found: PAT Plugin properties : " + PAT_PLUGIN_PROPERTIES); else LOG.debug(PAT_PLUGIN_NAME + ": PAT Plugin Properties:" + patPluginPropertiesUrl.toString()); if (contextUrl != null) { String appContextUrl = contextUrl.toString(); final ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext( new String[] { appContextUrl }, false); applicationContext.setClassLoader(pluginClassloader); applicationContext.setConfigLocation(appContextUrl); applicationContext.setAllowBeanDefinitionOverriding(true); final Configuration pentahoHibConfig = new Configuration(); pentahoHibConfig.configure(new File(pentahoHibConfigPath)); final AnnotationConfiguration patHibConfig = new AnnotationConfiguration(); patHibConfig.configure(patHibConfigUrl); Properties properties = new Properties(); properties.load(pluginClassloader.getResourceAsStream(PAT_PLUGIN_PROPERTIES)); String hibernateDialectCfg = (String) properties.get("pat.plugin.datasource.hibernate.dialect"); String hibernateDialect = null; if (StringUtils.isNotBlank(hibernateDialectCfg)) { if (hibernateDialectCfg.equals("auto")) { hibernateDialect = pentahoHibConfig.getProperty("dialect"); } else { hibernateDialect = hibernateDialectCfg; } } if (StringUtils.isNotBlank(hibernateDialect)) { patHibConfig.setProperty("hibernate.dialect", hibernateDialect); LOG.info(PAT_PLUGIN_NAME + " : using hibernate dialect: " + hibernateDialect); } String dataSourceType = (String) properties.get("pat.plugin.datasource.type"); String datasourceResource = null; if (StringUtils.isNotEmpty(dataSourceType) && dataSourceType.equals("jdbc")) { datasourceResource = PAT_DATASOURCE_JDBC; LOG.info(PAT_PLUGIN_NAME + " : using JDBC connection"); } if (StringUtils.isNotEmpty(dataSourceType) && dataSourceType.equals("jndi")) { datasourceResource = PAT_DATASOURCE_JNDI; LOG.info(PAT_PLUGIN_NAME + " : using JNDI : " + (String) properties.get("jndi.name")); } XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource(datasourceResource)); PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer(); cfg.setLocation(new ClassPathResource(PAT_PLUGIN_PROPERTIES)); cfg.postProcessBeanFactory(factory); XmlBeanFactory bfSession = new XmlBeanFactory(new ClassPathResource(PAT_SESSIONFACTORY), factory); PropertyPlaceholderConfigurer cfgSession = new PropertyPlaceholderConfigurer(); cfgSession.setProperties(patHibConfig.getProperties()); cfgSession.postProcessBeanFactory(bfSession); ClassPathXmlApplicationContext tmpCtxt = new ClassPathXmlApplicationContext(); tmpCtxt.refresh(); DefaultListableBeanFactory tmpBf = (DefaultListableBeanFactory) tmpCtxt.getBeanFactory(); tmpBf.setParentBeanFactory(bfSession); applicationContext.setClassLoader(pluginClassloader); applicationContext.setParent(tmpCtxt); applicationContext.refresh(); sessionBean.setStandalone(true); SessionServlet.setApplicationContext(applicationContext); sessionBean.init(); queryBean.setStandalone(true); QueryServlet.setApplicationContext(applicationContext); queryBean.init(); discoveryBean.setStandalone(true); DiscoveryServlet.setApplicationContext(applicationContext); discoveryBean.init(); platformBean.setStandalone(true); PlatformServlet.setApplicationContext(applicationContext); platformBean.init(); injectPentahoXmlaUrl(); } else { throw new Exception(Messages.getString("LifeCycleListener.AppContextNotFound")); } } catch (ServiceException e1) { LOG.error(e1.getMessage(), e1); } catch (ServletException e) { LOG.error(e.getMessage(), e); } catch (Exception e) { LOG.error(e.getMessage(), e); } finally { // reset the classloader of the current thread if (origContextClassloader != null) { Thread.currentThread().setContextClassLoader(origContextClassloader); } } }
From source file:org.alfresco.bm.test.TestRun.java
/** * Called to ensure that the application context is started. * <p/>/*from www . j av a2s . c o m*/ * Note that we only pull out the test and test run names at this point so that we don't end up * using stale data. */ private synchronized void start() { DBObject runObj = getRunObj(true); if (runObj == null) { // Nothing much we can do here return; } // Check the application context if (testRunCtx != null) { // There is nothing to do, the context is already available return; } // INFO logging as this is a critical part of the whole application if (logger.isInfoEnabled()) { logger.info("Starting test run application context: " + runObj); } ObjectId testObjId = (ObjectId) runObj.get(FIELD_TEST); ObjectId runObjId = (ObjectId) runObj.get(FIELD_ID); String run = (String) runObj.get(FIELD_NAME); // We need to build the test run FQN out of the test run details DBObject testObj = testDAO.getTest(testObjId, false); if (testObj == null) { logger.warn("The test associated with the test run has been removed: " + runObj); logger.warn("The test run will be stopped and deleted: " + id); stop(); testDAO.deleteTestRun(id); return; } String test = (String) testObj.get(FIELD_NAME); String release = (String) testObj.get(FIELD_RELEASE); Integer schema = (Integer) testObj.get(FIELD_SCHEMA); String testRunFqn = test + "." + run; // Extract the current properties for the run Set<String> propsToMask = new HashSet<String>(7); Properties testRunProps = new Properties(); { testRunProps.put(PROP_DRIVER_ID, driverId); testRunProps.put(PROP_TEST, test); testRunProps.put(PROP_TEST_RUN, run); testRunProps.put(PROP_TEST_RUN_ID, id.toString()); testRunProps.put(PROP_TEST_RUN_FQN, testRunFqn); BasicDBList propObjs = (BasicDBList) runObj.get(FIELD_PROPERTIES); for (Object obj : propObjs) { DBObject propObj = (DBObject) obj; String propName = (String) propObj.get(FIELD_NAME); String propDef = (String) propObj.get(FIELD_DEFAULT); String propValue = (String) propObj.get(FIELD_VALUE); if (propValue == null) { propValue = propDef; } testRunProps.put(propName, propValue); // Check on the masking for later reporting boolean mask = Boolean.parseBoolean((String) propObj.get(FIELD_MASK)); if (mask) { propsToMask.add(propName); } } } // Create the child application context WITHOUT AUTOSTART // TODO: This is hard coded to "config/spring/test-context.xml". It should be one of the // test definition properties and have the same as default. ClassPathXmlApplicationContext testRunCtx = new ClassPathXmlApplicationContext( new String[] { PATH_TEST_CONTEXT }, false); // When running stand-alone, there might not be a parent context if (parentCtx != null) { testRunCtx.setParent(parentCtx); } // Push cluster properties into the context (must be done AFTER setting parent context) ConfigurableEnvironment ctxEnv = testRunCtx.getEnvironment(); ctxEnv.getPropertySources().addFirst(new PropertiesPropertySource("run-props", testRunProps)); ctxEnv.getPropertySources().addFirst(new PropertiesPropertySource("system-props", System.getProperties())); // Complete logging of what is going to be used for the test if (logger.isInfoEnabled()) { String nl = "\n"; StringBuilder sb = new StringBuilder(1024); sb.append("Test run application context starting: ").append(nl).append(" Run ID: ").append(id) .append(nl).append(" Test Name: ").append(test).append(nl).append(" Run Name: ") .append(run).append(nl).append(" Driver ID: ").append(driverId).append(nl) .append(" Release: ").append(release).append(nl).append(" Schema: ") .append(schema).append(nl).append(" Test Run Properties: ").append(nl); for (Object propNameObj : testRunProps.keySet()) { String propName = (String) propNameObj; String propValue = testRunProps.getProperty(propName); if (propsToMask.contains(propName) || propName.toLowerCase().contains("username") || propName.toLowerCase().contains("password")) { propValue = MASK; } sb.append(" ").append(propName).append("=").append(propValue).append(nl); } sb.append(" System Properties: ").append(nl); for (Object propNameObj : System.getProperties().keySet()) { String propName = (String) propNameObj; String propValue = System.getProperty(propName); if (propsToMask.contains(propName) || propName.toLowerCase().contains("username") || propName.toLowerCase().contains("password")) { propValue = MASK; } sb.append(" ").append(propName).append("=").append(propValue).append(nl); } logger.info(sb); } // Now refresh (to load beans) and start try { this.testRunCtx = testRunCtx; // 2015-08-04 fkbecker: store definitions first - for refresh() or start() may fail, too. this.test = test; this.run = run; this.release = release; this.schema = schema; testRunCtx.refresh(); testRunCtx.start(); // Make sure that the required components are present and of the correct type // There may be multiple beans of the type, so we have to use the specific bean name. @SuppressWarnings("unused") CompletionEstimator estimator = (CompletionEstimator) testRunCtx.getBean("completionEstimator"); @SuppressWarnings("unused") EventProcessor startEventProcessor = (EventProcessor) testRunCtx.getBean("event.start"); // Register the driver with the test run testDAO.addTestRunDriver(runObjId, driverId); // Log the successful startup logService.log(driverId, test, run, LogLevel.INFO, "Successful startup of test run '" + testRunFqn + "'."); } catch (Exception e) { /* Throwable root = ExceptionUtils.getRootCause(e); if (root != null && (root instanceof MongoException || root instanceof IOException)) { // 2015-08-04 fkbecker IOException also thrown by FTP file service if host not reachable ... // FIXME String msg1 = "Failed to start test run application '" + testRunFqn + "': " + e.getCause().getMessage(); //String msg2 = "Set the test run property '" + PROP_MONGO_TEST_HOST + "' (<server>:<port>) as required."; // We deal with this specifically as it's a simple case of not finding the MongoDB logger.error(msg1); //logger.error(msg2); logService.log(driverId, test, run, LogLevel.ERROR, msg1); //logService.log(driverId, test, run, LogLevel.ERROR, msg2); } else {*/ String stack = ExceptionUtils.getStackTrace(e); logger.error("Failed to start test run application '" + testRunFqn + "': ", e); String error = "Failed to start test run application '" + testRunFqn + ". \r\n" + stack; logService.log(driverId, test, run, LogLevel.ERROR, error); //} stop(); } }
From source file:org.entando.entando.plugins.jpcomponentinstaller.aps.system.services.installer.DefaultComponentInstaller.java
private ApplicationContext loadContext(String[] configLocations, URLClassLoader cl, String contextDisplayName, Properties properties) throws Exception { ServletContext servletContext = ((ConfigurableWebApplicationContext) this._applicationContext) .getServletContext();//from w ww . j a v a 2 s .co m //if plugin's classes have been loaded we can go on List<ClassPathXmlApplicationContext> ctxList = (List<ClassPathXmlApplicationContext>) servletContext .getAttribute("pluginsContextsList"); if (ctxList == null) { ctxList = new ArrayList<ClassPathXmlApplicationContext>(); servletContext.setAttribute("pluginsContextsList", ctxList); } ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader(); ClassPathXmlApplicationContext newContext = null; try { //create a new spring context with the classloader and the paths defined as parameter in pluginsInstallerContext.xml. //The new context is given the default webapplication context as its parent Thread.currentThread().setContextClassLoader(cl); newContext = new ClassPathXmlApplicationContext(); //ClassPathXmlApplicationContext newContext = new ClassPathXmlApplicationContext(configLocations, applicationContext); PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer(); configurer.setProperties(properties); newContext.addBeanFactoryPostProcessor(configurer); newContext.setClassLoader(cl); newContext.setParent(this._applicationContext); String[] configLocs = new String[] { "classpath:spring/restServerConfig.xml", "classpath:spring/baseSystemConfig.xml" }; newContext.setConfigLocations(configLocs); newContext.refresh(); BaseConfigManager baseConfigManager = (BaseConfigManager) ((ConfigurableWebApplicationContext) this._applicationContext) .getBean("BaseConfigManager"); baseConfigManager.init(); newContext.setConfigLocations(configLocations); newContext.refresh(); newContext.setDisplayName(contextDisplayName); ClassPathXmlApplicationContext currentCtx = (ClassPathXmlApplicationContext) this .getStoredContext(contextDisplayName); if (currentCtx != null) { currentCtx.close(); ctxList.remove(currentCtx); } ctxList.add(newContext); } catch (Exception e) { _logger.error("Unexpected error loading application context: " + e.getMessage()); e.printStackTrace(); throw e; } finally { Thread.currentThread().setContextClassLoader(currentClassLoader); } return newContext; }
From source file:org.springframework.batch.integration.x.RemoteFileToHadoopTests.java
@SuppressWarnings({ "unchecked", "rawtypes" }) @Before// w ww . j a v a 2 s .c om public void setup() throws Exception { byte[] bytes = "foobarbaz".getBytes(); // using this trick here by getting hadoop minicluster from main test // context and then using it to override 'hadoopConfiguration' bean // which is imported from ftphdfs.xml. ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(); ctx.setConfigLocations("org/springframework/batch/integration/x/RemoteFileToHadoopTests-context.xml", "org/springframework/batch/integration/x/miniclusterconfig.xml"); Properties properties = new Properties(); properties.setProperty("restartable", "false"); properties.setProperty("xd.config.home", "file:../../config"); properties.setProperty("partitionResultsTimeout", "3600000"); PropertiesPropertySource propertiesPropertySource = new PropertiesPropertySource("props", properties); ctx.getEnvironment().getPropertySources().addLast(propertiesPropertySource); ctx.setParent(context); ctx.refresh(); this.sessionFactory = ctx.getBean(SessionFactory.class); Session session = mock(Session.class); when(this.sessionFactory.getSession()).thenReturn(session); when(session.readRaw("/foo/bar.txt")).thenReturn(new ByteArrayInputStream(bytes)); when(session.readRaw("/foo/baz.txt")).thenReturn(new ByteArrayInputStream(bytes)); when(session.finalizeRaw()).thenReturn(true); Object[] fileList = new FTPFile[2]; FTPFile file = new FTPFile(); file.setName("bar.txt"); fileList[0] = file; file = new FTPFile(); file.setName("baz.txt"); fileList[1] = file; when(session.list("/foo/")).thenReturn(fileList); this.launcher = ctx.getBean(JobLauncher.class); this.job = ctx.getBean(Job.class); this.requestsOut = ctx.getBean("stepExecutionRequests.output", MessageChannel.class); this.requestsIn = ctx.getBean("stepExecutionRequests.input", MessageChannel.class); this.repliesOut = ctx.getBean("stepExecutionReplies.output", MessageChannel.class); this.repliesIn = ctx.getBean("stepExecutionReplies.input", MessageChannel.class); this.bus = new LocalMessageBus(); ((LocalMessageBus) this.bus).setApplicationContext(ctx); this.bus.bindRequestor("foo", this.requestsOut, this.repliesIn, null); this.bus.bindReplier("foo", this.requestsIn, this.repliesOut, null); }
From source file:org.springframework.integration.channel.DirectChannelTests.java
@Test // See INT-2434 public void testChannelCreationWithBeanDefinitionOverrideTrue() throws Exception { ClassPathXmlApplicationContext parentContext = new ClassPathXmlApplicationContext("parent-config.xml", this.getClass()); MessageChannel parentChannelA = parentContext.getBean("parentChannelA", MessageChannel.class); MessageChannel parentChannelB = parentContext.getBean("parentChannelB", MessageChannel.class); ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(); context.setAllowBeanDefinitionOverriding(false); context.setConfigLocations(//from w w w . j ava2 s. c o m new String[] { "classpath:org/springframework/integration/channel/channel-override-config.xml" }); context.setParent(parentContext); Method method = ReflectionUtils.findMethod(ClassPathXmlApplicationContext.class, "obtainFreshBeanFactory"); method.setAccessible(true); method.invoke(context); assertFalse(context.containsBean("channelA")); assertFalse(context.containsBean("channelB")); assertTrue(context.containsBean("channelC")); assertTrue(context.containsBean("channelD")); context.refresh(); PublishSubscribeChannel channelEarly = context.getBean("channelEarly", PublishSubscribeChannel.class); assertTrue(context.containsBean("channelA")); assertTrue(context.containsBean("channelB")); assertTrue(context.containsBean("channelC")); assertTrue(context.containsBean("channelD")); EventDrivenConsumer consumerA = context.getBean("serviceA", EventDrivenConsumer.class); assertEquals(context.getBean("channelA"), TestUtils.getPropertyValue(consumerA, "inputChannel")); assertEquals(context.getBean("channelB"), TestUtils.getPropertyValue(consumerA, "handler.outputChannel")); EventDrivenConsumer consumerB = context.getBean("serviceB", EventDrivenConsumer.class); assertEquals(context.getBean("channelB"), TestUtils.getPropertyValue(consumerB, "inputChannel")); assertEquals(context.getBean("channelC"), TestUtils.getPropertyValue(consumerB, "handler.outputChannel")); EventDrivenConsumer consumerC = context.getBean("serviceC", EventDrivenConsumer.class); assertEquals(context.getBean("channelC"), TestUtils.getPropertyValue(consumerC, "inputChannel")); assertEquals(context.getBean("channelD"), TestUtils.getPropertyValue(consumerC, "handler.outputChannel")); EventDrivenConsumer consumerD = context.getBean("serviceD", EventDrivenConsumer.class); assertEquals(parentChannelA, TestUtils.getPropertyValue(consumerD, "inputChannel")); assertEquals(parentChannelB, TestUtils.getPropertyValue(consumerD, "handler.outputChannel")); EventDrivenConsumer consumerE = context.getBean("serviceE", EventDrivenConsumer.class); assertEquals(parentChannelB, TestUtils.getPropertyValue(consumerE, "inputChannel")); EventDrivenConsumer consumerF = context.getBean("serviceF", EventDrivenConsumer.class); assertEquals(channelEarly, TestUtils.getPropertyValue(consumerF, "inputChannel")); }