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

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

Introduction

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

Prototype

@Override
    public <T> T getBean(Class<T> requiredType) throws BeansException 

Source Link

Usage

From source file:rooms.Application.java

public static void main(String[] args) throws ValueException, ThingException, InterruptedException {

    AbstractApplicationContext context = new AnnotationConfigApplicationContext(RoomConfig.class);
    //AbstractApplicationContext context = new AnnotationConfigApplicationContext(RoomConfigMongo.class);

    //        MongoOperations mo = (MongoOperations) context.getBean("mongoTemplate");
    final ThingControl tc = (ThingControl) context.getBean("thingControl");

    for (String s : context.getBeanDefinitionNames()) {
        System.out.println(s);//from  www. j  a v  a2  s.  co  m
    }

    System.out.println("THINGSSSS");
    for (Thing t : tc.findAllThings()) {
        System.out.println("THING: " + t);
    }

    //        mo.dropCollection(Thing.class);
    //        mo.dropCollection(Bridge.class);
    //        mo.dropCollection(Light.class);

    List<Thing> t = tc.findThingsForType("bridge");

    Bridge b = new Bridge("10.0.0.40");
    Thing tb = tc.createThing("bridge", b);

    Light l = new Light(Group.GROUP_1, "white");
    Thing tl = tc.createThing("bedroom_ceiling", l);

    Light l2 = new Light(Group.GROUP_2, "white");
    Thing tl2 = tc.createThing("bedroom_bed", l2);

    Light l3 = new Light(Group.GROUP_3, "white");
    Thing tl3 = tc.createThing("bedroom_desk", l3);

    tc.addChildThing(tb, tl);
    tc.addChildThing(tb, tl2);
    tc.addChildThing(tb, tl3);

    List<Thing<Bridge>> bridges = tc.findThingsForType(Bridge.class);

    Map<String, LightWhiteV2> lights = Maps.newHashMap();

    for (Thing<Bridge> bridgeThing : bridges) {

        Bridge bridge = tc.getValue(bridgeThing);
        LimitlessLEDControllerV2 c = new LimitlessLEDControllerV2(b.getHost(), b.getPort());

        List<Thing<Light>> lightThings = tc.getChildrenForType(Observable.just(bridgeThing), Light.class, true);
        for (Thing<Light> tempLight : lightThings) {
            Light ll = tc.getValue(tempLight);
            LightWhiteV2 white = new LightWhiteV2(tempLight.getKey(), c, ll.getLightGroup());
            lights.put(white.getName(), white);
            System.out.println("LIGHT: " + white.getName());
        }
    }

    //        lights.get("bedroom_ceiling").setOn(true);
    lights.get("bedroom_bed").setOn(true);
    Thread.sleep(2000);
    //        lights.get("bedroom_ceiling").setOn(false);
    lights.get("bedroom_bed").setOn(false);
    Thread.sleep(2000);

}

From source file:com.javaetmoi.elasticsearch.musicbrainz.batch.IndexBatchMain.java

public static void main(String... args) {
    AbstractApplicationContext context = null;
    try {//from   w w w. j  av  a  2 s . co  m
        context = new ClassPathXmlApplicationContext(new String[] {
                "com/javaetmoi/elasticsearch/musicbrainz/batch/applicationContext-datasource.xml",
                "com/javaetmoi/elasticsearch/musicbrainz/batch/applicationContext-elasticsearch.xml",
                "com/javaetmoi/elasticsearch/musicbrainz/batch/applicationContext-batch.xml" });

        JobLauncher jobLauncher = context.getBean(JobLauncher.class);
        Job musicAlbumJob = context.getBean("musicAlbumJob", Job.class);
        jobLauncher.run(musicAlbumJob, new JobParameters());
    } catch (Throwable e) {
        String message = "Job Terminated in error: " + e.getMessage();
        LOG.error(message, e);
        systemExiter.exit(exitCodeMapper.intValue(ExitStatus.FAILED.getExitCode()));
    } finally {
        if (context != null) {
            context.close();
        }
    }
    systemExiter.exit(exitCodeMapper.intValue(ExitStatus.COMPLETED.getExitCode()));
}

From source file:com.osc.edu.chapter3.Starter.java

/**
 * <pre>/*  w  w w .  ja  v a 2s  . c  o m*/
 *  ?  samples/commons/db_configuration/build.xml ?? test-db-start, initializeData Task  .
 * </pre>
 * @param args
 */
