Example usage for org.springframework.context ApplicationContext getBean

List of usage examples for org.springframework.context ApplicationContext getBean

Introduction

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

Prototype

Object getBean(String name) throws BeansException;

Source Link

Document

Return an instance, which may be shared or independent, of the specified bean.

Usage

From source file:net.sourceforge.happybank.facade.BankTest.java

/**
 * Test method.//from  w  ww.  ja v a2  s.  c o m
 * 
 * @param args command line arguments
 */
public static void main(final String[] args) {

    try {
        // get context and facade
        ApplicationContext ctx = new FileSystemXmlApplicationContext("build/applicationContext.xml");
        BankingFacade bank = (BankingFacade) ctx.getBean("bankManager");

        // get all customers
        List<Customer> customers = bank.getCustomers();
        Iterator<Customer> custIter = customers.iterator();
        Customer cust = null;
        while (custIter.hasNext()) {
            cust = custIter.next();
            String cid = cust.getId();
            Customer customer = bank.getCustomer(cid);
            System.out.println(customer.toString());

            // get customers accounts
            List<Account> accounts = bank.getAccounts(cid);
            Iterator<Account> accIter = accounts.iterator();
            Account acc = null;
            while (accIter.hasNext()) {
                acc = accIter.next();
                String aid = acc.getId();
                Account account = bank.getAccount(aid);
                System.out.println("\t> " + account.toString());

                // get account transactions
                List<TransRecord> transactions = bank.getTransactions(aid);
                Iterator<TransRecord> transIter = transactions.iterator();
                TransRecord tr = null;
                while (transIter.hasNext()) {
                    tr = transIter.next();
                    System.out.println("\t\t>" + tr.toString());
                }
            }
        }

        // test creation, deletion and withdrawal
        bank.addCustomer("999", "Mr", "First", "Last");
        bank.addAccount("999-99", "999", "Checking");
        bank.deposit("999-99", new BigDecimal(1000.0));
        bank.withdraw("999-99", new BigDecimal(500.0));
        bank.deleteAccount("999-99");
        bank.deleteCustomer("999");

    } catch (BankException ex) {
        ex.printStackTrace();
    }
}

From source file:org.ala.util.BieAccessLogReader.java

public static void main(String[] args) {
    if (args.length != 2) {
        System.err.println("usage: java BieAccessLogReader" + " fileLocation" + " url");
        System.exit(0);// ww  w  .  j  a  va 2 s .c o m
    }
    try {
        ApplicationContext context = SpringUtils.getContext();
        BieAccessLogReader bieAccessLogReader = context.getBean(BieAccessLogReader.class);
        bieAccessLogReader.processFile(args[0], args[1]);
        System.exit(1);
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(0);
    }
}

From source file:com.pymmasoftware.demo.loyalty.client.StandaloneLoyaltyClient.java

public static void main(String[] args) throws InterruptedException, ParseException {
    ApplicationContext context = new ClassPathXmlApplicationContext("META-INF/spring/application-context.xml");

    StandaloneLoyaltyClient loyaltyClient = context.getBean(StandaloneLoyaltyClient.class);
    Ticket ticket = new Ticket();
    ticket.setAmount(1000.0f);/*from  w  w w .ja v  a2s.  co  m*/
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    ticket.setDateTicket(sdf.parse("01/01/2012"));
    ticket.setId("1");

    Card loyaltyCard = new Card();
    loyaltyCard.setCartType("Gold");
    loyaltyCard.setName("VISA");
    loyaltyCard.setName("4859569558");
    Customer customer = new Customer();
    customer.setCustomerID("12");
    customer.setBirthDate(sdf.parse("23/08/1968"));
    customer.setName("Heron");
    customer.setSurName("Nicolas");
    customer.setGender(Gender.Mr);
    loyaltyCard.setCustomer(customer);
    ticket.setLoyaltyCard(loyaltyCard);
    Provider provider = new Provider();
    provider.setName("Pymma Software");
    provider.setCountry("fr");
    Price price = new Price();
    price.setCurrency(Currency.Euro);
    price.setPrice(new Float("100.0"));
    Product product = new Product();
    product.setPrice(price);
    product.setProvider(provider);
    product.setId("100-100");
    product.setName("Pampers");
    ticket.AddLine(product, new Float("100.0"), 10);

    while (true) {
        ticket = loyaltyClient.fireAllRules(ticket);
        logger.info("Ticket processed : {}", ticket);
        sleep(30000);
    }

}

