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

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

Introduction

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

Prototype

@Override
    public Object getBean(String name) throws BeansException 

Source Link

Usage

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   www  . j  ava2s.com
    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:cn.vlabs.umt.ui.UMTStartupListener.java

public void contextInitialized(ServletContextEvent event) {
    ServletContext context = event.getServletContext();
    PropertyConfigurator.configure(context.getRealPath("/WEB-INF/conf/log4j.properties"));
    String contextxml = context.getInitParameter("contextConfigLocation");
    if (contextxml == null) {
        contextxml = "/WEB-INF/conf/UMTContext.xml";
    }//  w  w w. jav a  2 s  .  c o  m
    //FIX the bug in linux
    String realpath = context.getRealPath(contextxml);
    if (realpath != null && realpath.startsWith("/")) {
        realpath = "/" + realpath;
    }
    FileSystemXmlApplicationContext factory = new FileSystemXmlApplicationContext(realpath);
    PathMapper mapper = (PathMapper) factory.getBean("PathMapper");
    mapper.setContext(context);

    CreateTable createTable = (CreateTable) factory.getBean("CreateTable");
    if (!createTable.isTableExist()) {
        createTable.createTable();
    }
    factory.getBean("UMTCredUtil");
    context.setAttribute(Attributes.APPLICATION_CONTEXT_KEY, factory);
    UMTContext.setFactory(factory);

}

From source file:org.apache.ftpserver.config.spring.PropertyPlaceholderTest.java

public void test() throws Throwable {
    System.setProperty("port2", "3333");

    FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext(
            "src/test/resources/spring-config/config-property-placeholder.xml");

    DefaultFtpServer server = (DefaultFtpServer) ctx.getBean("server");

    assertEquals(2222, server.getListener("listener0").getPort());
    assertEquals(3333, server.getListener("listener1").getPort());
}

From source file:org.apache.smscserver.test.spring.PropertyPlaceholderTest.java

public void test() throws Throwable {
    System.setProperty("port2", "3333");

    FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext(
            "src/test/resources/spring-config/config-property-placeholder.xml");

    DefaultSmscServer server = (DefaultSmscServer) ctx.getBean("server");

    Assert.assertEquals(2222, server.getServerContext().getListener("listener0").getPort());
    Assert.assertEquals(3333, server.getServerContext().getListener("listener1").getPort());
}

From source file:org.apache.smscserver.main.CommandLine.java

/**
 * Get the configuration object./*from  w w w  .j  a va2s.  c o  m*/
 */
protected SmscServer getConfiguration(String[] args) throws Exception {

    SmscServer server = null;
    if (args.length == 0) {
        System.out.println("Using default configuration");
        server = new SmscServerFactory().createServer();
    } else if ((args.length == 1) && args[0].equals("-default")) {
        // supported for backwards compatibility, but not documented
        System.out.println("The -default switch is deprecated, please use --default instead");
        System.out.println("Using default configuration");
        server = new SmscServerFactory().createServer();
    } else if ((args.length == 1) && args[0].equals("--default")) {
        System.out.println("Using default configuration");
        server = new SmscServerFactory().createServer();
    } else if ((args.length == 1) && args[0].equals("--help")) {
        this.usage();
    } else if ((args.length == 1) && args[0].equals("-?")) {
        this.usage();
    } else if (args.length == 1) {
        System.out.println("Using XML configuration file " + args[0] + "...");
        FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext(args[0]);

        if (ctx.containsBean("server")) {
            server = (SmscServer) ctx.getBean("server");
        } else {
            String[] beanNames = ctx.getBeanNamesForType(SmscServer.class);
            if (beanNames.length == 1) {
                server = (SmscServer) ctx.getBean(beanNames[0]);
            } else if (beanNames.length > 1) {
                System.err
                        .println("Using the first server defined in the configuration, named " + beanNames[0]);
                server = (SmscServer) ctx.getBean(beanNames[0]);
            } else {
                System.err.println("XML configuration does not contain a server configuration");
            }
        }
    } else {
        this.usage();
    }

    return server;
}

