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, boolean refresh) throws BeansException 

Source Link

Document

Create a new FileSystemXmlApplicationContext, loading the definitions from the given XML files.

Usage

From source file:org.trpr.platform.servicefw.impl.spring.SpringServicesContainer.java

/**
 * Interface method implementation/*  ww w.  ja v  a2  s.  com*/
 * @see ServiceContainer#init()
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public void init() throws PlatformException {
    // The common service beans context is loaded first using the Platform common beans context as parent
    String commonContextFile = FILE_PREFIX + FileLocator
            .findUniqueFile(ServiceFrameworkConstants.COMMON_SPRING_SERVICES_CONFIG).getAbsolutePath();
    this.commonServiceBeansContext = new FileSystemXmlApplicationContext(new String[] { commonContextFile },
            ApplicationContextFactory.getCommonBeansContext());

    // load the service beans and set the commons bean context as the parent
    File[] serviceBeansFiles = FileLocator.findFiles(ServiceFrameworkConstants.SPRING_SERVICES_CONFIG);
    List<String> fileNamesList = new LinkedList<String>();
    for (File serviceBeansFile : serviceBeansFiles) {
        // add the "file:" prefix to file names to get around strange behavior of FileSystemXmlApplicationContext that converts absolute path 
        // to relative path
        fileNamesList.add(FILE_PREFIX + serviceBeansFile.getAbsolutePath());
    }
    this.servicesContext = new FileSystemXmlApplicationContext((String[]) fileNamesList.toArray(new String[0]),
            this.commonServiceBeansContext);

    // now initialize context, statistics gatherer and registry
    this.serviceContext = (ServiceContext) this.commonServiceBeansContext
            .getBean(SpringServicesContainer.SERVICE_CONTEXT_BEAN);
    this.serviceContext.setServiceContainer(this);
    ((ServiceStatisticsGatherer) this.commonServiceBeansContext
            .getBean(SpringServicesContainer.SERVICE_STATISTICS_BEAN)).setServiceContainer(this);

    this.serviceRegistry = (ServiceRegistry) this.commonServiceBeansContext
            .getBean(SpringServicesContainer.SERVICE_REGISTRY_BEAN);

    // Set this ServiceContainer and ServiceRegistry on the BrokerFactory TODO : Need a better way of doing this
    BrokerFactory.setServiceContainer(this);
    BrokerFactory.setServiceRegistry(this.serviceRegistry);

    // register all service infos with the registry
    String[] serviceBeanIds = this.servicesContext.getBeanNamesForType(Service.class);
    for (String serviceBeanId : serviceBeanIds) {
        try {
            // find the project name from the Resource that was used to load the bean
            String projectName = this.getProjectName(
                    ((UrlResource) ((AbstractBeanDefinition) this.servicesContext.getBeanFactory()
                            .getBeanDefinition(serviceBeanId)).getResource()).getFile().getAbsolutePath());
            String[] serviceNameParts = serviceBeanId.split(SERVICE_VERSION_SEPARATOR);
            // TODO find a way to determine domain names for a service, using ServiceFrameworkConstants.DEFAULT_DOMAIN for now
            this.serviceRegistry.addServiceInfoToRegistry(serviceNameParts[0], serviceNameParts[1], projectName,
                    ServiceFrameworkConstants.DEFAULT_DOMAIN);
        } catch (Exception ex) {
            // the service name is not as per standard naming convention of <serviceName>_<serviceVersion>. Throw an exception
            throw new ServiceException(
                    "Invalid service bean name? Convention is <serviceName>_<serviceVersion>. Offending bean name is : "
                            + serviceBeanId,
                    ex);
        }
    }

    // now initialize ServiceCompartmentS for all ServiceS
    // create ServiceCompartment instances for the located services
    this.serviceCompartments = new HashMap<ServiceKey, ServiceCompartment<T, S>>();
    this.serviceInfos = new HashMap<ServiceKey, ServiceInfo>();
    for (ServiceInfo serviceInfo : this.serviceRegistry.getAllServiceInfos()) {
        ServiceKey serviceKey = serviceInfo.getServiceKey();
        serviceInfos.put(serviceKey, serviceInfo);
        ServiceCompartment<T, S> serviceCompartment = new ServiceCompartmentImpl<T, S>(serviceInfo);
        serviceCompartment.init();
        serviceCompartments.put(serviceKey, serviceCompartment);
    }
}