From source file:com.berrysys.ussdgw.Starter.java

/**
 * The main method.//from  w ww .j  av a  2 s.  c o m
 *
 * @param args the arguments
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static void main(String[] args) throws IOException {
    StringBuilder banner = new StringBuilder();
    banner.append("\n").append("  ____                       ____            \n")
            .append(" | __ )  ___ _ __ _ __ _   _/ ___| _   _ ___ \n")
            .append(" |  _ \\ / _ \\ '__| '__| | | \\___ \\| | | / __|\n")
            .append(" | |_) |  __/ |  | |  | |_| |___) | |_| \\__ \\\n")
            .append(" |____/ \\___|_| _|_|   \\__, |____/ \\__, |___/\n")
            .append(" / ___|(_) __ _| |_ _ _|___/_ _ __ |___/     \n")
            .append(" \\___ \\| |/ _` | __| '__/ _` | '_ \\          \n")
            .append("  ___) | | (_| | |_| | | (_| | | | |         \n")
            .append(" |____/|_|\\__, |\\__|_|  \\__,_|_| |_|         \n")
            .append("  _   _ __|___/__  ____                      \n")
            .append(" | | | / ___/ ___||  _ \\                     \n")
            .append(" | | | \\___ \\___ \\| | | |                    \n")
            .append(" | |_| |___) |__) | |_| |                    \n")
            .append("  \\___/|____/____/|____/                     \n")
            .append("  / ___| __ _| |_ _____      ____ _ _   _    \n")
            .append(" | |  _ / _` | __/ _ \\ \\ /\\ / / _` | | | |   \n")
            .append(" | |_| | (_| | ||  __/\\ V  V / (_| | |_| |   \n")
            .append("  \\____|\\__,_|\\__\\___| \\_/\\_/ \\__,_|\\__, |\n")
            .append("                                    |___/    \n");
    String berrysysUssdGW = banner.toString();

    log.info(berrysysUssdGW);
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/app-context.xml");

    List<DialogListener> serverList = (List<DialogListener>) applicationContext.getBean("sctpServerList");

    Iterator<DialogListener> i = serverList.iterator();
    while (i.hasNext()) {
        final DialogListener dialogListenerItem = i.next();
        DialogListenerThread dialogListenerThread = new DialogListenerThread();
        dialogListenerThread.setDialogListener(dialogListenerItem);
        dialogListenerThread.start();
        ThreadHolder.getInstance().getDialogListenerThreadList().add(dialogListenerThread);
    }

    Iterator<DialogListenerThread> j = ThreadHolder.getInstance().getDialogListenerThreadList().iterator();
    while (j.hasNext()) {
        try {
            j.next().join();
        } catch (InterruptedException e) {
            log.catching(e);
        }

    }
}

From source file:ar.com.springbasic.app.MainApp.java

public static void main(String[] args) {

    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("newSpringXMLConfig.xml");

    AdminDao adminDao = (AdminDao) applicationContext.getBean("adminDao");

    Timestamp ts = new Timestamp(new Date().getTime());

    //        ***Creo un nuevo admin***
    //          Admin admin = new Admin();
    //        admin.setCargo("Gerente");
    //        admin.setNombre("carlo");
    //        admin.setFechaCreacion(ts);

    try {/*from  w  w  w .ja va2  s  .  c  om*/
        //            ***Guardo el admin***
        //            adminDao.save(admin);

        //               ***traigo todos los campos ***
        //            List<Admin> admins = adminDao.findAll();
        //            for (Object admin1 : admins) {
        //                System.out.println(admin1);    
        //            }

        //            ***Busco por un id***
        //            System.out.println(adminDao.findById(2));

        //            Busco por un nombre
        //            System.out.println(adminDao.findByNombre("pepe").toString());

        //            Modificar y borrar
        //            Admin admin = adminDao.findById(1);
        //            System.out.println("Admin con id 1= " + admin);
        //            
        //            admin.setCargo("Subgerente");
        //            admin.setNombre("Adrian");
        //            
        //            if (adminDao.update(admin)) {
        //                System.out.println("Actializacion correcta " +admin);
        //            }
        //            if (adminDao.delete(admin.getIdAd())) {
        //                System.out.println("Admin: "+admin.getNombre() +" eliminado correctamente");
        //                
        //            }

        List<Admin> admins = new ArrayList<>();
        admins.add(new Admin("Papulo", "Jefe de ingenieria", ts));
        admins.add(new Admin("Cucuro", "Chorro", ts));
        admins.add(new Admin("Zafalo", "Mujeriego", ts));
        admins.add(new Admin("Mengano", "Chupa culo", ts));

        int[] vals = adminDao.saveAll(admins);

        for (int val : vals) {
            System.out.println("Filas afectadas para esta operacion= " + val);
        }

    } catch (CannotGetJdbcConnectionException e) {
        //Error de conneccion
        System.out.println(e);
    } catch (DataAccessException b) {
        //Error de acceso a datos
        System.out.println(b);

    }

}

