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

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

Introduction

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

Prototype

@Override
    public void refresh() throws BeansException, IllegalStateException 

Source Link

Usage

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

/**
 * Called to ensure that the application context is started.
 * <p/>//from  ww w.jav  a 2 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 ww.  j  a v  a 2 s. com
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.easyrec.plugin.container.PluginRegistry.java

@SuppressWarnings({ "unchecked" })
public void installPlugin(URI pluginId, Version version) {
    FileOutputStream fos = null;// www .j a  v a2s  .c om
    File tmpFile = null;

    try {
        PluginVO plugin = pluginDAO.loadPlugin(pluginId, version);
        if (plugin == null)
            throw new Exception("Plugin not found in DB!");
        // write file to plugin folder
        tmpFile = new File(pluginFolder.getFile(),
                plugin.getId().toString() + "_" + plugin.getDisplayName() + ".jar");
        fos = new FileOutputStream(tmpFile);
        fos.write(plugin.getFile());
        fos.close();

        // install the plugin

        PluginClassLoader ucl = new PluginClassLoader(new URL[] { tmpFile.toURI().toURL() },
                this.getClass().getClassLoader());

        if (ucl.findResource(DEFAULT_PLUGIN_CONFIG_FILE) == null) {
            logger.warn("no " + DEFAULT_PLUGIN_CONFIG_FILE + " found in plugin jar ");
            return;
        }

        ClassPathXmlApplicationContext cax = new ClassPathXmlApplicationContext(
                new String[] { DEFAULT_PLUGIN_CONFIG_FILE }, false, appContext);
        cax.setClassLoader(ucl);
        cax.refresh();
        //            cax.stop();
        //            cax.start();

        // currently only GeneratorPluginSupport is used
        Map<String, GeneratorPluginSupport> beans = cax.getBeansOfType(GeneratorPluginSupport.class);

        if (beans.isEmpty()) {
            logger.warn("no GeneratorPluginSupport subclasses found in plugin jar");
            return;
        }

        Generator<GeneratorConfiguration, GeneratorStatistics> generator = beans.values().iterator().next();

        installGenerator(pluginId, version, plugin, cax, generator);
    } catch (Exception e) {
        logger.error("An Exception occurred while installing the plugin!", e);

        pluginDAO.updatePluginState(pluginId, version, LifecyclePhase.INSTALL_FAILED.toString());
    } finally {
        if (fos != null)
            try {
                fos.close();
            } catch (Exception ignored) {
                logger.warn("could not close file output stream", ignored);
            }

        /*
        if (tmpFile != null)
        try {
            tmpFile.delete();
        } catch (Exception ignored) {
            logger.warn("could not delete temporary plugin file", ignored);
        }
        */
    }
}

From source file:org.easyrec.plugin.container.PluginRegistry.java

