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

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

Introduction

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

Prototype

@Override
    public void refresh() throws BeansException, IllegalStateException 

Source Link

Usage

From source file:net.itransformers.idiscover.v2.core.Main.java

public static void main(String[] args) throws MalformedURLException {
    logger.debug("iDiscover v2. gearing up");
    Map<String, String> params = CmdLineParser.parseCmdLine(args);
    //        String connectionDetailsFileName = params.get("-f");
    //        if (connectionDetailsFileName == null) {
    //            printUsage("fileName"); return;
    //        }/*from   ww w . j  a v a 2  s.  c o m*/
    String depthCmdArg = params.get("-d");
    //        if (depthCmdArg == null) {
    //            printUsage("depth"); return;
    //        }
    String projectPath = params.get("-p");

    if (projectPath == null) {
        File cwd = new File(".");
        System.out.println("Project path is not specified. Will use current dir: " + cwd.getAbsolutePath());
        projectPath = cwd.getAbsolutePath();
    }

    File workingDir = new File(projectPath);
    if (!workingDir.exists()) {
        System.out.println("Invalid project path!");
        return;
    }
    System.out.println("Loading beans!!");

    File conDetails = new File(projectPath, "iDiscover/conf/txt/connection-details.txt");

    File generic = new File(projectPath, "iDiscover/conf/xml/generic.xml");
    String genericContextPath = generic.toURI().toURL().toString();

    File snmpDiscovery = new File(projectPath, "iDiscover/conf/xml/snmpNetworkDiscovery.xml");
    String snmpDiscoveryContextPath = snmpDiscovery.toURI().toURL().toString();

    File connectionsDetails = new File(projectPath, "iDiscover/conf/xml/connectionsDetails.xml");
    String connectionsDetailsContextPath = connectionsDetails.toURI().toURL().toString();

    DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
    BeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(String.class)
            .addConstructorArgValue(projectPath).getBeanDefinition();

    String labelDirName = autolabel(projectPath);

    BeanDefinition beanDefinition2 = BeanDefinitionBuilder.rootBeanDefinition(String.class)
            .addConstructorArgValue(labelDirName).getBeanDefinition();

    beanFactory.registerBeanDefinition("projectPath", beanDefinition);

    beanFactory.registerBeanDefinition("labelDirName", beanDefinition2);

    GenericApplicationContext cmdArgCxt = new GenericApplicationContext(beanFactory);
    // Must call refresh to initialize context
    cmdArgCxt.refresh();

    String[] paths = new String[] { genericContextPath, snmpDiscoveryContextPath,
            connectionsDetailsContextPath };
    //        ,project.getAbsolutePath()+project.getAbsolutePath()+File.separator+"iDiscover/conf/xml/snmpNetworkDiscovery.xml", project.getAbsolutePath()+File.separator+"iDiscover/src/main/resources/connectionsDetails.xml"
    FileSystemXmlApplicationContext applicationContext = new FileSystemXmlApplicationContext(paths, cmdArgCxt);
    //        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(workingDir+File.separator+"iDiscover/conf/xml/generic.xml",workingDir+File.separator+"/iDiscover/conf/xml/snmpNetworkDiscovery.xml","connectionsDetails.xml");
    // NetworkDiscoverer discoverer = fileApplicationContext.getBean("bgpPeeringMapDiscovery", NetworkDiscoverer.class);
    //NetworkDiscoverer discoverer = fileApplicationContext.getBean("floodLightNodeDiscoverer", NetworkDiscoverer.class);
    NetworkDiscoverer discoverer = applicationContext.getBean("snmpDiscovery", NetworkDiscoverer.class);
    LinkedHashMap<String, ConnectionDetails> connectionList = (LinkedHashMap) applicationContext
            .getBean("connectionList", conDetails);
    int depth = (Integer) applicationContext.getBean("discoveryDepth",
            depthCmdArg == null ? "-1" : depthCmdArg);
    NetworkDiscoveryResult result = discoverer
            .discoverNetwork(new ArrayList<ConnectionDetails>(connectionList.values()), depth);
    if (result != null) {
        for (String s : result.getNodes().keySet()) {
            System.out.println("\nNode: " + s);

        }
    }

    //
}

From source file:org.mzd.shap.spring.cli.ConfigSetup.java