From source file:nl.minbzk.dwr.zoeken.enricher.Enricher.java

/**
 * Application entry-point.//from w  w  w .  j av  a  2s. c om
 * 
 * @param args
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    try {
        ApplicationContext context = new ClassPathXmlApplicationContext(APPLICATION_CONTEXT);

        // Create a new enricher service

        EnricherService service = (EnricherService) context.getBean("enricherService");

        // Retrieve the fetcher settings

        EnricherSettings settings = (EnricherSettings) context.getBean("settings");

        if (!settings.processArguments(args))
            System.exit(-1);

        // We assume the input encoding is the same as the output encoding

        InputStreamReader reader = new InputStreamReader(new FileInputStream(settings.getInputFile()),
                settings.getEncoding());

        // Now process the given file

        service.processImport(reader, settings.getJobOverride(), settings.getEncoding());
    } catch (Exception e) {
        logger.error("The given import envelopes could not be processed", e);

        System.exit(1);
    }
}

From source file:org.freewheelschedule.freewheel.common.util.DatabasePopulator.java

@Transactional
public static void main(String[] args) {
    ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-CommonUtil.xml");
    JobDao jobDao = (JobDao) ctx.getBean("jobDao");
    MachineDao machineDao = (MachineDao) ctx.getBean("machineDao");
    TriggerDao triggerDao = (TriggerDao) ctx.getBean("triggerDao");

    Machine machine = new Machine();
    machine.setName("localhost");
    machine.setPort(12145L);//  w w w  .j  a va 2  s.  com
    machineDao.create(machine);

    RepeatingTrigger trigger = new RepeatingTrigger();
    trigger.setTriggerInterval(50000L);
    triggerDao.create(trigger);

    CommandJob job = new CommandJob();
    List<Trigger> triggers = new ArrayList<Trigger>();
    triggers.add(trigger);

    job.setName("Test Job");
    job.setCommand("java -version");
    job.setStderr("stderr.log");
    job.setStdout("stdout.log");
    job.setAppendStderr(true);
    job.setExecutingServer(machine);
    job.setTriggers(triggers);

    jobDao.create(job);

    trigger.setJob(job);
    triggerDao.create(trigger);

    TimedTrigger timedTrigger = new TimedTrigger();
    LocalTime triggerTime = new LocalTime();
    timedTrigger.setTriggerTime(triggerTime.plusMinutes(5));
    timedTrigger.setDaysOfWeek(127);
    triggerDao.create(timedTrigger);

    List<Trigger> timedTriggers = new ArrayList<Trigger>();
    timedTriggers.add(timedTrigger);

    CommandJob job2 = new CommandJob();

    job2.setName("Test Job2");
    job2.setCommand("java -version");
    job2.setStderr("stderr.log");
    job2.setStdout("stdout.log");
    job2.setAppendStderr(true);
    job2.setExecutingServer(machine);
    job2.setTriggers(timedTriggers);
    jobDao.create(job2);

    timedTrigger.setJob(job2);
    triggerDao.create(timedTrigger);

    Job readJob = jobDao.readByName("Test Job");
    log.info("Record read: " + readJob);

    //        readJob = jobDao.readById(9999L);
    //        log.info("Record read: " + readJob);
    //
    List<Job> jobs = jobDao.read();
    for (Job job1 : jobs) {
        log.info("All jobs read: " + job1);
    }
}

From source file:x595.Main.java

public static void main(String... args) {
    @SuppressWarnings("resource")
    ApplicationContext ctx = new AnnotationConfigApplicationContext(JpaConfig.class);

    CarRepository repo = ctx.getBean(CarRepository.class);

    log("Start testing CarRepository");

    LicenceInfo info1 = new LicenceInfo("Jane Doe", "jane@corp.com", new Date(), "N17D3E");
    LicenceInfo info2 = new LicenceInfo("Josh Maxwell", "josh@googol.com", new Date(), "G99331");
    LicenceInfo info3 = new LicenceInfo("JD", "saxe@me.com", new Date(), "HL9010");
    LicenceInfo info4 = new LicenceInfo("Triple corp", "triple@doodle.org", new Date(), "JDC13X");
    LicenceInfo info5 = new LicenceInfo("JD", "pro4@k5.com", new Date(), "A75Dc1");

    Car c1 = new Car("AMG", "A4", 2012, 110, info1);
    Car c2 = new Car("Genesis", "G20", 2008, 170, info2);
    Car c3 = new Car("Lena", "sigma", 2015, 150, info3);
    Car c4 = new Car("AMG", "A7", 2010, 130, info4);
    Car c5 = new Car("Tesla", "T1", 2011, 90, info5);

    log("Part 0. insert cars");
    repo.save(c1);//from ww  w  .  java  2  s  .c o m
    repo.save(c2);
    repo.save(c3);
    repo.save(c4);
    repo.save(c5);

    Iterator<Car> it = repo.findAll().iterator();
    log("Part 0. result of inserted car: ");
    while (it.hasNext()) {
        log(it.next().toString());
    }

    log("Part 1. findByOrderByMakerAsc");
    it = repo.findByOrderByMakerAsc().iterator();
    log("Result: ");
    while (it.hasNext()) {
        log(it.next().toString());
    }

    log("Part 2. findByLicenseInfoOwnerName");
    it = repo.findByLicenseInfoOwnerName("JD").iterator();
    log("Result: ");
    while (it.hasNext()) {
        log(it.next().toString());
    }

    log("Part 3. findByMaker");
    it = repo.findByMaker("AMG").iterator();
    log("Result: ");
    while (it.hasNext()) {
        log(it.next().toString());
    }

    log("Part 4. findByMakeYearBetween");
    it = repo.findByMakeYearBetween(2010, 2013).iterator();
    log("Result: ");
    while (it.hasNext()) {
        log(it.next().toString());
    }

    log("Part 5. findByLicenseInfoLicensePlateNumber");
    Car c = repo.findByLicenseInfoLicensePlateNumber("HL9010");
    log("Result: ");
    log(c.toString());

}

From source file:org.ala.hbase.IdentifyLifeLoader.java

/**
 * /*from  w  w w  .  j  ava  2  s.  c o m*/
 * Usage: [idLifeURI][idLifeRsURI]
 * eg: http://www.identifylife.org/ http://www.identifylife.org:8001/
 * 
 */
