List of usage examples for org.springframework.context.support ClassPathXmlApplicationContext getEnvironment
@Override
public ConfigurableEnvironment getEnvironment()
From source file:net.sf.gazpachoquest.extractor.dbunit.DBUnitDataExtractorRunner.java
public static void main(final String[] args) throws Exception { String dbEngine = "db_postgres"; logger.info("Extracting data from {} database in DBUnit format", dbEngine); ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(); ctx.getEnvironment().setActiveProfiles("postgres", dbEngine); ctx.refresh();//from w w w. j a va2 s .com ctx.setConfigLocations( new String[] { "dbunitextractor-datasource-context.xml", "dbunitextractor-context.xml" }); /*- ctx.getEnvironment().getPropertySources() .addLast(new ResourcePropertySource(String.format("classpath:/database/%s.properties", dbEngine))); */ ctx.refresh(); DBUnitDataExtractor extractor = (DBUnitDataExtractor) ctx.getBean("dbUnitDataExtractor"); extractor.extract(); ctx.close(); logger.info("Done successfully. Check your target directory"); }
From source file:cn.webank.ecif.index.server.EcifIndexServer.java
/** * @param args/*from w w w . java2 s .c o m*/ */ public static void main(String[] args) { final EcifIndexServer server = new EcifIndexServer(); // start spring context; final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(); context.getEnvironment().setActiveProfiles("product"); context.setConfigLocation("application.xml"); context.refresh(); context.start(); // thread pool construct ThreadPoolTaskExecutor taskThreadPool = context.getBean("taskExecutor", ThreadPoolTaskExecutor.class); server.setTaskThreadPool(taskThreadPool); ExecutorService fixedThreadPool = context.getBean("fixedTaskExecutor", ExecutorService.class); server.setSchedulerThreadPool(fixedThreadPool); EcifThreadFactory threadFactory = context.getBean("cn.webank.ecif.index.async.EcifThreadFactory", EcifThreadFactory.class); server.setThreadFactory(threadFactory); Properties props = context.getBean("ecifProperties", java.util.Properties.class); WeBankServiceDispatcher serviceDispatcher = context.getBean( "cn.webank.framework.biz.service.support.WeBankServiceDispatcher", WeBankServiceDispatcher.class); ReloadableResourceBundleMessageSource bundleMessageSource = context.getBean("messageSource", ReloadableResourceBundleMessageSource.class); String topics = props.getProperty("listener.topics"); String[] splits = topics.split(","); SolaceManager solaceManager = context.getBean("cn.webank.framework.message.SolaceManager", SolaceManager.class); MessageListener messageLisener = new MessageListener( // props.getProperty("listener.queue"), Arrays.asList(splits), Integer.parseInt(props.getProperty("listener.scanintervalseconds", "5")), taskThreadPool, Integer.parseInt(props.getProperty("listener.timeoutseconds", "5")), serviceDispatcher, solaceManager, bundleMessageSource); server.addListenerOnSchedule(messageLisener); // register shutdownhook Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { // close resource if (context != null) { context.close(); } } catch (Exception e) { LOG.error("shutdown error", e); } } }); // hold server try { LOG.info("ecif-index server start ok!"); server.start(); } catch (Exception e) { try { // close resource server.shutDown(); if (context != null) { context.close(); } } catch (Exception ex) { LOG.error("shutdown error", ex); } } LOG.info("ecif-index server stop !"); }
From source file:com.setronica.ucs.server.MessageServer.java
private static ClassPathXmlApplicationContext initApplication(String profile, DefaultListableBeanFactory parentBeanFactory) { ClassPathXmlApplicationContext applicationContext; if (parentBeanFactory != null) { //wrap BeanFactory inside ApplicationContext GenericApplicationContext parentContext = new GenericApplicationContext(parentBeanFactory); parentContext.refresh();//from w w w .j a va 2s . c om applicationContext = new ClassPathXmlApplicationContext(parentContext); } else { applicationContext = new ClassPathXmlApplicationContext(); } ConfigurableEnvironment environment = applicationContext.getEnvironment(); environment.setDefaultProfiles(profile); applicationContext.setConfigLocation("spring-application.xml"); // log active profile String[] profiles = environment.getActiveProfiles(); if (profiles.length == 0) { profiles = environment.getDefaultProfiles(); } for (String activeProfile : profiles) { if (environment.acceptsProfiles(activeProfile)) { logger.info("Profile " + activeProfile + " is active"); } } applicationContext.refresh(); return applicationContext; }
From source file:org.alfresco.bm.tools.BMTestRunner.java
/** * Execute the default test against the given MongoDB or an in-memory instance * /*w ww . j av a 2 s. c om*/ * @param mongoConfigHost the MongoDB host to connect to for configuraton data or <tt>null</tt> to use an in-memory version * @param mongoTestHost the MongoDB host to connect to for test data data or <tt>null</tt> to use the same database as the config * @param testProperties any properties to specifically set for the test or <tt>null</tt> if there are none */ public void run(String mongoConfigHost, String mongoTestHost, Properties testProperties) throws Exception { // Secure the listeners against modification List<BMTestRunnerListener> listeners = new ArrayList<BMTestRunnerListener>(this.listeners); // If no MongoDB URL is provided, then we have to start one MongoDBForTestsFactory mongoDBForTestsFactory = null; ClassPathXmlApplicationContext ctx = null; try { // Ensure that required system properties are present System.setProperty(PROP_APP_CONTEXT_PATH, System.getProperty("user.dir")); System.setProperty(PROP_APP_DIR, System.getProperty("user.dir")); // Create a MongoDB for use if one has not been specified if (mongoConfigHost == null) { mongoDBForTestsFactory = new MongoDBForTestsFactory(); String uriWithoutDB = mongoDBForTestsFactory.getMongoURIWithoutDB(); mongoConfigHost = new MongoClientURI(uriWithoutDB).getHosts().get(0); } // Fill in the URI for the test MongoDB if (mongoTestHost == null) { mongoTestHost = mongoConfigHost; } // Fill in the properties required for the test Properties mongoProps = new Properties(); mongoProps.put(PROP_MONGO_CONFIG_HOST, mongoConfigHost); // Construct the application context ctx = new ClassPathXmlApplicationContext(new String[] { PATH_APP_CONTEXT }, false); // Push cluster properties into the context (must be done AFTER setting parent context) ConfigurableEnvironment ctxEnv = ctx.getEnvironment(); // Mongo properties come first ctxEnv.getPropertySources().addFirst(new PropertiesPropertySource("mongo-props", mongoProps)); // Finally, system properties overrule them all ctxEnv.getPropertySources() .addFirst(new PropertiesPropertySource("system-props", System.getProperties())); // Kick it all off try { ctx.refresh(); } catch (Exception e) { Throwable root = ExceptionUtils.getRootCause(e); if (root != null && (root instanceof MongoSocketException || root instanceof UnknownHostException)) { // We deal with this specifically as it's a simple case of not finding the MongoDB logger.error("Set the configuration property '" + PROP_MONGO_CONFIG_HOST + "' (<server>:<port>) as required."); } else { // Log application start failure because test frameworks might not do so nicely logger.error("Failed to start application.", e); } throw new RuntimeException("Failed to start application.", e); } // Get the test Test test = ctx.getBean(Test.class); String release = test.getRelease(); Integer schema = test.getSchema(); TestRestAPI api = ctx.getBean(TestRestAPI.class); // Create a new test TestDetails testDetails = new TestDetails(); String testName = "BMTestRunner_" + System.currentTimeMillis(); testDetails.setName(testName); testDetails.setDescription("Test created by BMTestRunner on " + new Date()); testDetails.setRelease(release); testDetails.setSchema(schema); api.createTest(testDetails); // We need to tell the test which MongoDB to write data to PropSetBean propSet = new PropSetBean(); propSet.setValue(mongoTestHost); propSet.setVersion(0); api.setTestProperty(testName, PROP_MONGO_TEST_HOST, propSet); // Now set any properties that have been explicitly passed in for the test if (testProperties != null) { for (Map.Entry<Object, Object> entry : testProperties.entrySet()) { String propKey = (String) entry.getKey(); String propVal = (String) entry.getValue(); propSet.setValue(propVal); propSet.setVersion(0); api.setTestProperty(testName, propKey, propSet); } } // Call listeners: the test has been created for (BMTestRunnerListener listener : listeners) { listener.testReady(ctx, testName); } // Create a new test run TestRunDetails testRunDetails = new TestRunDetails(); String testRunName = "BMTestRunner_" + System.currentTimeMillis(); testRunDetails.setName(testRunName); testRunDetails.setDescription("Test run created by BMTestRunner on " + new Date()); api.createTestRun(testDetails.getName(), testRunDetails); // Call listeners: the test run has been created for (BMTestRunnerListener listener : listeners) { listener.testRunReady(ctx, testName, testRunName); } // Get all the test run properties for logging String jsonTestRun = api.getTestRun(testName, testRunName); // Start the test run logger.info("Starting test run: " + testRunName + "\n" + jsonTestRun); TestRunSchedule testRunSchedule = new TestRunSchedule(); testRunSchedule.setScheduled(System.currentTimeMillis()); api.scheduleTestRun(testName, testRunName, testRunSchedule); // Call listeners: the test run has started for (BMTestRunnerListener listener : listeners) { listener.testRunStarted(ctx, testName, testRunName); } // Wait for the test run to complete long timeInit = System.currentTimeMillis(); long timeLastChange = -1L; String jsonLastChange = null; String testRunStateStr = api.getTestRunState(testName, testRunName); // Keep looking until the test run completes while (!TestRunState.COMPLETED.toString().equals(testRunStateStr)) { long now = System.currentTimeMillis(); // Check that we have not exceeded the maximum time if (now - timeInit > maxTestTime) { throw new RuntimeException("Test run failed to complete in " + (int) maxTestTime / 1000 + "s."); } testRunStateStr = api.getTestRunState(testName, testRunName); if (TestRunState.SCHEDULED.toString().equals(testRunStateStr) && (now - timeInit) > 10000L) { throw new RuntimeException("Test run failed to start in 10s."); } // Check that there are updates to the test run String jsonNow = api.getTestRunSummary(testName, testRunName); if (jsonLastChange != null && jsonLastChange.equals(jsonNow)) { if ((now - timeLastChange) > 60000L) { throw new RuntimeException("Test run has not been updated in the last 60s"); } } // Store values for next iteration timeLastChange = now; jsonLastChange = jsonNow; synchronized (testRunStateStr) { try { testRunStateStr.wait(1000L); } catch (InterruptedException e) { } } } // Call listeners: the test run has finished for (BMTestRunnerListener listener : listeners) { listener.testRunFinished(ctx, testName, testRunName); } } finally { // Close the context if (ctx != null) { try { ctx.close(); } catch (Exception e) { logger.error("Failed to shut down application context.", e); } } // Close the local Mongo instance if (mongoDBForTestsFactory != null) { try { mongoDBForTestsFactory.destroy(); } catch (Exception e) { logger.error("Failed to stop in-memory MongoDB instance.", e); } } } }
From source file:nl.nn.adapterframework.configuration.IbisContext.java
/** * Create Spring Bean factory. Parameter 'springContext' can be null. * * Create the Spring Bean Factory using the supplied <code>springContext</code>, * if not <code>null</code>. * * @param springContext Spring Context to create. If <code>null</code>, * use the default spring context./*from ww w. j a v a 2 s. c o m*/ * The spring context is loaded as a spring ClassPathResource from * the class path. * * @return The Spring XML Bean Factory. * @throws BeansException If the Factory can not be created. * */ private ApplicationContext createApplicationContext() throws BeansException { // Reading in Spring Context long start = System.currentTimeMillis(); String springContext = "/springContext.xml"; ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(); MutablePropertySources propertySources = applicationContext.getEnvironment().getPropertySources(); propertySources.remove(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME); propertySources.remove(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME); propertySources.addFirst(new PropertiesPropertySource("ibis", APP_CONSTANTS)); applicationContext.setConfigLocation(springContext); applicationContext.refresh(); log("startup " + springContext + " in " + (System.currentTimeMillis() - start) + " ms"); return applicationContext; }
From source file:org.alfresco.bm.test.TestRun.java
/** * Called to ensure that the application context is started. * <p/>//w w w.j a v a 2s .c om * 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.alfresco.bm.test.TestRunServicesCache.java
/** * Create an application context holding the services for the given test run *//*from w w w .j a v a2 s.co m*/ private ClassPathXmlApplicationContext createContext(String test, String run) { String testRunFqn = test + "." + run; DBObject runObj; try { runObj = dao.getTestRun(test, run, true); } catch (ObjectNotFoundException e1) { logger.error("Test '" + test + "." + run + "' not found.", e1); return null; } // Dig the properties out of the test run Properties testRunProps = new Properties(); { 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); } } // Construct the properties ClassPathXmlApplicationContext testRunCtx = new ClassPathXmlApplicationContext( new String[] { PATH_TEST_SERVICES_CONTEXT }, false); ConfigurableEnvironment ctxEnv = testRunCtx.getEnvironment(); ctxEnv.getPropertySources().addFirst(new PropertiesPropertySource("run-props", testRunProps)); // Bind to shutdown testRunCtx.registerShutdownHook(); // Attempt to start the context try { testRunCtx.refresh(); testRunCtx.start(); // Make sure that the required components are present testRunCtx.getBean(EventService.class); testRunCtx.getBean(ResultService.class); testRunCtx.getBean(SessionService.class); } catch (Exception e) { Throwable root = ExceptionUtils.getRootCause(e); if (root != null && root instanceof MongoSocketException) { // We deal with this specifically as it's a simple case of not finding the MongoDB logger.error("Failed to start test run services context '" + testRunFqn + "': " + e.getCause().getMessage()); logger.error( "Set the test run property '" + PROP_MONGO_TEST_HOST + "' (<server>:<port>) as required."); } else if (root != null && root instanceof UnknownHostException) { // We deal with this specifically as it's a simple case of not finding the MongoDB logger.error("Failed to start test run services context '" + testRunFqn + "': " + e.getCause().getCause().getMessage()); logger.error( "Set the test run property '" + PROP_MONGO_TEST_HOST + "' (<server>:<port>) as required."); } else { logger.error("Failed to start test run services context '" + testRunFqn + "': ", e); } testRunCtx = null; } // Done if (testRunCtx == null) { logger.warn("Failed to start test run services context: " + testRunFqn); } else if (logger.isDebugEnabled()) { logger.debug("Started test run services context: " + testRunFqn); } return testRunCtx; }
From source file:org.springframework.batch.integration.x.RemoteFileToHadoopTests.java
@SuppressWarnings({ "unchecked", "rawtypes" }) @Before// ww w . j a va 2s . c o m 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); }