List of usage examples for org.springframework.context.support ClassPathXmlApplicationContext refresh
@Override public void refresh() throws BeansException, IllegalStateException
From source file:org.activiti.crystalball.simulator.TwoEnginesWithoutProcessTest.java
@Test public void test() throws Exception { String tempDir = "target"; FileUtils.copyFile(/*from www. j ava2s. c o m*/ FileUtils.getFile( new String[] { (new StringBuilder()).append(LIVE_DB).append(".h2.db").toString() }), FileUtils.getFile( new String[] { (new StringBuilder()).append(tempDir).append("/simulationRunDB-aaa-") .append(Thread.currentThread().getId()).append(".h2.db").toString() })); System.setProperty("_SIM_DB_PATH", (new StringBuilder()).append(tempDir).append("/simulationRunDB-aaa-") .append(Thread.currentThread().getId()).toString()); ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext( "/org/activiti/crystalball/simulator/SimRun-h2-context.xml"); PropertyPlaceholderConfigurer propConfig = new PropertyPlaceholderConfigurer(); Properties properties = new Properties(); properties.put("simulationRunId", "simulationRunDB-aaa-" + Thread.currentThread().getId()); propConfig.setProperties(properties); appContext.addBeanFactoryPostProcessor(propConfig); appContext.refresh(); SimulationRun simRun = (SimulationRun) appContext.getBean(SimulationRun.class); String userId = "user1"; TaskService taskService = (TaskService) appContext.getBean("taskService"); TaskService simTaskService = (TaskService) appContext.getBean("simTaskService"); List<Task> liveTaskList = ((TaskQuery) taskService.createTaskQuery().taskCandidateUser(userId) .orderByTaskPriority().desc()).listPage(0, 1); List<Task> execTaskList = ((TaskQuery) simTaskService.createTaskQuery().taskCandidateUser(userId) .orderByTaskPriority().desc()).listPage(0, 1); Assert.assertTrue(liveTaskList.size() == execTaskList.size()); IdentityService identityService = (IdentityService) appContext.getBean("identityService"); IdentityService simIdentityService = (IdentityService) appContext.getBean("simIdentityService"); List<User> users = identityService.createUserQuery().list(); List<User> simUsers = simIdentityService.createUserQuery().list(); Assert.assertTrue(users.size() == simUsers.size()); simRun.execute(new Date(), null); appContext.close(); }
From source file:gemlite.shell.service.batch.ImportService.java
/** * //from ww w . j ava2 s . co m * @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:com.temenos.interaction.loader.detector.SpringBasedLoaderAction.java
@Override public void execute(FileEvent<File> dirEvent) { LOGGER.debug("Creation of new Spring ApplicationContext based CommandController triggerred by change in", dirEvent.getResource().getAbsolutePath()); Collection<File> jars = FileUtils.listFiles(dirEvent.getResource(), new String[] { "jar" }, true); Set<URL> urls = new HashSet(); for (File f : jars) { try {/*w w w . j a v a2 s .c om*/ LOGGER.trace("Adding {} to list of URLs to create ApplicationContext from", f.toURI().toURL()); urls.add(f.toURI().toURL()); } catch (MalformedURLException ex) { // kindly ignore and log } } Reflections reflectionHelper = new Reflections( new ConfigurationBuilder().addClassLoader(classloaderFactory.getForObject(dirEvent)) .addScanners(new ResourcesScanner()).addUrls(urls)); Set<String> resources = new HashSet(); for (String locationPattern : configLocationsPatterns) { String regex = convertWildcardToRegex(locationPattern); resources.addAll(reflectionHelper.getResources(Pattern.compile(regex))); } if (!resources.isEmpty()) { // if resources are empty just clean up the previous ApplicationContext and leave! LOGGER.debug("Detected potential Spring config files to load"); ClassPathXmlApplicationContext context; if (parentContext != null) { context = new ClassPathXmlApplicationContext(parentContext); } else { context = new ClassPathXmlApplicationContext(); } context.setConfigLocations(configLocationsPatterns.toArray(new String[] {})); ClassLoader childClassLoader = classloaderFactory.getForObject(dirEvent); context.setClassLoader(childClassLoader); context.refresh(); CommandController cc = null; try { cc = context.getBean(commandControllerBeanName, CommandController.class); LOGGER.debug("Detected pre-configured CommandController in added config files"); } catch (BeansException ex) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("No detected pre-configured CommandController in added config files.", ex); } Map<String, InteractionCommand> commands = context.getBeansOfType(InteractionCommand.class); if (!commands.isEmpty()) { LOGGER.debug("Adding new commands"); SpringContextBasedInteractionCommandController scbcc = new SpringContextBasedInteractionCommandController(); scbcc.setApplicationContext(context); cc = scbcc; } else { LOGGER.debug("No commands detected to be added"); } } if (parentChainingCommandController != null) { List<CommandController> newCommandControllers = new ArrayList<CommandController>( parentChainingCommandController.getCommandControllers()); // "unload" the previously loaded CommandController if (previouslyAddedCommandController != null) { LOGGER.debug("Removing previously added instance of CommandController"); newCommandControllers.remove(previouslyAddedCommandController); } // if there is a new CommandController on the Spring file, add it on top of the chain if (cc != null) { LOGGER.debug("Adding newly created CommandController to ChainingCommandController"); newCommandControllers.add(0, cc); parentChainingCommandController.setCommandControllers(newCommandControllers); previouslyAddedCommandController = cc; } else { previouslyAddedCommandController = null; } } else { LOGGER.debug( "No ChainingCommandController set to add newly created CommandController to - skipping action"); } if (previousAppCtx != null) { if (previousAppCtx instanceof Closeable) { try { ((Closeable) previousAppCtx).close(); } catch (Exception ex) { LOGGER.error("Error closing the ApplicationContext.", ex); } } previousAppCtx = context; } } else { LOGGER.debug("No Spring config files detected in the JARs scanned"); } }
From source file:org.openspaces.itest.persistency.cassandra.archive.CassandaraArchiveOperationHandlerTest.java
private void xmlTest(String relativeXmlName) { final boolean refreshNow = false; final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( new String[] { relativeXmlName }, refreshNow); PropertyPlaceholderConfigurer propertyConfigurer = new PropertyPlaceholderConfigurer(); Properties properties = new Properties(); properties.put("cassandra.keyspace", server.getKeySpaceName()); properties.put("cassandra.hosts", server.getHost()); properties.put("cassandra.port", "" + server.getPort()); properties.put("cassandra.write-consistency", "ALL"); propertyConfigurer.setProperties(properties); context.addBeanFactoryPostProcessor(propertyConfigurer); context.refresh();/*w w w .j ava2s. co m*/ try { final CassandraArchiveOperationHandler archiveHandler = context .getBean(CassandraArchiveOperationHandler.class); Assert.assertEquals(CassandraConsistencyLevel.ALL, archiveHandler.getWriteConsistency()); final GigaSpace gigaSpace = context.getBean(org.openspaces.core.GigaSpace.class); test(archiveHandler, gigaSpace); } finally { context.close(); } }
From source file:nz.co.senanque.madura.configuration.ConfigSetupTest.java
@Test public void testSpringConfig() throws Exception { ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext( getConfigLocations());/*from w w w .ja v a 2 s .c o m*/ Object hs1 = applicationContext.getBean("component.sourcedir"); assertTrue("mysourcedir".equals(hs1.toString())); Object hs2 = applicationContext.getBean("component1.sourcedir"); System.out.println(hs2.toString()); assertTrue("mysourcedir".equals(hs2.toString())); URL url = (URL) applicationContext.getBean("myurl"); assertTrue("http://localhost:8080/jjj".equals(url.toString())); System.out.println(url.toString()); Configuration configuration = (Configuration) applicationContext.getBean("configuration"); Object doc = applicationContext.getBean("test1"); MyTestBean myTestBean = (MyTestBean) applicationContext.getBean("test2"); assertTrue(myTestBean.getA().equals("XYZ")); myTestBean.setA("12345"); assertTrue(myTestBean.getA().equals("12345")); List sampleList = (List) applicationContext.getBean("sampleList"); assertEquals(2, sampleList.size()); applicationContext.refresh(); // ManagedReloadingStrategy reloadingStrategy = (ManagedReloadingStrategy)applicationContext.getBean("reloadingStrategy"); // reloadingStrategy.refresh(); MyTestBean myTestBean1 = (MyTestBean) applicationContext.getBean("test2"); assertTrue(myTestBean1.getA().equals("XYZ")); }
From source file:org.openspaces.itest.persistency.cassandra.spring.CassandaraFactoryBeansTest.java
@Test public void test() { final boolean refreshNow = false; final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( new String[] { TEST_FACTORY_XML }, refreshNow); PropertyPlaceholderConfigurer propertyConfigurer = new PropertyPlaceholderConfigurer(); Properties properties = new Properties(); properties.setProperty("cassandra.hosts", server.getHost()); properties.setProperty("cassandra.port", String.valueOf(server.getPort())); properties.setProperty("cassandra.keyspace", server.getKeySpaceName()); properties.setProperty("cassandra.user", "default"); properties.setProperty("cassandra.password", "default"); properties.setProperty("cassandra.ds.cluster", "ds_cluster"); properties.setProperty("cassandra.sync.cluster", "sync_cluster"); properties.setProperty("cassandra.ds.minconnections", String.valueOf(1)); properties.setProperty("cassandra.ds.maxconnections", String.valueOf(5)); properties.setProperty("cassandra.ds.batchlimit", String.valueOf(100)); properties.setProperty("cassandra.hector.gcgrace", String.valueOf(60 * 60 * 24 * 10)); properties.setProperty("cassandra.hector.read.consistency.level", CassandraConsistencyLevel.QUORUM.name()); properties.setProperty("cassandra.hector.write.consistency.level", CassandraConsistencyLevel.ONE.name()); propertyConfigurer.setProperties(properties); context.addBeanFactoryPostProcessor(propertyConfigurer); context.refresh(); try {// www.j ava2 s. c om syncEndpoint = context.getBean(CassandraSpaceSynchronizationEndpoint.class); dataSource = context.getBean(CassandraSpaceDataSource.class); doWork(); } finally { context.close(); } }
From source file:org.alfresco.bm.tools.BMTestRunner.java
/** * Execute the default test against the given MongoDB or an in-memory instance * //from w ww. j a v 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 va 2s .com*/ * 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; }