Example usage for org.springframework.context.support FileSystemXmlApplicationContext FileSystemXmlApplicationContext

List of usage examples for org.springframework.context.support FileSystemXmlApplicationContext FileSystemXmlApplicationContext

Introduction

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

Prototype

public FileSystemXmlApplicationContext(String... configLocations) throws BeansException 

Source Link

Document

Create a new FileSystemXmlApplicationContext, loading the definitions from the given XML files and automatically refreshing the context.

Usage

From source file:org.jodconverter.cli.Convert.java

private static AbstractApplicationContext getApplicationContextOption(final CommandLine commandLine) {

    if (commandLine.hasOption(OPT_APPLICATION_CONTEXT.getOpt())) {

        return new FileSystemXmlApplicationContext(
                commandLine.getOptionValue(OPT_APPLICATION_CONTEXT.getOpt()));
    }/*from  w w w . j  av  a2s. c om*/

    return null;
}

From source file:com.cisco.dvbu.ps.deploytool.DeployManagerUtil.java

private static void initSpring() {
    try {/*from  w ww.  j av  a  2 s .  co  m*/
        String configDirRoot = System.getProperty(configRootProperty);
        if (configDirRoot != null && configDirRoot.length() > 0) {
            File dir = new File(configDirRoot);

            // Set the file system separator type
            @SuppressWarnings("static-access")
            String sep = dir.separator;
            System.setProperty("FILE_SYSTEM_SEPARATOR", sep);

            if (dir.exists() && dir.isDirectory()) {
                File file = new File(dir, springConfigFile);

                if (logger.isDebugEnabled()) {
                    logger.debug("Config root " + dir.getPath());
                    logger.debug("Loading Spring Config File " + file.getPath());
                }
                String[] contextFiles = { "file:" + file.getPath() };
                context = new FileSystemXmlApplicationContext(contextFiles);
            }
        }
    } catch (BeansException e) {
        logger.warn("spring initialization failed due to " + e.getMessage());
    }
}

From source file:com.fusesource.forge.jmstest.benchmark.BenchmarkConfig.java

public ApplicationContext getApplicationContext() {

    if (applictionContext == null) {
        log().info("getSpringConfigurations() --> " + getSpringConfigurations());
        if (getSpringConfigurations().size() > 0) {

            log().info("tmpdir --> " + System.getProperty("java.io.tmpdir"));
            File tmpDir = new File(System.getProperty("java.io.tmpdir"), getBenchmarkId());
            if (tmpDir.exists()) {
                if (tmpDir.isFile()) {
                    FileUtils.deleteQuietly(tmpDir);
                } else if (tmpDir.isDirectory()) {
                    try {
                        FileUtils.deleteDirectory(tmpDir);
                    } catch (IOException ioe) {
                        log().error("Error deleting directory: " + tmpDir, ioe);
                    }// w  w w  .  j av  a2 s  . c  o  m
                }
            }
            tmpDir.mkdirs();
            log().debug("Created directory: " + tmpDir);

            String[] tempFiles = new String[getSpringConfigurations().size()];

            int cfgNumber = 0;
            for (String config : getSpringConfigurations()) {
                log().debug("Config to be written " + config);
                File cfgFile = new File(tmpDir, "SpringConfig-" + (cfgNumber) + ".xml");
                tempFiles[cfgNumber++] = "file:/" + cfgFile.getAbsolutePath();
                //tempFiles[cfgNumber++] = "file:\\\\localhost\\c$\\" + cfgFile.getAbsolutePath().substring(2);

                log().debug("file location " + tempFiles[cfgNumber - 1]);
                log().debug("Dumping : " + cfgFile.getAbsolutePath());
                try {
                    OutputStream os = new FileOutputStream(cfgFile);
                    IOUtils.write(config.getBytes("UTF-8"), os);
                    os.close();
                } catch (Exception e) {
                    log().error("Error Dumping: " + cfgFile.getAbsolutePath());
                }
            }
            log().debug("Creating ApplicationContext from temporary files.");
            applictionContext = new FileSystemXmlApplicationContext(tempFiles);
        } else {
            applictionContext = new FileSystemXmlApplicationContext();
        }
    }
    return applictionContext;
}

From source file:org.bigtester.ate.model.caserunner.CaseRunner.java

/**
 * Test runner1./*w  w  w .ja  v  a2s.  c o m*/
 * 
 * @param ctx
 *            the ctx
 * @throws Throwable
 */