@SuppressWarnings({ "unchecked" })
public PluginVO checkPlugin(byte[] file) throws Exception {
    PluginVO plugin;//from w  w  w . ja v a2  s.co  m
    FileOutputStream fos = null;
    URLClassLoader ucl;
    ClassPathXmlApplicationContext cax = null;
    File tmpFile = null;

    try {
        if (file == null)
            throw new IllegalArgumentException("Passed file must not be null!");

        tmpFile = File.createTempFile("plugin", null);
        tmpFile.deleteOnExit();

        fos = new FileOutputStream(tmpFile);
        fos.write(file);
        fos.close();

        // check if plugin is valid
        ucl = new URLClassLoader(new URL[] { tmpFile.toURI().toURL() }, this.getClass().getClassLoader());

        if (ucl.getResourceAsStream(DEFAULT_PLUGIN_CONFIG_FILE) != null) {
            cax = new ClassPathXmlApplicationContext(new String[] { DEFAULT_PLUGIN_CONFIG_FILE }, false,
                    appContext);
            cax.setClassLoader(ucl);
            logger.info("Classloader: " + cax.getClassLoader());
            cax.refresh();

            Map<String, GeneratorPluginSupport> beans = cax.getBeansOfType(GeneratorPluginSupport.class);

            if (beans.isEmpty()) {
                logger.debug("No class implementing a generator could be found. Plugin rejected!");
                throw new Exception("No class implementing a generator could be found. Plugin rejected!");
            }

            Generator<GeneratorConfiguration, GeneratorStatistics> generator = beans.values().iterator().next();

            logger.info(String.format("Plugin successfully validated! class: %s name: %s, id: %s",
                    generator.getClass(), generator.getDisplayName(), generator.getId()));

            cax.getAutowireCapableBeanFactory().autowireBeanProperties(generator,
                    AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);

            plugin = new PluginVO(generator.getDisplayName(), generator.getId().getUri(),
                    generator.getId().getVersion(), LifecyclePhase.NOT_INSTALLED.toString(), file, null);

            if (tmpFile.delete())
                logger.info("tmpFile deleted successfully");

            return plugin;
        } else { // config file not found
            logger.debug("No valid config file found in the supplied .jar file. Plugin rejected!");
            throw new Exception("No valid config file found in the supplied .jar file. Plugin rejected!");
        }
    } catch (Exception e) {
        logger.error("An Exception occurred while checking the plugin!", e);

        throw e;
    } finally {
        if (fos != null)
            fos.close();

        if ((cax != null) && (!cax.isActive()))
            cax.close();

        if (tmpFile != null)
            try {
                if (!tmpFile.delete())
                    logger.warn("could not delete tmpFile");
            } catch (SecurityException se) {
                logger.error("Could not delete temporary file! Please check permissions!", se);
            }
    }
}

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   ww w  .  j  a  v  a2 s .c  om*/
    //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.jumpmind.symmetric.ClientSymmetricEngine.java

@Override
protected void init() {
    try {/*from   www .  j a v a2 s. com*/
        LogSummaryAppenderUtils.registerLogSummaryAppender();

        super.init();

        this.dataSource = platform.getDataSource();

        PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
        configurer.setProperties(parameterService.getAllParameters());

        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(springContext);
        ctx.addBeanFactoryPostProcessor(configurer);

        List<String> extensionLocations = new ArrayList<String>();
        extensionLocations.add("classpath:/symmetric-ext-points.xml");
        if (registerEngine) {
            extensionLocations.add("classpath:/symmetric-jmx.xml");
        }

        String xml = parameterService.getString(ParameterConstants.EXTENSIONS_XML);
        File file = new File(parameterService.getTempDirectory(), "extension.xml");
        FileUtils.deleteQuietly(file);
        if (isNotBlank(xml)) {
            try {
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                factory.setValidating(false);
                factory.setNamespaceAware(true);
                DocumentBuilder builder = factory.newDocumentBuilder();
                // the "parse" method also validates XML, will throw an exception if misformatted
                builder.parse(new InputSource(new StringReader(xml)));
                FileUtils.write(file, xml, false);
                extensionLocations.add("file:" + file.getAbsolutePath());
            } catch (Exception e) {
                log.error("Invalid " + ParameterConstants.EXTENSIONS_XML + " parameter.");
            }
        }

        try {
            ctx.setConfigLocations(extensionLocations.toArray(new String[extensionLocations.size()]));
            ctx.refresh();

            this.springContext = ctx;

            ((ClientExtensionService) this.extensionService).setSpringContext(springContext);
            this.extensionService.refresh();
        } catch (Exception ex) {
            log.error(
                    "Failed to initialize the extension points.  Please fix the problem and restart the server.",
                    ex);
        }
    } catch (RuntimeException ex) {
        destroy();
        throw ex;
    }
}

From source file:org.oscarehr.labs.alberta.CLSHandlerIntegrationTest.java

@BeforeClass
public static void init() throws Exception {
    SchemaUtils.restoreAllTables();//  w w w  . j ava  2  s .c  o  m

    if (SpringUtils.beanFactory == null) {
        oscar.OscarProperties p = oscar.OscarProperties.getInstance();
        p.setProperty("db_name",
                ConfigUtils.getProperty("db_schema") + ConfigUtils.getProperty("db_schema_properties"));
        p.setProperty("db_username", ConfigUtils.getProperty("db_user"));
        p.setProperty("db_password", ConfigUtils.getProperty("db_password"));
        p.setProperty("db_uri", ConfigUtils.getProperty("db_url_prefix"));
        p.setProperty("db_driver", ConfigUtils.getProperty("db_driver"));
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext();
        context.setConfigLocations(new String[] { "/applicationContext.xml", "/applicationContextBORN.xml" });
        context.refresh();
        SpringUtils.beanFactory = context;
    }

    AuthUtils.initLoginContext();

}