public static void main(String[] args) {
    logger.debug("Initializing Spring context.");

    AbstractApplicationContext applicationContext = new ClassPathXmlApplicationContext(
            new String[] { "spring/application-context.xml" });

    logger.debug("Spring context initialized.");

    //CustomersService customersService = (CustomersService)applicationContext.getBean("customersService");
    //EmployeesService employeesService = (EmployeesService)applicationContext.getBean("employeesService");
    CustomersService customersService = applicationContext.getBean(CustomersService.class);
    EmployeesService employeesService = applicationContext.getBean(EmployeesService.class);

    customersService.setUseMapper(true);
    employeesService.setUseMapper(true);

    logger.debug("customers size with mapper : {}", customersService.getCustomersList().size());
    logger.debug("employees size with mapper : {}", employeesService.getEmployeesList().size());

    customersService.setUseMapper(false);
    employeesService.setUseMapper(false);

    logger.debug("customers size with sqlSession : {}", customersService.getCustomersList().size());
    logger.debug("employees size with sqlSession : {}", employeesService.getEmployeesList().size());

    applicationContext.close();
}

From source file:net.thackbarth.sparrow.Sparrow.java

/**
 * The main method of the tool.//from ww  w . j  a va 2 s  .co  m
 *
 * @param args command line parameter
 */
public static void main(String... args) {

    // Construct the spring application context
    progress.info("Building Spring Context");
    AbstractApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    context.registerShutdownHook();

    Options options = createOptions();
    PosixParser parser = new PosixParser();

    SparrowMode mode = SparrowMode.CRAWL;
    // analyze the arguments
    try {
        CommandLine commandLine = parser.parse(options, args);
        SparrowConfiguration configuration = (SparrowConfiguration) context.getBean("configuration");
        processConfiguration(configuration, commandLine);
        boolean processed = false;
        if (commandLine.hasOption('h')) {
            mode = SparrowMode.NOTHING;
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("Sparrow", options);
            processed = true;
        }
        if ((!processed) && (commandLine.hasOption('c'))) {
            mode = SparrowMode.CLEAN;
            // processed = true;
        }
    } catch (ParseException e) {
        progress.error("could not parse the arguments");
        mode = SparrowMode.NOTHING;
    }

    if (SparrowMode.CRAWL.equals(mode)) {
        // execute the crawl process
        SparrowCrawler crawler = (SparrowCrawler) context.getBean("crawler");
        crawler.startCrawling();
    }
    if (SparrowMode.CLEAN.equals(mode)) {
        // execute the cleaner process
        DatabaseCleaner cleaner = (DatabaseCleaner) context.getBean("cleaner");
        cleaner.clean();
    }
}

From source file:com.springdeveloper.hadoop.hive.HiveJdbcApp.java

public static void main(String[] args) throws Exception {
    AbstractApplicationContext context = new ClassPathXmlApplicationContext(
            "/META-INF/spring/hive-jdbc-context.xml", HiveJdbcApp.class);
    log.info("Hive JDBC Application Running");
    context.registerShutdownHook();/*from w w  w. java2 s .  c o m*/

    String tableDdl = "create external table if not exists tweetdata (value STRING) LOCATION '/tweets/input'";
    String query = "select r.retweetedUser, '\t', count(r.retweetedUser) as count " + " from tweetdata j "
            + " lateral view json_tuple(j.value, 'retweet', 'retweetedStatus') t as retweet, retweetedStatus "
            + " lateral view json_tuple(t.retweetedStatus, 'fromUser') r as retweetedUser "
            + " where t.retweet = 'true' " + " group by r.retweetedUser order by count desc limit 10";
    String results = "insert overwrite directory '/tweets/hiveout'";

    JdbcTemplate template = context.getBean(JdbcTemplate.class);
    template.execute(tableDdl);

    template.execute(results + " " + query);

    context.close();
}

From source file:com.bt.aloha.mockphones.Main.java