// @Test(dataProvider = "dp")
public void runTest(TestParameters testParams) throws Throwable {
    String testname = testParams.getTestFilename();

    // ApplicationContext context;
    try {
        context = new FileSystemXmlApplicationContext(testname);
        IMyWebDriver myWebD = (IMyWebDriver) GlobalUtils.findMyWebDriver(context);
        mainDriver = myWebD.getWebDriverInstance();
        myTestCase = GlobalUtils.findTestCaseBean(getContext());
        getMyTestCase().setStepThinkTime(testParams.getStepThinkTime());
        getMyTestCase().setCurrentWebDriver(myWebD);
        getMyTestCase().goSteps();

    } catch (FatalBeanException fbe) {
        if (fbe.getCause() instanceof FileNotFoundException) {
            context = new ClassPathXmlApplicationContext(testname);
            mainDriver = ((IMyWebDriver) GlobalUtils.findMyWebDriver(context)).getWebDriverInstance();
            myTestCase = GlobalUtils.findTestCaseBean(getContext());
            myTestCase.setStepThinkTime(testParams.getStepThinkTime());
            getMyTestCase().goSteps();

        } else if (fbe instanceof BeanCreationException) { // NOPMD
            ITestResult itr = Reporter.getCurrentTestResult();

            if (itr.getThrowable() != null && itr.getThrowable() instanceof TestDataException) {
                TestDataException tde = (TestDataException) itr.getThrowable();
                tde.setTestStepName(((BeanCreationException) fbe.getCause()).getBeanName());
                tde.setTestCaseName(((BeanCreationException) fbe).getResourceDescription());
                tde.setMessage(tde.getMessage() + LogbackTag.TAG_SEPERATOR + tde.getTestCaseName()
                        + LogbackTag.TAG_SEPERATOR + tde.getTestStepName());
                throw (TestDataException) itr.getThrowable();
            } else { // other test case bean creation errors. need to create
                // another exception to handle it.
                String[] fullST = Utils.stackTrace(fbe, false);
                int TWO = 2; // NOPMD
                if (fullST.length < TWO) {
                    LogbackWriter.writeSysError("java internal error in stack trace.");
                } else {
                    String errLog = fullST[1];
                    if (null == errLog)
                        LogbackWriter.writeSysError("java internal error in stack trace.");
                    else
                        LogbackWriter.writeSysError(errLog);
                }
                throw fbe;

            }
        } else {
            throw fbe;
        }
    }
}

From source file:org.paxml.tag.SpringXmlEntityFactory.java

/**
 * Get the cached application context with paxml resource.
 * //w w w. j  ava2 s .  c om
 * @param targetResource
 *            the paxml resource pointing to a spring bean xml file.
 * @return the application context.
 */
public static ApplicationContext getApplicationContext(PaxmlResource targetResource) {
    if (log.isInfoEnabled()) {
        log.debug("Requesting spring resource: " + targetResource.getPath());
    }
    ApplicationContext factory = FACTORY_CACHE.get(targetResource);
    if (factory == null) {
        if (log.isInfoEnabled()) {
            log.info("Loading spring xml: " + targetResource.getPath());
        }
        if (targetResource instanceof ClasspathResource) {
            factory = new ClassPathXmlApplicationContext(targetResource.getPath());
        } else {
            factory = new FileSystemXmlApplicationContext(targetResource.getPath());
        }
        ApplicationContext existing = FACTORY_CACHE.putIfAbsent(targetResource, factory);
        if (existing != null) {
            factory = existing;
        }
    }
    return factory;
}

From source file:com.emc.vipr.sync.ViPRSync.java

/**
 * Initializes a Spring Application Context from the given file and
 * bootstraps the ViPRSync object from there.
 *//*from w w w.  ja  va2  s .  co  m*/
protected static ViPRSync springBootstrap(String pathToSpringXml) {
    File springXml = new File(pathToSpringXml);
    if (!springXml.exists()) {
        throw new ConfigurationException("the Spring XML file: " + springXml + " does not exist");
    }

    l4j.info("loading configuration from Spring XML file: " + springXml);
    FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext(pathToSpringXml);

    if (!ctx.containsBean(ROOT_SPRING_BEAN)) {
        throw new ConfigurationException("your Spring XML file: " + springXml + " must contain one bean named '"
                + ROOT_SPRING_BEAN + "' that initializes an ViPRSync object");
    }

    return ctx.getBean(ROOT_SPRING_BEAN, ViPRSync.class);
}

From source file:org.age.services.worker.internal.DefaultWorkerService.java

private void setupTaskFromConfig(final @NonNull String configPath) {
    assert nonNull(configPath);
    assert !isTaskRunning() : "Task is already running.";

    taskLock.writeLock().lock();//from www. j  av a  2  s . c o  m
    try {
        log.debug("Setting up task from config {}.", configPath);

        log.debug("Creating internal Spring context.");
        final FileSystemXmlApplicationContext taskContext = new FileSystemXmlApplicationContext(configPath);
        prepareContext(taskContext);

        currentClassName = taskContext.getType("runnable").getCanonicalName();

        log.debug("Task setup finished.");
    } catch (final BeanCreationException e) {
        log.error("Cannot create the task.", e);
        cleanUpAfterTask();
    } finally {
        taskLock.writeLock().unlock();
    }
}

