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

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

Introduction

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

Prototype

@Override
    public void refresh() throws BeansException, IllegalStateException 

Source Link

Usage

From source file:net.phoenix.thrift.server.Server.java

/**
 * ? spring?/*  w  w w .  ja v  a  2 s .  c  o m*/
 * @param args
 * @throws Exception
 */
public static int main(String[] args) throws Exception {
    if (args.length == 0 || StringUtils.isEmpty(args[0])) {
        LOG.error("Please assign spring configuration file . ");
        return 0;
    }
    FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext();
    context.setConfigLocation(args[0]);
    context.registerShutdownHook();
    context.refresh();
    context.close();
    return 1;
}

From source file:com.predic8.membrane.annot.bean.MCUtil.java

@SuppressWarnings("unchecked")
public static <T> T fromXML(Class<T> clazz, final String xml) {
    final String MAGIC = "magic.xml";

    FileSystemXmlApplicationContext fsxacApplicationContext = new FileSystemXmlApplicationContextExtension(
            MAGIC, xml);/*from w  w  w.  ja v a2 s  .co m*/
    fsxacApplicationContext.setConfigLocation(MAGIC);

    fsxacApplicationContext.refresh();

    Object bean = null;

    if (fsxacApplicationContext.containsBean("main")) {
        bean = fsxacApplicationContext.getBean("main");
    } else {
        Collection<T> beans = fsxacApplicationContext.getBeansOfType(clazz).values();
        if (beans.size() > 1)
            throw new InvalidParameterException(
                    "There is more than one bean of type '" + clazz.getName() + "'.");
        bean = beans.iterator().next();
    }

    if (bean == null)
        throw new InvalidParameterException("Did not find bean with ID 'main'.");

    if (!clazz.isAssignableFrom(bean.getClass()))
        throw new InvalidParameterException("Bean 'main' is not a " + clazz.getName() + " .");

    return (T) bean;
}

From source file:org.hbird.business.core.Starter.java

/**
 * Method to read the XML assembly file and run the main
 * /*from   w w  w  .  j  av a2 s  .c om*/
 * @throws Exception
 */
@SuppressWarnings("resource")
protected void boot() throws Exception {
    LOG.info("Starting Hummingbird based system.");

    Main main = new Main();
    main.enableHangupSupport();

    /* Read the configuration file as the first argument. If not set, then we try the default name. */
    String assemblyFile = System.getProperty("hbird.assembly") == null ? "classpath:main.xml"
            : System.getProperty("hbird.assembly");

    LOG.info("Reading assembly file '{}'", assemblyFile);

    FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext(new String[] { assemblyFile },
            false);
    context.setDisplayName(CONTEXT_NAME + "-" + (++counter));
    LOG.info("Created Spring AppicationContext '{}'", context.getDisplayName());
    context.refresh();
    main.run();
}

From source file:org.pentaho.agilebi.spoon.visualizations.VisualizationManager.java

protected void loadVisualizationFile(File file) {
    try {/*from   w w  w  .j  a va2  s  . co m*/
        FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext(
                new String[] { file.getPath() }, false);
        context.setClassLoader(getClass().getClassLoader());
        context.refresh();
        Map beans = context.getBeansOfType(IVisualization.class);
        for (Object key : beans.keySet()) {
            IVisualization vis = (IVisualization) beans.get(key);
            if (vis.getOrder() >= 0) {
                visualizations.add(vis);
            }
        }
    } catch (XmlBeanDefinitionStoreException e) {
        // TODO: introduce logging
        e.printStackTrace();
    }
}

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

/**
 * Launch Red5 under it's own classloader
 *//*from   w  ww  .jav  a 2  s.  c  o  m*/