From source file:org.springframework.batch.admin.BootstrapTests.java

@Test
public void testServletConfiguration() throws Exception {
    ClassPathXmlApplicationContext parent = new ClassPathXmlApplicationContext(
            "classpath:/org/springframework/batch/admin/web/resources/webapp-config.xml");
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            new String[] { "classpath:/org/springframework/batch/admin/web/resources/servlet-config.xml" },
            parent);/*  ww  w  .j  a v a2s . c  om*/

    assertTrue(context.containsBean("jobRepository"));
    String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context.getBeanFactory(),
            JobController.class);
    assertEquals(1, beanNames.length);

    MenuManager menuManager = context.getBean(MenuManager.class);
    assertEquals(4, menuManager.getMenus().size());

    context.refresh();

    ClassPathXmlApplicationContext child = new ClassPathXmlApplicationContext(
            new String[] { "classpath:/test-job-context.xml" }, parent);
    Job job = child.getBean(Job.class);
    final JobExecution jobExecution = parent.getBean(JobLauncher.class).run(job, new JobParameters());

    new DirectPoller<BatchStatus>(100).poll(new Callable<BatchStatus>() {
        public BatchStatus call() throws Exception {
            BatchStatus status = jobExecution.getStatus();
            if (status.isLessThan(BatchStatus.STOPPED) && status != BatchStatus.COMPLETED) {
                return null;
            }
            return status;
        }
    }).get(2000, TimeUnit.MILLISECONDS);

    HomeController metaData = new HomeController();
    metaData.setApplicationContext(context);
    metaData.afterPropertiesSet();
    MockHttpServletRequest request = new MockHttpServletRequest();
    ModelMap model = new ModelMap();
    metaData.getResources(request, model);
    @SuppressWarnings("unchecked")
    List<ResourceInfo> resources = (List<ResourceInfo>) model.get("resources");
    StringBuilder content = new StringBuilder();
    for (ResourceInfo resourceInfo : resources) {
        content.append(resourceInfo.getMethod() + resourceInfo.getUrl() + "=\n");
    }
    FileUtils.writeStringToFile(new File("target/resources.properties"), content.toString());

    HomeController home = context.getBean(HomeController.class);
    // System.err.println(home.getUrlPatterns());
    assertTrue(home.getUrlPatterns().contains("/jobs/{jobName}"));

    String message = context.getMessage("GET/jobs/{jobName}", new Object[0], Locale.getDefault());
    assertTrue("No message for /jobs/{jobName}", StringUtils.hasText(message));

    child.close();
    context.close();
    parent.close();

    assertEquals(BatchStatus.COMPLETED, jobExecution.getStatus());

}

From source file:org.springframework.batch.integration.x.RemoteFileToHadoopTests.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Before// w  w w  .  jav a 2s .co 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);
}

From source file:org.springframework.data.neo4j.illegal.aspects.index1.IllegalIndex1Tests.java

/**
 * As the first illegal entity detected will blow up the application context - we need a way
 * to ensure only the illegal entity under test it loaded to assert that we fail
 * for the correct reason and in an appropriate way. This method will create and application
 * context ensuring that only the illegal entity under test (passed in as an argument), is
 * detected by the context.  This is currently done by wrapping each Illegal Entity bootstrap
 * logic in a Spring profile against its same name
 *
 * @param entityUnderTest Class which should be detected by SDN for the purposes of testing
 * @throws Throwable//from w  w w  .  jav  a  2s . c o m
 */
private void createAppCtxAndPropagateRootExceptionIfThrown(Class entityUnderTest) throws Throwable {
    try {
        ClassPathXmlApplicationContext appCtx = new ClassPathXmlApplicationContext();
        appCtx.setConfigLocation(
                "org/springframework/data/neo4j/aspects/support/illegal-index1-tests-context.xml");
        appCtx.getEnvironment().setActiveProfiles(entityUnderTest.getSimpleName());
        appCtx.refresh();
    } catch (BeanCreationException bce) {
        throw ExceptionUtils.getRootCause(bce);
    }
}