From source file:com.bagri.xdm.process.coherence.factory.SpringAwareCacheFactory.java

private static synchronized void initializeContext(String sCacheConfig, String sAppContext) {
    if (appContext == null) {
        azzert(sAppContext != null && sAppContext.length() > 0, "Application context location required");

        appContext = sCacheConfig.startsWith("file:") ? new FileSystemXmlApplicationContext(sAppContext)
                : new ClassPathXmlApplicationContext(sAppContext);

        // register a shutdown hook so the bean factory cleans up
        // upon JVM exit
        ((AbstractApplicationContext) appContext).registerShutdownHook();
    }//  ww  w  .  j a v  a 2  s.c o m
}

From source file:org.trpr.platform.runtime.impl.bootstrap.spring.Bootstrap.java

/**
 * Interface method implementation// w w  w .java  2s  . com
 * @see BootstrapManagedBean#start()
 */
public void start() throws Exception {
    // logging has not been configured, so use System.out.println();
    long start = System.currentTimeMillis();
    System.out.println("** Trooper runtime Bootstrap start **");

    // check if the tccl of the invoking thread is the same as the one that was used in #init(), else use the stored tccl
    if (Thread.currentThread().getContextClassLoader() != this.tccl) {
        Thread.currentThread().setContextClassLoader(tccl);
    }

    runtimeVariables = RuntimeVariables.getInstance();
    try {

        // configure the logging framework from a path relative to where the bootstrap config file is specified
        configureLogging();

        // Load the bootstrap config file
        File bootstrapFile = new File(this.bootstrapConfigFile);
        // add the "file:" prefix to file names to get around strange behavior of FileSystemXmlApplicationContext that converts absolute path 
        // to relative path
        this.containerContext = new FileSystemXmlApplicationContext(
                FILE_PREFIX + bootstrapFile.getAbsolutePath());
        BootstrapInfo bootstrapInfo = (BootstrapInfo) this.containerContext.getBean(BootstrapInfo.class);

        // see if the path to projects root has been specified as a relative
        // path to the bootstrap.config file and
        // replace it with appropriate value to make it absolute         
        String path = bootstrapInfo.getProjectsRoot();
        if (path.startsWith(RuntimeConstants.CONFIG_FILE_NAME_TOKEN)) {
            path = path.replace(RuntimeConstants.CONFIG_FILE_NAME_TOKEN,
                    new File(this.bootstrapConfigFile).getParent());
            bootstrapInfo.setProjectsRoot(new File(path).getCanonicalPath());
        }

        this.container = bootstrapInfo.getContainer();
        setPlatformVariablesFromConfig(bootstrapInfo);

        // export the RuntimeConstants.TRPR_APP_NAME property, if set, to System properties for use in JMX export
        try {
            System.setProperty(RuntimeConstants.TRPR_APP_NAME,
                    RuntimeVariables.getVariable(RuntimeConstants.TRPR_APP_NAME));
        } catch (Exception e) {
            // Catch and consume this Exception. Only impact is on JMX binding name as exported by BootstrapModelMBeanExporter
        }

        // initialize the container
        this.container.init();

    } catch (Exception e) {
        // catch all block to consume and minimally log bootstrap errors
        // Log to both LOGGER and System.out.println();
        LOGGER.error("Fatal error in bootstrap sequence. Cannot continue!", e);
        System.out.println("Fatal error in bootstrap sequence. Cannot continue!");
        e.printStackTrace(System.out);
        return;
    }

    // publish an event that this Bootstrap has started
    publishBootstrapEvent("** Trooper bootstrap complete **", RuntimeConstants.BOOTSTRAP_START_STATE);

    // Log successful start up details
    String ccDisplay = RuntimeVariables.getContainerType() == null ? "None"
            : RuntimeVariables.getContainerType();
    final Object[] displayArgs = { RuntimeVariables.getRuntimeNature(), ccDisplay,
            (System.currentTimeMillis() - start), this.hostName, };
    LOGGER.info(STARTUP_DISPLAY.format(displayArgs));
    LOGGER.info("** Trooper Bootstrap complete **");
}

From source file:terrastore.startup.Startup.java

private ApplicationContext startContext() throws Exception {
    String location = getConfigFileLocation();
    ApplicationContext context = new FileSystemXmlApplicationContext(location);
    return context;
}