public static void main(String[] args) {
    System.out.println("Starting IdentifyLifeLoader process.....");
    ApplicationContext context = SpringUtils.getContext();
    IdentifyLifeLoader l = context.getBean(IdentifyLifeLoader.class);
    try {
        if (args.length == 1) {
            l.setIdLifeURI(args[0]);
        } else if (args.length == 2) {
            l.setIdLifeURI(args[0]);
            l.setIdLifeRsURI(args[1]);
        }
        System.out.println("Starting load process.....");
        l.load();
        System.out.println("load process finished.....");
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
    System.exit(0);
}

From source file:org.lieuofs.extraction.commune.historisation.ExtractionNumHistorisationCommune.java

/**
 * @param args/* w  w  w.  jav a2  s. c o m*/
 */
public static void main(String[] args) throws IOException {
    ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "beans_lieuofs.xml" });
    CommuneCritere critere = new CommuneCritere();
    IGestionCommune gestionnaire = (IGestionCommune) context.getBean("gestionCommune");
    List<ICommuneSuisse> communes = gestionnaire.rechercher(critere);
    Collections.sort(communes, new Comparator<ICommuneSuisse>() {
        public int compare(ICommuneSuisse com1, ICommuneSuisse com2) {
            return com1.getNumeroOFS() - com2.getNumeroOFS();
        }
    });

    BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream("NumeroHistorisationCommune.sql"), "Windows-1252"));
    NumeroHistorisationCommuneWriter commWriter = new NumeroHistorisationRefonteSQLWriter();
    for (ICommuneSuisse commune : communes) {
        String numHistStr = commWriter.ecrireNumero(commune);
        if (null != numHistStr) {
            writer.append(numHistStr);
        }
    }
    writer.close();

}