public static void main(String[] args) {
    // check args
    if (args.length != 1) {
        exitOnError(1, null);/*w  w  w  .  j a  v a2  s . co  m*/
    }

    // check file existance
    File analyzerXML = new File(args[0]);
    if (!analyzerXML.exists()) {
        exitOnError(1, "'" + analyzerXML.getPath() + "' did not exist\n");
    }

    // prompt user whether existing data should be purged
    boolean isPurged = false;
    String ormContext = null;
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    try {
        System.out.println("\nDo you wish to purge the database before running setup?");
        System.out.println("WARNING: all existing data in SHAP will be lost!");
        System.out.println("Really purge? yes/[NO]");
        String ans = br.readLine();
        if (ans.toLowerCase().equals("yes")) {
            System.out.println("Purging enabled");
            ormContext = "orm-purge-context.xml";
            isPurged = true;
        } else {
            System.out.println("Purging disabled");
            ormContext = "orm-context.xml";
        }
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }

    // run tool
    try {
        // Using a generic application context since we're referencing
        // both classpath and filesystem resources.
        GenericApplicationContext ctx = new GenericApplicationContext();
        XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);
        xmlReader.loadBeanDefinitions(new ClassPathResource("datasource-context.xml"),
                new ClassPathResource(ormContext), new FileSystemResource(analyzerXML));
        ctx.refresh();

        /*
         * Create an base admin user.
         */
        if (isPurged) {
            //only attempted if we've wiped the old database.
            RoleDao roleDao = (RoleDao) ctx.getBean("roleDao");
            Role adminRole = roleDao.saveOrUpdate(new Role("admin", "ROLE_ADMIN"));
            Role userRole = roleDao.saveOrUpdate(new Role("user", "ROLE_USER"));
            UserDao userDao = (UserDao) ctx.getBean("userDao");
            userDao.saveOrUpdate(new User("admin", "admin", "shap01", adminRole, userRole));
        }

        /*
         * Create some predefined analyzers. Users should have modified
         * the configuration file to suit their environment.
         */
        AnnotatorDao annotatorDao = (AnnotatorDao) ctx.getBean("annotatorDao");
        DetectorDao detectorDao = (DetectorDao) ctx.getBean("detectorDao");

        ConfigSetup config = (ConfigSetup) ctx.getBean("configuration");

        for (Annotator an : config.getAnnotators()) {
            System.out.println("Adding annotator: " + an.getName());
            annotatorDao.saveOrUpdate(an);
        }

        for (Detector dt : config.getDetectors()) {
            System.out.println("Adding detector: " + dt.getName());
            detectorDao.saveOrUpdate(dt);
        }

        System.exit(0);
    } catch (Throwable t) {
        System.err.println(t.getMessage());
        System.exit(1);
    }
}

From source file:org.anarres.dblx.core.Main.java

public static void main(String[] args) throws Exception {
    Stopwatch stopwatch = Stopwatch.createStarted();
    Arguments arguments = new Arguments(args);
    GenericApplicationContext context = new GenericApplicationContext();
    AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(context);
    reader.register(AppConfiguration.class);
    for (AppConfiguration.Provider configurationProvider : ServiceLoader
            .load(AppConfiguration.Provider.class)) {
        for (Class<?> configurationClass : configurationProvider.getConfigurationClasses()) {
            LOG.debug("Registering additional ServerConfiguration class " + configurationClass.getName());
            reader.register(configurationClass);
        }//from  www. ja  va 2s  .c  o m
    }
    SpringUtils.addConfigurations(context, arguments);
    context.refresh();
    context.registerShutdownHook();
    context.start();

    LOG.info("Ready; startup took " + stopwatch);
}

From source file:com.jaspersoft.jasperserver.export.RemoveDuplicatedDisplayName.java

public static void main(String[] args) {

    Parameters params = null;/*from  w ww  .j  ava2 s  .co m*/
    boolean success = false;
    try {

        GenericApplicationContext ctx = new GenericApplicationContext();
        XmlBeanDefinitionReader configReader = new XmlBeanDefinitionReader(ctx);
        List resourceXML = getPaths(args[2]);
        if (args != null && args.length > 0) {
            for (int i = 0; i < resourceXML.size(); i++) {
                org.springframework.core.io.Resource resource = classPathResourceFactory
                        .create((String) resourceXML.get(i));
                configReader.loadBeanDefinitions(resource);
            }
        }
        ctx.refresh();
        if (args.length > 3) {
            if ("UPDATE".equals(args[3])) {
                updateRepo = true;
            }
        }

        // write to file
        //

        try {
            CommandBean commandBean = (CommandBean) ctx.getBean("removeDuplicateDisplayName",
                    CommandBean.class);
            Charset encoding = Charset.forName(
                    ((RemoveDuplicatedDisplayName) commandBean).getEncodingProvider().getCharacterEncoding());
            osw = new OutputStreamWriter(new FileOutputStream("remove_duplicated_display_name_report.txt"),
                    encoding);
            commandBean.process(params);

        } finally {
            osw.close();
        }
        success = true;
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
    System.exit(success ? 0 : -1);
}

From source file:de.visualdependencies.context.ContextUtil.java

/**
 * Creates and return a new Spring context object.
 * //from   w  ww .  j  a  v a  2s .  c  o m
 * This creates a complete new context including data abstraction layer and plugin management. All plugins defined
 * in the application's package will recognized.
 * 
 * @return applicationContext
 */
public static GenericApplicationContext initialize() {

    // Creating the context for database configuration.
    final GenericXmlApplicationContext contextDatabase = new GenericXmlApplicationContext(
            "classpath:context-database.xml");
    final GenericApplicationContext context = new GenericApplicationContext(contextDatabase);
    context.refresh();

    return context;
}

From source file:org.apache.empire.samples.spring.SampleSpringApp.java

static GenericApplicationContext getContext() {
    log.info("Creating Spring Application Context ...");
    GenericApplicationContext ctx = new GenericApplicationContext();
    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(ctx);
    reader.loadBeanDefinitions(new ClassPathResource("/applicationContext.xml"));

    ctx.refresh();
    return ctx;//from   w ww.ja  va2 s . c  o  m
}

From source file:com.wavemaker.commons.util.SpringUtils.java

public static Object getBean(Resource resource, String beanName) {
    GenericApplicationContext ctx = initSpringConfig(false);
    XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);
    xmlReader.loadBeanDefinitions(resource);
    ctx.refresh();
    return ctx.getBean(beanName);
}