From source file:org.apache.ftpserver.main.CommandLine.java

/**
 * Get the configuration object.//from ww  w.  j  ava 2s  . c  o m
 */
protected FtpServer getConfiguration(String[] args) throws Exception {

    FtpServer server = null;
    if (args.length == 0) {
        System.out.println("Using default configuration");
        server = new FtpServerFactory().createServer();
    } else if ((args.length == 1) && args[0].equals("-default")) {
        // supported for backwards compatibility, but not documented
        System.out.println("The -default switch is deprecated, please use --default instead");
        System.out.println("Using default configuration");
        server = new FtpServerFactory().createServer();
    } else if ((args.length == 1) && args[0].equals("--default")) {
        System.out.println("Using default configuration");
        server = new FtpServerFactory().createServer();
    } else if ((args.length == 1) && args[0].equals("--help")) {
        usage();
    } else if ((args.length == 1) && args[0].equals("-?")) {
        usage();
    } else if (args.length == 1) {
        System.out.println("Using XML configuration file " + args[0] + "...");
        FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext(args[0]);

        if (ctx.containsBean("server")) {
            server = (FtpServer) ctx.getBean("server");
        } else {
            String[] beanNames = ctx.getBeanNamesForType(FtpServer.class);
            if (beanNames.length == 1) {
                server = (FtpServer) ctx.getBean(beanNames[0]);
            } else if (beanNames.length > 1) {
                System.out
                        .println("Using the first server defined in the configuration, named " + beanNames[0]);
                server = (FtpServer) ctx.getBean(beanNames[0]);
            } else {
                System.err.println("XML configuration does not contain a server configuration");
            }
        }
    } else {
        usage();
    }

    return server;
}

From source file:org.activiti.crystalball.anttasks.RunSimulationTask.java

public void execute() {

    log("Starting simulation run [" + simRunBean + "] from application context [" + appContext + "].");

    // seting app context
    if (appContext == null) {
        throw new BuildException("No application context set.");
    }/*w w  w  . j  ava 2 s . co  m*/
    FileSystemXmlApplicationContext applicationContext = new FileSystemXmlApplicationContext(appContext);

    try {
        // getting simulation run
        SimulationRun simRun = null;
        if (simRunBean != null)
            simRun = (SimulationRun) applicationContext.getBean(simRunBean);
        if (simRun == null) {
            log("Using default simulation run bean", Project.MSG_WARN);
            simRun = applicationContext.getBean(SimulationRun.class);
        }
        if (simRun == null) {
            throw new BuildException("unable to get sim run bean");
        }

        //
        // execute simulation run
        //
        simRun.execute(getStartDate(), getEndDate());
    } catch (ParseException e) {
        log("Simulation task exception - parsing dates", Project.MSG_ERR);
        throw new BuildException(e);
    } catch (Exception e) {
        log("Simulation task exception - simulation run error", Project.MSG_ERR);
        throw new BuildException(e);
    } finally {
        applicationContext.close();
    }

    log("Simulation run [" + simRunBean + "] from application context [" + appContext + "] done.");

}

From source file:org.jaffre.springframework.JaffreExporterTestCase.java

public void test() throws Exception {
    final File l_fileAppContext;
    final FileSystemXmlApplicationContext l_appCtx;

    l_fileAppContext = PackageFile.get("test-resources/appcontext01.xml");
    assertTrue(l_fileAppContext.isFile());

    l_appCtx = new FileSystemXmlApplicationContext(l_fileAppContext.getPath());

    l_appCtx.start();//w  ww  .  j  a  v a2s  .  c  o  m

    assertEquals(6, l_appCtx.getBeanDefinitionCount());
    assertNotNull(l_appCtx.getBean("jaffreClient"));
    assertNotNull(l_appCtx.getBean("jaffreServer"));
    assertNotNull(l_appCtx.getBean("jaffreConnector"));
    assertNotNull(l_appCtx.getBean("jaffreExporter"));
    assertNotNull(l_appCtx.getBean("throwException"));
    assertNotNull(l_appCtx.getBean("greeting"));

    l_appCtx.stop();
    l_appCtx.close();
}