public void launch() {
    System.out.printf("Root: %s\nDeploy type: %s\nLogback selector: %s\n", System.getProperty("red5.root"),
            System.getProperty("red5.deployment.type"), System.getProperty("logback.ContextSelector"));
    try {
        // install the slf4j bridge (mostly for JUL logging)
        SLF4JBridgeHandler.install();
        // we create the logger here so that it is instanced inside the expected classloader
        // check for the logback disable flag
        boolean useLogback = Boolean.valueOf(System.getProperty("useLogback", "true"));
        Red5LoggerFactory.setUseLogback(useLogback);
        // get the first logger
        Logger log = Red5LoggerFactory.getLogger(Launcher.class);
        // version info banner
        log.info("{} (http://code.google.com/p/red5/)", Red5.getVersion());
        // pimp red5
        System.out.printf("%s (http://code.google.com/p/red5/)\n", Red5.getVersion());
        // create red5 app context
        FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext(
                new String[] { "classpath:/red5.xml" }, false);
        // set the current threads classloader as the loader for the factory/appctx
        ctx.setClassLoader(Thread.currentThread().getContextClassLoader());
        // refresh must be called before accessing the bean factory
        ctx.refresh();
        /*
        if (log.isTraceEnabled()) {
           String[] names = ctx.getBeanDefinitionNames();
           for (String name : names) {
              log.trace("Bean name: {}", name);
           }
        }
        */
    } catch (Throwable t) {
        System.out.printf("Exception %s\n", t);
        System.exit(9999);
    }
}

From source file:com.browseengine.bobo.api.BoboIndexReader.java

private static Collection<FacetHandler<?>> loadFromIndex(File file, WorkArea workArea) throws IOException {
    // File springFile = new File(file, SPRING_CONFIG);
    // FileSystemXmlApplicationContext appCtx =
    //   new FileSystemXmlApplicationContext("file:" + springFile.getAbsolutePath());
    //return (Collection<FacetHandler<?>>) appCtx.getBean("handlers");

    Set<Entry<Class<?>, Object>> entries = workArea.map.entrySet();
    FileSystemXmlApplicationContext appCtx = new FileSystemXmlApplicationContext();
    for (Entry<Class<?>, Object> entry : entries) {
        Object obj = entry.getValue();
        if (obj instanceof ClassLoader) {
            appCtx.setClassLoader((ClassLoader) obj);
            break;
        }/* w  w w. j  av a  2 s.  com*/
    }

    String absolutePath = file.getAbsolutePath();
    String partOne = absolutePath.substring(0, absolutePath.lastIndexOf(File.separator));
    String partTwo = URLEncoder.encode(absolutePath.substring(absolutePath.lastIndexOf(File.separator) + 1),
            "UTF-8");
    absolutePath = partOne + File.separator + partTwo;

    File springFile = new File(new File(absolutePath), SPRING_CONFIG);
    appCtx.setConfigLocation("file:" + springFile.getAbsolutePath());
    appCtx.refresh();

    return (Collection<FacetHandler<?>>) appCtx.getBean("handlers");

}

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