From source file:com.wavemaker.commons.util.SpringUtils.java

private static GenericApplicationContext initSpringConfig(boolean refresh) {
    GenericApplicationContext ctx = new GenericApplicationContext();
    XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);
    xmlReader.loadBeanDefinitions(new ClassPathResource("config.xml"));

    if (refresh) {
        ctx.refresh();
    }//from  w w w. j  av a2 s . co  m

    return ctx;
}

From source file:com.setronica.ucs.server.MessageServer.java

private static ClassPathXmlApplicationContext initApplication(String profile,
        DefaultListableBeanFactory parentBeanFactory) {
    ClassPathXmlApplicationContext applicationContext;

    if (parentBeanFactory != null) {
        //wrap BeanFactory inside ApplicationContext
        GenericApplicationContext parentContext = new GenericApplicationContext(parentBeanFactory);
        parentContext.refresh();
        applicationContext = new ClassPathXmlApplicationContext(parentContext);
    } else {/* www  .j a  va2s  .  com*/
        applicationContext = new ClassPathXmlApplicationContext();
    }
    ConfigurableEnvironment environment = applicationContext.getEnvironment();
    environment.setDefaultProfiles(profile);
    applicationContext.setConfigLocation("spring-application.xml");

    // log active profile

    String[] profiles = environment.getActiveProfiles();
    if (profiles.length == 0) {
        profiles = environment.getDefaultProfiles();
    }
    for (String activeProfile : profiles) {
        if (environment.acceptsProfiles(activeProfile)) {
            logger.info("Profile " + activeProfile + " is active");
        }
    }

    applicationContext.refresh();
    return applicationContext;
}

From source file:org.apache.ignite.yardstick.IgniteNode.java

/**
 * @param springCfgPath Spring configuration file path.
 * @return Grid configuration./*  ww w  .  jav  a  2 s. c o m*/
 * @throws Exception If failed.
 */
protected static IgniteConfiguration loadConfiguration(String springCfgPath) throws Exception {
    URL url;

    try {
        url = new URL(springCfgPath);
    } catch (MalformedURLException e) {
        url = IgniteUtils.resolveIgniteUrl(springCfgPath);

        if (url == null)
            throw new IgniteCheckedException("Spring XML configuration path is invalid: " + springCfgPath
                    + ". Note that this path should be either absolute or a relative local file system path, "
                    + "relative to META-INF in classpath or valid URL to IGNITE_HOME.", e);
    }

    GenericApplicationContext springCtx;

    try {
        springCtx = new GenericApplicationContext();

        new XmlBeanDefinitionReader(springCtx).loadBeanDefinitions(new UrlResource(url));

        springCtx.refresh();
    } catch (BeansException e) {
        throw new Exception("Failed to instantiate Spring XML application context [springUrl=" + url + ", err="
                + e.getMessage() + ']', e);
    }

    Map<String, IgniteConfiguration> cfgMap;

    try {
        cfgMap = springCtx.getBeansOfType(IgniteConfiguration.class);
    } catch (BeansException e) {
        throw new Exception("Failed to instantiate bean [type=" + IgniteConfiguration.class + ", err="
                + e.getMessage() + ']', e);
    }

    if (cfgMap == null || cfgMap.isEmpty())
        throw new Exception("Failed to find ignite configuration in: " + url);

    return cfgMap.values().iterator().next();
}