Example usage for org.springframework.context.support ClassPathXmlApplicationContext start

List of usage examples for org.springframework.context.support ClassPathXmlApplicationContext start

Introduction

In this page you can find the example usage for org.springframework.context.support ClassPathXmlApplicationContext start.

Prototype

@Override
    public void start() 

Source Link

Usage

From source file:com.ryantenney.metrics.spring.ReporterTest.java

@Test
public void fakeReporters() throws Throwable {
    ClassPathXmlApplicationContext ctx = null;
    FakeReporter one = null;/*from   w  ww .j  a  v  a2 s  .co  m*/
    FakeReporter two = null;
    try {
        MetricRegistry registry = new MetricRegistry();
        SharedMetricRegistries.add("reporterTestRegistry", registry);

        ctx = new ClassPathXmlApplicationContext("classpath:fake-reporter-test.xml");
        ctx.start();

        Thread.sleep(1000);

        one = ctx.getBean("fakeReporterOne", FakeReporter.class);
        Assert.assertEquals(registry, one.getRegistry());
        Assert.assertEquals("milliseconds", one.getDurationUnit());
        Assert.assertEquals("second", one.getRateUnit());
        Assert.assertEquals(100000000, one.getPeriod());
        Assert.assertEquals(10, one.getCalls());
        Assert.assertEquals("[MetricFilter regex=foo]", one.getFilter().toString());
        Assert.assertTrue(one.isRunning());

        two = ctx.getBean("fakeReporterTwo", FakeReporter.class);
        Assert.assertEquals(registry, two.getRegistry());
        Assert.assertEquals("nanoseconds", two.getDurationUnit());
        Assert.assertEquals("hour", two.getRateUnit());
        Assert.assertEquals(100000000, two.getPeriod());
        Assert.assertEquals(10, one.getCalls());
        Assert.assertEquals(ctx.getBean(BarFilter.class), two.getFilter());
        Assert.assertTrue(one.isRunning());

    } finally {
        if (ctx != null) {
            ctx.stop();
            ctx.close();
        }
    }

    if (one != null) {
        Assert.assertFalse(one.isRunning());
    }

    if (two != null) {
        Assert.assertFalse(two.isRunning());
    }
}

From source file:net.dfs.remote.main.ClientServicesStarter.java

public final void loadNode() {

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext();

    PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
    configurer.setProperties(props);//w  w w .  ja  va 2 s.  com

    context.addBeanFactoryPostProcessor(configurer);
    context.setConfigLocation("net\\dfs\\remote\\filestorage\\spring-client.xml");
    context.refresh();
    context.start();

    /*      FileLocationTrackerImpl hash = new FileLocationTrackerImpl();
          hash.removeAll();
    */
    log.info("Client Started");

    FileReceiverSupport receiveFile = (FileReceiverSupport) context.getBean("receiveFile");

    receiveFile.connectJavaSpace();
    receiveFile.retrieveFile();
}

From source file:org.alfresco.bm.test.TestRun.java

/**
 * Called to ensure that the application context is started.
 * <p/>/*from  w  ww.  jav 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  w w w  . j a  va 2 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.integration.samples.kafka.outbound.OutboundRunner.java

public static void main(final String args[]) {
    final ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(CONFIG, OutboundRunner.class);
    ctx.start();

    final MessageChannel channel = ctx.getBean("inputToKafka", MessageChannel.class);
    LOG.info(channel.getClass());/*from  w  w w  .jav a2s. com*/

    //sending 100,000 messages to Kafka server for topic test1
    for (int i = 0; i < 500; i++) {
        final User user = new User();
        user.setFirstName("fname" + i);
        user.setLastName("lname" + i);
        channel.send(MessageBuilder.withPayload(user).setHeader("messageKey", String.valueOf(i))
                .setHeader("topic", "test1").build());

        LOG.info("message sent " + i);
    }

    //sending 5,000 messages to kafka server for topic test2
    for (int i = 0; i < 50; i++) {
        channel.send(MessageBuilder.withPayload("hello Fom ob adapter test2 -  " + i)
                .setHeader("messageKey", String.valueOf(i)).setHeader("topic", "test2").build());

        LOG.info("message sent " + i);
    }

    //Send some messages to multiple topics matching regex.
    for (int i = 0; i < 10; i++) {
        channel.send(MessageBuilder.withPayload("hello Fom ob adapter regextopic1 -  " + i)
                .setHeader("messageKey", String.valueOf(i)).setHeader("topic", "regextopic1").build());

        LOG.info("message sent " + i);
    }
    for (int i = 0; i < 10; i++) {
        channel.send(MessageBuilder.withPayload("hello Fom ob adapter regextopic2 -  " + i)
                .setHeader("messageKey", String.valueOf(i)).setHeader("topic", "regextopic2").build());

        LOG.info("message sent " + i);
    }
}