From source file:org.activiti.crystalball.anttasks.GenerateGraphTask.java

public void execute() {

    log("Starting generator [" + generatorBean + "] from application context [" + appContext + "].",
            Project.MSG_INFO);/*from w w w  .j  a v  a2  s. c o m*/

    // seting app context
    if (appContext == null) {
        throw new BuildException("No application context set.");
    }
    FileSystemXmlApplicationContext applicationContext = new FileSystemXmlApplicationContext(appContext);
    try {
        // getting generator
        AbstractProcessEngineGraphGenerator generator = null;
        if (generatorBean != null)
            generator = (AbstractProcessEngineGraphGenerator) applicationContext.getBean(generatorBean);
        if (generator == null) {
            applicationContext.close();
            throw new BuildException("unable to get generator bean");
        }

        // running report generate
        try {
            generator.generateReport(processDefinitionId, getStartDate(), getEndDate(), reportFileName);
        } catch (IOException e) {
            log("Generator exception", Project.MSG_ERR);
            throw new BuildException(e);
        } catch (ParseException e) {
            log("Generator exception - parsing dates", Project.MSG_ERR);
            throw new BuildException(e);
        }
    } finally {
        applicationContext.close();
    }

    log("Generator [" + generatorBean + "] execution from application context [" + appContext + "] done.",
            Project.MSG_INFO);
}

From source file:org.intalio.deploy.deployment.ws.DeployWS.java

protected void initialize() {
    try {/* w w w .j  ava2s.  co m*/
        synchronized (DeployWS.class) {
            if (_instance != null)
                return;
            LOG.debug("Initializing configuration.");
            String configDir = System.getProperty(CONFIG_DIR_PROPERTY);
            if (configDir == null) {
                throw new RuntimeException("System property " + CONFIG_DIR_PROPERTY + " not defined.");
            }
            _configDir = new File(configDir);
            if (!_configDir.exists()) {
                throw new RuntimeException(
                        "Configuration directory " + _configDir.getAbsolutePath() + " doesn't exist.");
            }
            ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
            Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
            try {
                Collection<String> configPaths = new HashSet<String>();

                File jmxConfigFile = new File(_configDir, "jmx.xml");
                if (jmxConfigFile.exists()) {
                    configPaths.add(String.valueOf(jmxConfigFile.toURI()));
                }
                File clusterConfigFile = new File(_configDir, "cluster-config.xml");
                if (clusterConfigFile.exists()) {
                    configPaths.add(String.valueOf(clusterConfigFile.toURI()));
                }

                configPaths.add(String.valueOf(new File(_configDir, "deploy-service.xml").toURI()));

                FileSystemXmlApplicationContext factory = new FileSystemXmlApplicationContext(
                        configPaths.toArray(new String[] {}));
                if (_deployService != null) {
                    _deployService.stop();
                }
                _deployService = (DeploymentServiceImpl) factory.getBean("deploymentService");

                if (LOG.isDebugEnabled())
                    LOG.debug("MBeanServer used: " + _deployService.getDeployMBeanServer());

                Cluster cluster = null;
                try {
                    cluster = (Cluster) factory.getBean("clusterConfig");
                } catch (NoSuchBeanDefinitionException nsbde) {
                    // not defined
                }

                if (cluster != null) {
                    if (LOG.isInfoEnabled())
                        LOG.info("Found clustering configuration at:" + configPaths + ".");

                    if (cluster.getListener() instanceof NullClusterListener) {
                        cluster.setListener(_deployService);
                    }

                    _deployService.setCluster(cluster);
                }

                _deployService.init();
                _deployService.start();
                _instance = this;
            } finally {
                Thread.currentThread().setContextClassLoader(oldClassLoader);
            }
        }
    } catch (RuntimeException except) {
        LOG.error("Error during initialization of deployment service", except);
        throw except;
    } catch (Exception e) {
        LOG.error("Error during initialization of deployment service", e);
        throw new RuntimeException(e);
    }
}