From source file:org.apache.camel.spring.Main.java

protected AbstractApplicationContext createDefaultApplicationContext() {
    // file based
    if (getFileApplicationContextUri() != null) {
        String[] args = getFileApplicationContextUri().split(";");

        ApplicationContext parentContext = getParentApplicationContext();
        if (parentContext != null) {
            return new FileSystemXmlApplicationContext(args, parentContext);
        } else {//from   w  ww  .j  av a  2s  . co  m
            return new FileSystemXmlApplicationContext(args);
        }
    }

    // default to classpath based
    String[] args = getApplicationContextUri().split(";");
    ApplicationContext parentContext = getParentApplicationContext();
    if (parentContext != null) {
        return new ClassPathXmlApplicationContext(args, parentContext);
    } else {
        return new ClassPathXmlApplicationContext(args);
    }
}

From source file:org.red5.server.Bootstrap.java

/**
 * Launch Red5 under it's own classloader
 *  /* w  w  w  .j  a v a2  s.  co m*/
 */
public void launch() {
    try {
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        //System.out.printf("Launch - Thread classloader: %s\n", loader);

        //create red5 app context
        FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext(
                new String[] { "classpath:/red5.xml" }, false);
        ctx.setClassLoader(loader);

        //install the slf4j bridge (mostly for JUL logging)
        SLF4JBridgeHandler.install();
        //we create the logger here so that it is instanced inside the expected 
        //classloader
        Logger log = Red5LoggerFactory.getLogger(Bootstrap.class);
        //version info banner
        log.info("{} (http://www.osflash.org/red5)", Red5.getVersion());
        //see which logger binder has been instanced
        log.trace("Logger binder: {}", StaticLoggerBinder.getSingleton().getClass().getName());

        //refresh must be called before accessing the bean factory
        ctx.refresh();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:se.trillian.goodies.spring.ApplicationLauncher.java

public Integer start(String[] args) {
    String logFile = null;// w  w w.ja va2  s  .  c  om
    ArrayList<String> springFiles = new ArrayList<String>();
    try {
        int i = 0;
        if (i < args.length && args[i].toLowerCase().matches("logback.*\\.xml")) {
            logFile = args[i++];
        }

        while (i < args.length) {
            springFiles.add(args[i++]);
        }
    } catch (Throwable t) {
        printUsage(t.getMessage());
        return new Integer(1);
    }

    if (logFile == null) {
        logFile = getDefaultLogbackFile();
    }

    try {
        /*
         * Initialize the logback logging system.
         */
        if (logFile != null) {
            log.info("Configuring logback from file '" + logFile + "'");
            LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
            lc.reset();
            lc.putProperty("se.trillian.goodies.hostname", hostName);
            lc.putProperty("se.trillian.goodies.hostname.full", fullHostName);

            try {
                JoranConfigurator configurator = new JoranConfigurator();
                configurator.setContext(lc);
                configurator.doConfigure(logFile);
            } catch (JoranException je) {
                StatusPrinter.print(lc);
            }
        }
    } catch (Throwable t) {
        log.error("Failed to initialize logback logging system: " + t.getMessage(), t);
        return new Integer(2);
    }

    try {
        /*
         * Load the Spring bean configuration files.
         */
        if (springFiles.isEmpty()) {
            springFiles.add("classpath*:/spring/*.xml");
        }
        log.info("Loading spring files: " + springFiles);
        context = new FileSystemXmlApplicationContext(springFiles.toArray(new String[0]), false);
        context.refresh();
    } catch (Throwable t) {
        log.error("Unable to load Spring configuration files", t);
        return new Integer(3);
    }

    return null;
}

From source file:maltcms.ui.fileHandles.properties.tools.SceneParser.java

/**
 * Supports both absolute and relative paths and also arbitrary combinations
 * of the two. In case of relative paths, the location of the file
 * containing the pipeline configuration is used as basedir to resolve the
 * relative path.//from   w  w w.  j a v  a  2s.c  o  m
 *
 * Example for relative path:
 * <pre>pipelines.properties = fragmentCommands/myClassName.properties</pre>
 * Example for absolute path:
 * <pre>pipelines.properties = /home/juser/myFunkyDir/myClassName.properties</pre>
 *
 * <pre>pipeline.properties</pre> accepts multiple entries, separated by a
 * ',' (comma) character. Example:
 * <pre>pipeline.properties = fragmentCommands/myClassName.properties,/home/juser/myFunkyDir/myClassName.properties</pre>
 *
 * @param filename the filename of the base configuration, which contains
 * the pipeline= and pipeline.properties keys.
 * @param cfg the configuration object resembling the content of filename.
 * @param scene the graph scene into which to load the configuration.
 */
public static void parseIntoScene(String filename, Configuration cfg, PipelineGraphScene scene) {
    Logger.getLogger(SceneParser.class.getName())
            .info("###################################################################");
    Logger.getLogger(SceneParser.class.getName()).info("Creating graph scene from file");
    File f = new File(filename);
    //Get pipeline from configuration
    cfg.addProperty("config.basedir", f.getParentFile().getAbsoluteFile().toURI().getPath());
    String pipelineXml = cfg.getString("pipeline.xml");

    FileSystemXmlApplicationContext fsxmac = new FileSystemXmlApplicationContext(new String[] { pipelineXml },
            true);
    ICommandSequence commandSequence = fsxmac.getBean("commandPipeline",
            cross.datastructures.pipeline.CommandPipeline.class);
    //        String[] pipes = pipeline.toArray(new String[]{});
    Logger.getLogger(SceneParser.class.getName()).log(Level.INFO, "Pipeline elements: {0}",
            commandSequence.getCommands());
    PipelineGeneralConfigWidget pgcw = (PipelineGeneralConfigWidget) scene.createGeneralWidget();
    pgcw.setProperties(cfg);
    String lastNode = null;
    String edge;
    int edgeCounter = 0;
    int nodeCounter = 0;
    Configuration pipeHash = new PropertiesConfiguration();
    for (IFragmentCommand command : commandSequence.getCommands()) {
        Collection<String> configKeys = cross.annotations.AnnotationInspector
                .getRequiredConfigKeys(command.getClass());
        //        for (String pipe : pipes) {
        String nodeId = command.getClass().getCanonicalName() + "" + nodeCounter;
        PipelineElementWidget node = (PipelineElementWidget) scene.addNode(nodeId);
        //            node.setPropertyFile();

        //            System.out.println("Parsing pipeline element " + pipeCfg.getAbsolutePath());
        node.setBean(command);
        node.setLabel(command.getClass().getSimpleName());
        node.setCurrentClassProperties();
        Configuration prop = node.getProperties();
        //            pipeHash = PropertyLoader.getHash(pipeCfg.getAbsolutePath());
        //            node.setPropertyFile(pipeCfg.getAbsolutePath());
        Iterator iter = pipeHash.getKeys();
        while (iter.hasNext()) {
            String key = (String) iter.next();
            prop.setProperty(key, pipeHash.getProperty(key));
        }
        node.setProperties(prop);

        if (lastNode != null) {
            edge = "Ledge" + edgeCounter++;
            scene.addEdge(edge);
            Logger.getLogger(SceneParser.class.getName()).log(Level.INFO,
                    "Adding edge between lastNode {0} and {1}", new Object[] { lastNode, nodeId });
            scene.setEdgeSource(edge, lastNode);
            scene.setEdgeTarget(edge, nodeId);
            scene.validate();
        }
        //                x += dx;
        //                y += dy;
        scene.validate();
        lastNode = nodeId;
        nodeCounter++;
    }

    scene.validate();
    SceneLayouter.layoutVertical(scene);
}

From source file:com.flipkart.phantom.runtime.impl.spring.ServiceProxyComponentContainer.java

/**
 * Interface method implementation. Locates and loads all configured proxy handlers.
 * @see ComponentContainer#init()/* w  w w.j  a v  a 2s.c o  m*/
 */
public void init() throws PlatformException {
    //Register HystrixEventNotifier
    if (HystrixPlugins.getInstance().getEventNotifier() == null) {
        HystrixPlugins.getInstance().registerEventNotifier(new HystrixEventReceiver());
    }
    // store the thread's context class loader for later use in on the fly loading of proxy handler app contexts
    this.tccl = Thread.currentThread().getContextClassLoader();

    // The common proxy handler beans context is loaded first using the Platform common beans context as parent
    // load this from classpath as it is packaged with the binaries
    ApplicationContextFactory defaultCtxFactory = null;
    for (BootstrapExtension be : this.loadedBootstrapExtensions) {
        if (ApplicationContextFactory.class.isAssignableFrom(be.getClass())) {
            defaultCtxFactory = (ApplicationContextFactory) be;
            break;
        }
    }

    ServiceProxyComponentContainer.commonProxyHandlerBeansContext = new ClassPathXmlApplicationContext(
            new String[] { ServiceProxyFrameworkConstants.COMMON_PROXY_CONFIG },
            defaultCtxFactory.getCommonBeansContext());
    // add the common proxy beans independently to the list of proxy handler contexts as common handlers are declared there
    this.handlerConfigInfoList
            .add(new HandlerConfigInfo(new File(ServiceProxyFrameworkConstants.COMMON_PROXY_CONFIG), null,
                    ServiceProxyComponentContainer.commonProxyHandlerBeansContext));

    // Get the Config Service Bean
    this.configService = (SPConfigServiceImpl) ServiceProxyComponentContainer.commonProxyHandlerBeansContext
            .getBean(ServiceProxyComponentContainer.CONFIG_SERVICE_BEAN);
    ((SPConfigServiceImpl) this.configService).setComponentContainer(this);

    // Load additional if runtime nature is "server". This context is the new common beans context
    if (RuntimeVariables.getRuntimeNature().equalsIgnoreCase(RuntimeConstants.SERVER)) {
        ServiceProxyComponentContainer.commonProxyHandlerBeansContext = new ClassPathXmlApplicationContext(
                new String[] { ServiceProxyFrameworkConstants.COMMON_PROXY_SERVER_NATURE_CONFIG },
                ServiceProxyComponentContainer.getCommonProxyHandlerBeansContext());
        // now add the common server nature proxy hander beans to the contexts list
        this.handlerConfigInfoList.add(new HandlerConfigInfo(
                new File(ServiceProxyFrameworkConstants.COMMON_PROXY_SERVER_NATURE_CONFIG), null,
                ServiceProxyComponentContainer.getCommonProxyHandlerBeansContext()));
    }

    // locate and load a single common proxy handler bean XML files which is initialized before all other individual handlers
    // in case multiple are found fail the bootstrap.
    File[] commonProxyHandlerConfigFiles = FileLocator
            .findFiles(ServiceProxyFrameworkConstants.COMMON_PROXY_HANDLER_CONFIG);
    if (commonProxyHandlerConfigFiles.length > 0) {
        if (commonProxyHandlerConfigFiles.length == 1) {
            File commonProxyHandlerConfigFile = commonProxyHandlerConfigFiles[0];
            // load the common proxy handler
            this.loadProxyHandlerContext(new HandlerConfigInfo(commonProxyHandlerConfigFile));
            LOGGER.info("Loaded Common Proxy Handler Config: " + commonProxyHandlerConfigFile);
        } else {
            final String errorMessage = "Found multiple common-proxy-handler-configs, only one is allowed";
            LOGGER.error(errorMessage);
            for (File commonHandlerConfig : commonProxyHandlerConfigFiles)
                LOGGER.error(commonHandlerConfig.getAbsolutePath());
            throw new PlatformException(errorMessage);
        }
    }

    // locate and load the individual proxy handler bean XML files using the common proxy handler beans context as parent
    File[] proxyHandlerBeansFiles = FileLocator
            .findFiles(ServiceProxyFrameworkConstants.SPRING_PROXY_HANDLER_CONFIG);
    for (File proxyHandlerBeansFile : proxyHandlerBeansFiles) {
        HandlerConfigInfo handlerConfigInfo = new HandlerConfigInfo(proxyHandlerBeansFile);
        // load the proxy handler's appcontext
        this.loadProxyHandlerContext(handlerConfigInfo);
        LOGGER.info("Loaded: " + proxyHandlerBeansFile);
    }

    // add the proxy listener beans to the contexts list (these have the thrift handlers)
    File[] proxyListenerBeanFiles = FileLocator
            .findFiles(ServiceProxyFrameworkConstants.SPRING_PROXY_LISTENER_CONFIG);
    for (File proxyListenerBeanFile : proxyListenerBeanFiles) {
        // locate and load the service proxy listener defined in the file identified by {@link ServiceProxyFrameworkConstants#SPRING_PROXY_LISTENER_CONFIG}
        AbstractApplicationContext listenerContext = new FileSystemXmlApplicationContext(
                new String[] { FILE_PREFIX + proxyListenerBeanFile.getAbsolutePath() },
                ServiceProxyComponentContainer.getCommonProxyHandlerBeansContext());
        this.handlerConfigInfoList.add(new HandlerConfigInfo(proxyListenerBeanFile, null, listenerContext));
        LOGGER.info("Loaded: " + proxyListenerBeanFile);
    }

    // load all registries
    for (HandlerConfigInfo handlerConfigInfo : handlerConfigInfoList) {
        // handler registries
        String[] registryBeans = handlerConfigInfo.getProxyHandlerContext()
                .getBeanNamesForType(AbstractHandlerRegistry.class);
        for (String registryBean : registryBeans) {
            AbstractHandlerRegistry registry = (AbstractHandlerRegistry) handlerConfigInfo
                    .getProxyHandlerContext().getBean(registryBean);
            LOGGER.info("Found handler registry: " + registry.getClass().getName());
            // init the Registry
            try {
                this.taskContext = (TaskContext) ServiceProxyComponentContainer
                        .getCommonProxyHandlerBeansContext()
                        .getBean(ServiceProxyComponentContainer.TASK_CONTEXT_BEAN);
                AbstractHandlerRegistry.InitedHandlerInfo[] initedHandlerInfos = registry
                        .init(this.handlerConfigInfoList, this.taskContext);
                LOGGER.info("Initialized handler registry: " + registry.getClass().getName());
                //Add the file path of each inited handler to SPConfigService (for configuration console)
                for (AbstractHandlerRegistry.InitedHandlerInfo initedHandlerInfo : initedHandlerInfos) {
                    this.configService.addHandlerConfigPath(
                            initedHandlerInfo.getHandlerConfigInfo().getXmlConfigFile(),
                            initedHandlerInfo.getInitedHandler());
                }
            } catch (Exception e) {
                LOGGER.error("Error initializing registry: " + registry.getClass().getName());
                throw new PlatformException("Error initializing registry: " + registry.getClass().getName(), e);
            }
            // add registry to config
            this.configService.addHandlerRegistry(registry);
            // add registry to local list
            this.registries.add(registry);
        }

        // add all network servers to config
        String[] networkServerBeans = handlerConfigInfo.getProxyHandlerContext()
                .getBeanNamesForType(AbstractNetworkServer.class);
        for (String networkServerBean : networkServerBeans) {
            AbstractNetworkServer networkServer = (AbstractNetworkServer) handlerConfigInfo
                    .getProxyHandlerContext().getBean(networkServerBean);
            // init the server
            try {
                networkServer.init();
            } catch (Exception e) {
                LOGGER.error("Error initializeing network server: " + networkServer.getServerType() + ": "
                        + networkServer.getServerEndpoint());
                throw new PlatformException("Error initializeing network server: "
                        + networkServer.getServerType() + ": " + networkServer.getServerEndpoint(), e);
            }
            configService.addDeployedNetworkServer(networkServer);
        }

    }
}

From source file:org.apache.ctakes.ytex.kernel.evaluator.CorpusKernelEvaluatorImpl.java

public static void main(String args[]) throws Exception {
    Options options = initOptions();/* w w  w. ja v  a  2  s  .co m*/

    if (args.length == 0) {
        printHelp(options);
    } else {
        CommandLineParser parser = new GnuParser();
        try {
            // parse the command line arguments
            CommandLine line = parser.parse(options, args);
            // parse the command line arguments
            String beanRefContext = line.getOptionValue("beanref", "classpath*:simSvcBeanRefContext.xml");
            String contextName = line.getOptionValue("appctx", "kernelApplicationContext");
            String beans = line.getOptionValue("beans");
            ApplicationContext appCtx = (ApplicationContext) ContextSingletonBeanFactoryLocator
                    .getInstance(beanRefContext).useBeanFactory(contextName).getFactory();
            ApplicationContext appCtxSource = appCtx;
            if (beans != null) {
                appCtxSource = new FileSystemXmlApplicationContext(new String[] { beans }, appCtx);
            }
            evalKernel(appCtxSource, line);
        } catch (ParseException e) {
            printHelp(options);
            throw e;
        }
    }
}

From source file:org.apache.ctakes.ytex.KernelLauncher.java

/**
 * @param args/*  w  w w  .  j  av  a 2 s .c  o  m*/
 */
public static void main(String[] args) throws Exception {
    Options options = initOptions();

    if (args.length == 0) {
        printHelp(options);
    } else {
        CommandLineParser parser = new GnuParser();
        try {
            // parse the command line arguments
            CommandLine line = parser.parse(options, args);
            String storeInstanceMap = line.getOptionValue("storeInstanceMap");
            boolean evalKernel = line.hasOption("evalKernel");
            String exportBagOfWords = line.getOptionValue("exportBagOfWords");
            if (!evalKernel && storeInstanceMap == null && exportBagOfWords == null) {
                System.out.println("specify either -evalKernel, -storeInstanceMap, or -exportBagOfWords");
                printHelp(options);
            } else {

                // parse the command line arguments
                // by default use the kernelBeanRefContext
                // when evaluating kernel, by default use the
                // simSvcBeanRefContext.xml
                // don't want to load that for other tasks as the simSvc
                // loads the UMLS object graph which needs lots of memory
                String beanRefContext = line.getOptionValue("beanref",
                        evalKernel ? "classpath*:org/apache/ctakes/ytex/simSvcBeanRefContext.xml"
                                : "classpath*:org/apache/ctakes/ytex/kernelBeanRefContext.xml");
                String contextName = line.getOptionValue("appctx", "kernelApplicationContext");
                String beans = line.getOptionValue("beans");
                ApplicationContext appCtx = (ApplicationContext) ContextSingletonBeanFactoryLocator
                        .getInstance(beanRefContext).useBeanFactory(contextName).getFactory();
                ApplicationContext appCtxSource = appCtx;
                if (beans != null) {
                    appCtxSource = new FileSystemXmlApplicationContext(new String[] { beans }, appCtx);
                }
                if (storeInstanceMap != null) {
                    storeInstanceMap(appCtxSource, storeInstanceMap, line);
                    //               } else if (evalKernel) {
                    //                  evalKernel(appCtxSource, line);
                    //               } else if (exportBagOfWords != null) {
                    //                  exportBagOfWords(appCtxSource, exportBagOfWords, line);
                }
            }
        } catch (ParseException e) {
            printHelp(options);
            throw e;
        }
    }
}