/**
 * Launch Red5 under it's own classloader
 *  /* w w w .ja v  a 2  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:net.frontlinesms.FrontlineSMS.java

/** Initialise {@link #applicationContext}. */
public void initApplicationContext() throws DataAccessResourceFailureException {
    // Load the data mode from the app.properties file
    AppProperties appProperties = AppProperties.getInstance();

    LOG.info("Load Spring/Hibernate application context to initialise DAOs");

    // Create a base ApplicationContext defining the hibernate config file we need to import
    StaticApplicationContext baseApplicationContext = new StaticApplicationContext();
    baseApplicationContext.registerBeanDefinition("hibernateConfigLocations",
            createHibernateConfigLocationsBeanDefinition());

    // Get the spring config locations
    String databaseExternalConfigPath = ResourceUtils.getConfigDirectoryPath()
            + ResourceUtils.PROPERTIES_DIRECTORY_NAME + File.separatorChar
            + appProperties.getDatabaseConfigPath();
    String[] configLocations = getSpringConfigLocations(databaseExternalConfigPath);
    baseApplicationContext.refresh();//from w ww.ja  v a  2  s  .  c o  m

    FileSystemXmlApplicationContext applicationContext = new FileSystemXmlApplicationContext(configLocations,
            false, baseApplicationContext);
    this.applicationContext = applicationContext;

    // Add post-processor to handle substituted database properties
    PropertyPlaceholderConfigurer propertyPlaceholderConfigurer = new PropertyPlaceholderConfigurer();
    String databasePropertiesPath = ResourceUtils.getConfigDirectoryPath()
            + ResourceUtils.PROPERTIES_DIRECTORY_NAME + File.separatorChar
            + appProperties.getDatabaseConfigPath() + ".properties";
    propertyPlaceholderConfigurer.setLocation(new FileSystemResource(new File(databasePropertiesPath)));
    propertyPlaceholderConfigurer.setIgnoreResourceNotFound(true);
    applicationContext.addBeanFactoryPostProcessor(propertyPlaceholderConfigurer);
    applicationContext.refresh();

    LOG.info("Context loaded successfully.");

    this.pluginManager = new PluginManager(this, applicationContext);

    LOG.info("Getting DAOs from application context...");
    groupDao = (GroupDao) applicationContext.getBean("groupDao");
    groupMembershipDao = (GroupMembershipDao) applicationContext.getBean("groupMembershipDao");
    contactDao = (ContactDao) applicationContext.getBean("contactDao");
    keywordDao = (KeywordDao) applicationContext.getBean("keywordDao");
    keywordActionDao = (KeywordActionDao) applicationContext.getBean("keywordActionDao");
    messageDao = (MessageDao) applicationContext.getBean("messageDao");
    emailDao = (EmailDao) applicationContext.getBean("emailDao");
    emailAccountDao = (EmailAccountDao) applicationContext.getBean("emailAccountDao");
    smsInternetServiceSettingsDao = (SmsInternetServiceSettingsDao) applicationContext
            .getBean("smsInternetServiceSettingsDao");
    smsModemSettingsDao = (SmsModemSettingsDao) applicationContext.getBean("smsModemSettingsDao");
    eventBus = (EventBus) applicationContext.getBean("eventBus");
}

From source file:org.apache.oodt.cas.catalog.cli.action.LoadCatalogRepositoryCliAction.java

@Override
public void execute(ActionMessagePrinter printer) throws CmdLineActionException {
    try {/*from  w ww.jav a 2  s  .co  m*/
        Validate.notNull(catalogRepositoryId, "Must specify catalogRepositoryId");
        Validate.notNull(beanRepo, "Must specify beanRepo");

        FileSystemXmlApplicationContext appContext = new FileSystemXmlApplicationContext(
                new String[] { this.beanRepo }, false);
        appContext.setClassLoader(new Serializer().getClassLoader());
        appContext.refresh();
        CatalogRepositoryFactory factory = (CatalogRepositoryFactory) appContext
                .getBean(this.catalogRepositoryId, CatalogRepositoryFactory.class);
        CatalogRepository catalogRepository = factory.createRepository();
        Set<Catalog> catalogs = catalogRepository.deserializeAllCatalogs();
        printer.println("Deserialized Catalogs: " + catalogs.toString());
        for (Catalog catalog : catalogs) {
            printer.println("Adding Catalog: " + catalog);
            getClient().addCatalog(catalog);
        }
    } catch (Exception e) {
        throw new CmdLineActionException("Failed to load catalogs from bean repo : " + e.getMessage(), e);
    }
}

From source file:org.apache.oodt.cas.catalog.cli.action.LoadCatalogsCliAction.java

@Override
public void execute(ActionMessagePrinter printer) throws CmdLineActionException {
    try {//  w w w. ja  v  a 2 s  . co m
        Validate.notNull(beanRepo, "Must specify beanRepo");

        FileSystemXmlApplicationContext repoAppContext = new FileSystemXmlApplicationContext(
                new String[] { this.beanRepo }, false);
        repoAppContext.setClassLoader(new Serializer().getClassLoader());
        repoAppContext.refresh();
        @SuppressWarnings("unchecked")
        Map<String, Catalog> catalogs = repoAppContext.getBeansOfType(Catalog.class);
        for (Catalog catalog : catalogs.values()) {
            printer.println("Adding catalog: " + catalog.getId());
            getClient().addCatalog(catalog);
        }
    } catch (Exception e) {
        throw new CmdLineActionException("Failed to load catalogs : " + e.getMessage(), e);
    }
}