List of usage examples for org.springframework.context.support ClassPathXmlApplicationContext getBean
@Override public Object getBean(String name) throws BeansException
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();/*from www .j a va2 s. c om*/ try { 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 * //ww w . j av a2 s. co m * @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:org.aksw.dice.eaglet.web.RootConfig.java
@Bean public EagletDatabaseStatements experimentDAO() { LOGGER.debug("Setting up database."); ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( "/spring/database/database-context.xml"); EagletDatabaseStatements database = context.getBean(EagletDatabaseStatements.class); context.close();//ww w .j ava 2 s.c om return database; }
From source file:org.alfresco.bm.test.TestRun.java
/** * Called to ensure that the application context is started. * <p/>/*from ww w. ja v a2 s .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.alfresco.bm.test.TestRunServicesCache.java
/** * Create an application context holding the services for the given test run *//*from ww w .jav a 2 s . c om*/ 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.alfresco.filesys.CIFSServerBean.java
/** * Runs the CIFS server directly/*w w w .j a v a2s . c o m*/ * * @param args String[] */ public static void main(String[] args) { PrintStream out = System.out; out.println("CIFS Server Test"); out.println("----------------"); ClassPathXmlApplicationContext ctx = null; try { // Create the configuration service in the same way that Spring creates it ctx = new ClassPathXmlApplicationContext("alfresco/application-context.xml"); // Get the CIFS server bean CIFSServerBean server = (CIFSServerBean) ctx.getBean("cifsServer"); if (server == null) { throw new AlfrescoRuntimeException("Server bean 'cifsServer' not defined"); } // Stop the FTP server, if running NetworkServer srv = server.getConfiguration().findServer("FTP"); if (srv != null) srv.shutdownServer(true); // Stop the NFS server, if running srv = server.getConfiguration().findServer("NFS"); if (srv != null) srv.shutdownServer(true); // Only wait for shutdown if the SMB/CIFS server is enabled if (server.getConfiguration().hasConfigSection(CIFSConfigSection.SectionName)) { // SMB/CIFS server should have automatically started // Wait for shutdown via the console out.println("Enter 'x' to shutdown ..."); boolean shutdown = false; // Wait while the server runs, user may stop the server by typing a key while (shutdown == false) { // Wait for the user to enter the shutdown key int ch = System.in.read(); if (ch == 'x' || ch == 'X') shutdown = true; synchronized (server) { server.wait(20); } } // Stop the server server.stopServer(); } } catch (Exception ex) { ex.printStackTrace(); } finally { if (ctx != null) { ctx.close(); } } System.exit(1); }
From source file:org.alfresco.filesys.FTPServerBean.java
/** * Runs the FTP server directly// w w w. j av a 2 s .c om * * @param args String[] */ public static void main(String[] args) { PrintStream out = System.out; out.println("FTP Server Test"); out.println("---------------"); ClassPathXmlApplicationContext ctx = null; try { // Create the configuration service in the same way that Spring creates it ctx = new ClassPathXmlApplicationContext("alfresco/application-context.xml"); // Get the FTP server bean FTPServerBean server = (FTPServerBean) ctx.getBean("ftpServer"); if (server == null) { throw new AlfrescoRuntimeException("Server bean 'ftpServer' not defined"); } // Stop the CIFS server components, if running NetworkServer srv = server.getConfiguration().findServer("SMB"); if (srv != null) srv.shutdownServer(true); srv = server.getConfiguration().findServer("NetBIOS"); if (srv != null) srv.shutdownServer(true); // Only wait for shutdown if the FTP server is enabled if (server.getConfiguration().hasConfigSection(FTPConfigSection.SectionName)) { // FTP server should have automatically started // // Wait for shutdown via the console out.println("Enter 'x' to shutdown ..."); boolean shutdown = false; // Wait while the server runs, user may stop the server by typing a key while (shutdown == false) { // Wait for the user to enter the shutdown key int ch = System.in.read(); if (ch == 'x' || ch == 'X') shutdown = true; synchronized (server) { server.wait(20); } } // Stop the server server.stopServer(); } } catch (Exception ex) { ex.printStackTrace(); } finally { if (ctx != null) { ctx.close(); } } System.exit(1); }
From source file:org.axonframework.quickstart.RunUpcasterWithSpring.java
/** * @deprecated Spring XML config support is deprecated *///from ww w . java2 s . c o m @Deprecated public static void main(String[] args) throws IOException { // we want to delete the directory that will store our events FileUtils.deleteDirectory(new File(System.getProperty("java.io.tmpdir"), "Events")); // we start the application context ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext( "upcaster-config.xml"); // we fetch the EventStore from the application context EventStore eventStore = applicationContext.getBean(EventStore.class); // we append some events. Notice we append a "ToDoItemCreatedEvent". eventStore.publish(Arrays.asList( new GenericDomainEventMessage<Object>("ToDo", "todo1", 0, new ToDoItemCreatedEvent("todo1", "I need to do this today")), new GenericDomainEventMessage<Object>("ToDo", "todo1", 1, new ToDoItemCompletedEvent("todo1")))); eventStore.publish(Collections.singletonList(new GenericDomainEventMessage<Object>("ToDo", "todo2", 0, new ToDoItemCreatedEvent("todo2", "I also need to do this")))); // now, we read the events from the "todo1" stream DomainEventStream upcastEvents = eventStore.readEvents("todo1"); while (upcastEvents.hasNext()) { // and print them, so that we can see what we ended up with System.out.println(upcastEvents.next().getPayload().toString()); } IOUtils.closeQuietlyIfCloseable(upcastEvents); // to see the Upcaster doing the upcasting, see RunUpcaster, inner class ToDoItemUpcaster // we close the application context. It's just good habit applicationContext.close(); }
From source file:org.collectionspace.services.authorization.AuthZ.java
private void setupProvider() { String beanConfig = "applicationContext-authorization.xml"; //system property is only set in test environment String beanConfigProp = System.getProperty("spring-beans-config"); if (beanConfigProp != null && !beanConfigProp.isEmpty()) { beanConfig = beanConfigProp;//from ww w . ja va2 s . co m } if (log.isDebugEnabled()) { log.debug("reading beanConfig=" + beanConfig); } ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(new String[] { beanConfig }); provider = (CSpaceAuthorizationProvider) appContext.getBean("cspaceAuthorizationProvider"); if (log.isDebugEnabled()) { log.debug("initialized the authz provider"); } }