private static void printStartupScreen(AbstractApplicationContext applicationContext) {
    SimpleSipStack simpleSipStack = (SimpleSipStack) applicationContext.getBean("simpleSipStack");
    System.out.println("---------------------------------------------------------------------------");
    System.out.println("           Session Control Mock Phones                                     ");
    System.out.println("---------------------------------------------------------------------------");
    System.out.println("STARTED");
    System.out.println(" - IP Address:             " + simpleSipStack.getIpAddress());
    System.out.println(" - Port:                   " + simpleSipStack.getPort());
    System.out.println(" - Transport:              " + simpleSipStack.getTransport());
    CallCollection callCollection = (CallCollection) applicationContext.getBean("callCollection");
    System.out.println(" - CallCollection:         " + callCollection.getClass().getName());
    DialogCollection dialogCollection = (DialogCollection) applicationContext.getBean("dialogCollection");
    System.out.println(" - dialogCollection:       " + dialogCollection.getClass().getName());
    Object dialogCollectionBacker = applicationContext.getBean("dialogCollectionBacker");
    System.out.println(" - dialogCollectionBacker: " + dialogCollectionBacker.getClass().getName());
    System.out.println("---------------------------------------------------------------------------");
}

From source file:org.settings4j.helper.spring.ByteArrayXMLApplicationContext.java

/**
 * Static method to get a single Bean from a Spring Configuration XML.
 *
 * @param content The Spring configuration XML as byte[].
 * @param beanName The bean name/identifier.
 * @return The Bean-Object or <code>null</code>.
 *//*from   w  w w  . j a  va  2 s  .c o  m*/
public static Object getBean(final byte[] content, final String beanName) {

    final AbstractApplicationContext context = new ByteArrayXMLApplicationContext(content);
    context.refresh();

    final Object result = context.getBean(beanName);
    context.close();
    return result;
}

From source file:hub.Application.java

public static void main2(String[] args) throws ValueException, ThingException, InterruptedException {

    AbstractApplicationContext context = new AnnotationConfigApplicationContext(HubConfigJpa.class);

    MongoOperations mo = (MongoOperations) context.getBean("mongoTemplate");
    final ThingControl tc = (ThingControl) context.getBean("thingControl");

    //        for ( String s : context.getBeanDefinitionNames() ) {
    //            System.out.println(s);
    //        }/*  w w w. j av  a  2 s  .c o m*/

    //        Person p = new Person("markus", "binsteiner", "m.binsteiner@auckland.ac.nz");
    //        Thing<Person> tp = tc.createThing("markus", p);
    //
    //        Role r1 = new Role("role1");
    //        Thing<Role> tr1 = tc.createThing("group1", r1);
    //        Role r2 = new Role("role2");
    //        Thing<Role> tr2 = tc.createThing("group1", r2);

    //        Thing<Person> tp = tc.findUniqueThingMatchingTypeAndKey(Person.class, "markus", true).get();
    //
    //        List<Thing<Role>> tr = tc.findThingsForTypeAndKey(Role.class, "group1");
    //
    //        Thing<Role> tr1 = tr.get(0);
    //        Thing<Role> tr2 = tr.get(1);
    //
    //        tc.addChildThing(tp, tr1);
    //        tc.addChildThing(tp, tr2);
    //
    //
    //        List<Thing<Role>> t = tc.findThingsForType(Role.class);
    //
    //        t.stream().forEach(System.out::println);

}

From source file:de.uzk.hki.da.at.AcceptanceTest.java

private static void instantiateNode() {

    AbstractApplicationContext context = new FileSystemXmlApplicationContext("conf/beans.xml");
    localNode = (Node) context.getBean("localNode");

    Session session = HibernateUtil.openSession();
    session.beginTransaction();//from w ww  .ja  v  a2  s.  co  m
    session.refresh(localNode);
    session.close();

    context.close();
}

From source file:de.uzk.hki.da.at.AcceptanceTest.java

/**
 * @param gridImplBeanName bean name /* ww w  .j a  va  2 s.  c om*/
 * @param dcaImplBeanName distributed conversion adapter beanName
 * @return
 */

private static void instantiateGrid(Properties properties) {

    String gridImplBeanName = properties.getProperty("cb.implementation.grid");
    String dcaImplBeanName = properties.getProperty("cb.implementation.distributedConversion");

    if (gridImplBeanName == null)
        gridImplBeanName = "fakeGridFacade";
    if (dcaImplBeanName == null)
        dcaImplBeanName = "fakeDistributedConversionAdapter";

    AbstractApplicationContext context = new FileSystemXmlApplicationContext("conf/beans.xml");

    gridFacade = (GridFacade) context.getBean(gridImplBeanName);
    distributedConversionAdapter = (DistributedConversionAdapter) context.getBean(dcaImplBeanName);
    context.close();
}