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:org.openvpms.report.tools.TemplateLoader.java

/**
 * Main line.//from www .  ja  v  a 2 s .  co  m
 *
 * @param args command line arguments
 */
public static void main(String[] args) {
    try {
        JSAP parser = createParser();
        JSAPResult config = parser.parse(args);
        if (!config.success()) {
            displayUsage(parser);
        } else {
            String contextPath = config.getString("context");
            String file = config.getString("file");

            ApplicationContext context;
            if (!new File(contextPath).exists()) {
                context = new ClassPathXmlApplicationContext(contextPath);
            } else {
                context = new FileSystemXmlApplicationContext(contextPath);
            }

            if (file != null) {
                IArchetypeService service = (IArchetypeService) context.getBean("archetypeService");
                DocumentHandlers handlers = (DocumentHandlers) context.getBean("documentHandlers");
                TemplateLoader loader = new TemplateLoader(service, handlers);
                loader.load(file);
            } else {
                displayUsage(parser);
            }
        }
    } catch (Throwable throwable) {
        throwable.printStackTrace();
    }
}

From source file:org.ala.harvester.BiocacheHarvester.java

/**
 * Main method for testing this particular Harvester
 *
 * @param args/* w  w  w.j a va2 s.  c  o  m*/
 */
public static void main(String[] args) throws Exception {
    String[] locations = { "classpath*:spring.xml" };
    ApplicationContext context = new ClassPathXmlApplicationContext(locations);
    BiocacheHarvester h = (BiocacheHarvester) context.getBean(BiocacheHarvester.class);
    Repository r = (Repository) context.getBean("repository");
    h.setRepository(r);

    if (args.length == 1) {
        h.setEndDate(new Date());
        if ("-lastYear".equals(args[0])) {
            h.setStartDate(DateUtils.addYears(h.getEndDate(), -1));
        } else if ("-lastMonth".equals(args[0])) {
            h.setStartDate(DateUtils.addMonths(h.getEndDate(), -1));
        } else if ("-lastWeek".equals(args[0])) {
            h.setStartDate(DateUtils.addWeeks(h.getEndDate(), -1));
        } else if ("-lastDay".equals(args[0])) {
            h.setStartDate(DateUtils.addDays(h.getEndDate(), -1));
        } else if ("-lastHour".equals(args[0])) {
            h.setStartDate(DateUtils.addHours(h.getEndDate(), -1));
        } else {
            //attempt to parse the date down to an acceptable date
            try {
                Date startDate = DateUtils.parseDate(args[0], new String[] { "yyyy-MM-dd" });
                h.setStartDate(startDate);
            } catch (java.text.ParseException e) {
                h.setStartDate(DateUtils.addDays(h.getEndDate(), -1));
            }
        }
    } else if (args.length == 2 && "-query".equals(args[0])) {
        h.setQuery(args[1]);
    }
    h.start(-1, true);

}

From source file:org.openvpms.tools.archetype.loader.DerivedNodeUpdater.java

/**
 * Main line.//from   w  w w.j  a  v  a  2s .  c o m
 *
 * @param args the command line arguments
 */
public static void main(String[] args) {
    BasicConfigurator.configure();

    // set the root logger level to error
    Logger root = Logger.getRootLogger();
    root.setLevel(Level.ERROR);
    root.removeAllAppenders();
    root.addAppender(new ConsoleAppender(new PatternLayout("%m%n")));

    try {
        JSAP parser = createParser();
        JSAPResult config = parser.parse(args);
        if (!config.success()) {
            displayUsage(parser, config);
        } else {
            String contextPath = config.getString("context");

            ApplicationContext context;
            if (!new File(contextPath).exists()) {
                context = new ClassPathXmlApplicationContext(contextPath);
            } else {
                context = new FileSystemXmlApplicationContext(contextPath);
            }

            IArchetypeService service = (IArchetypeService) context.getBean("archetypeService");

            if (config.getBoolean("verbose")) {
                log.setLevel(Level.INFO);
            }

            DerivedNodeUpdater updater = new DerivedNodeUpdater(service);
            updater.setBatchSize(config.getInt("batchSize"));
            updater.setFailOnError(config.getBoolean("failOnError"));
            String archetype = config.getString("archetype");
            if (StringUtils.isEmpty(archetype)) {
                displayUsage(parser, config);
            } else {
                updater.update(archetype);
            }
        }
    } catch (Throwable throwable) {
        log.error(throwable, throwable);
    }
}

From source file:com.joymove.service.impl.JOYUserServiceImpl.java

public static void main(String[] args) throws Exception {

    ApplicationContext context = new ClassPathXmlApplicationContext("classpath:test.xml");
    Map<String, Object> likeCondition = new HashMap<String, Object>();
    JOYUser user = new JOYUser();
    DateFormat formatWithTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    user.registerTime = formatWithTime.parse("2013-04-29 15:08:41");

    JOYUserDao dao = (JOYUserDao) context.getBean("JOYUserDao");
    likeCondition.putAll(user.toMap());//from ww  w. java  2 s. c  o m
    likeCondition.put("filter", user);
    List<Map<String, Object>> mapList = dao.getPagedRecordList(likeCondition);
    for (int i = 0; i < mapList.size(); i++) {
        JOYUser userObj = new JOYUser();
        user.fromMap(mapList.get(i));
        System.out.println(user);
    }

    /*
            
            
    JOYPayHistoryService service = (JOYPayHistoryService)context.getBean("JOYPayHistoryService");
    JOYPayHistory payHistoryNew = new JOYPayHistory();
    payHistoryNew.balance = 0.2;
    payHistoryNew.type = 2;
    service.deleteByProperties(payHistoryNew);
            
            
    /*
    JOYUserService service = (JOYUserService)context.getBean("JOYUserService");
    JOYUser user = new JOYUser();
    user.mobileNo = "18500217642";
    List<Map<String,Object>> mapList = service.getExtendInfoPagedList(" select u.*, m.driverLicenseNumber  from JOY_Users u left join JOY_DriverLicense m on u.mobileNo = m.mobileNo ",user);
            
            
    //   JOYUser user2 = new JOYUser();
    Map<String,Object> t = mapList.get(0);
    Iterator i =t.entrySet().iterator();
    JSONObject tt = new JSONObject();
    while(i.hasNext()) {
            
       Map.Entry<String,Object> haha = (Map.Entry<String,Object>)i.next();
        if(String.valueOf(haha.getValue()).equals("null")) {
    logger.trace(haha.getKey()+" is null");
       }
    }
            
    /*
    user2.username = "?";
    user.mobileNo="18500217642";
    service.updateRecord(user2,user);
    user = service.getNeededRecord(user);
      logger.trace(user);
            
    /*
    JOYOrderService service = (JOYOrderService) context.getBean("JOYOrderService");
    JOYOrder order = new JOYOrder();
    order = service.getNeededRecord(order);
    JOYOrder order2 = new JOYOrder();
    order2.startTime = order.startTime;
    order = new JOYOrder();
    order.startTime = new Date(System.currentTimeMillis());
    service.updateRecord(order,order2);
       /*
    JOYNReserveOrderService  service  = (JOYNReserveOrderService)context.getBean("JOYNReserveOrderService");
    JOYReserveOrder order = new JOYReserveOrder();
    //service.insertRecord(order);
    JOYReserveOrder order2 = new JOYReserveOrder();
    order2.mobileNo = "18500217642";
    order2.startTime = new Date(System.currentTimeMillis());
      service.insertRecord(order2);
    order2.startTime = null;
    order = service.getNeededRecord(order2);
     order.startTime = new Date(System.currentTimeMillis());
    service.updateRecord(order,order2);
      order2.startTime = order.startTime;
    order2.mobileNo = null;
    order = service.getNeededRecord(order2);
    logger.trace(order);
    /*
    order.delFlag = 1;
    order.startTime = new Date(System.currentTimeMillis()+30);
    service.updateRecord(order,order2);
            
    order2.mobileNo = null;
    order2.startTime = order.startTime;
    order = service.getNeededRecord(order2);
    logger.trace(order);
    //service.deleteByProperties(order);
            
            
    /*
    JOYIdAuthInfoService service  = (JOYIdAuthInfoService)context.getBean("JOYIdAuthInfoService");
    JOYIdAuthInfo dl = new JOYIdAuthInfo();
    dl.idAuthInfo = "nihao".getBytes();
    dl.idAuthInfo_back = "Hello world".getBytes();
    JOYIdAuthInfo dl2 = new JOYIdAuthInfo();
    dl2.mobileNo = "15577586649";
    service.updateRecord(dl,dl2);
            
            
    service.getNeededList(dl2,null,null);
            
            
            
    List<JOYIdAuthInfo> dList = service.getNeededList(dl,null,null);
    logger.trace(dList.get(0));
            
    for(int i=0;i<dList.get(0).idAuthInfo.length;i++)
    System.out.format("%c",dList.get(0).idAuthInfo[i]);
    /*
    JOYUser user = new JOYUser();
    JOYUser user1 = new JOYUser();
    user.mobileNo = ("18500217642");
    List<JOYUser> userList =  service.getNeededList(user,0,10);
      logger.trace("sdfdsdsf :"+userList.size());
    JOYUser u = userList.get(0);
    logger.trace(u);
     */
}

From source file:com.nxhoaf.dbhelper.view.ExtractDataView.java

/**
 * @param args the command line arguments
 *///from  www  .  j a  va 2 s . c o  m
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(ExtractDataView.class.getName()).log(java.util.logging.Level.SEVERE,
                null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(ExtractDataView.class.getName()).log(java.util.logging.Level.SEVERE,
                null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(ExtractDataView.class.getName()).log(java.util.logging.Level.SEVERE,
                null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(ExtractDataView.class.getName()).log(java.util.logging.Level.SEVERE,
                null, ex);
    }
    //</editor-fold>
    //</editor-fold>
    @SuppressWarnings("resource")
    ApplicationContext context = new ClassPathXmlApplicationContext("classpath:beans.xml");
    final ExtractorController extractDataController = (ExtractorController) context
            .getBean("extractorController");
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new ExtractDataView(extractDataController).setVisible(true);
        }
    });
}

From source file:org.ala.harvester.TrinWikiHarvester.java

/**
 * Main method for testing this particular Harvester
 *
 * @param args//from  w  w w.  ja  va2  s  .co m
 */
public static void main(String[] args) throws Exception {
    String[] locations = { "classpath*:spring.xml" };
    ApplicationContext context = new ClassPathXmlApplicationContext(locations);
    TrinWikiHarvester h = new TrinWikiHarvester();
    Repository r = (Repository) context.getBean("repository");
    h.setRepository(r);

    //set the connection params 
    Map<String, String> connectParams = new HashMap<String, String>();

    //        connectParams.put("endpoint", "https://wiki.trin.org.au/bin/query/Marine/SeaSlugs/Taxa/Acanbrun/topic.json");
    connectParams.put("endpoint", jsonStr);

    h.setConnectionParams(connectParams);
    h.start(TRIN_WIKI_INFOSOURCE_ID);
}

From source file:org.openvpms.tools.data.loader.StaxArchetypeDataLoader.java

/**
 * The main line/*from  w  w  w  . j av  a  2s  . c  o m*/
 *
 * @param args the command line arguments
 */
public static void main(String[] args) {
    try {
        JSAP parser = createParser();
        JSAPResult config = parser.parse(args);
        String[] files = config.getStringArray("file");
        String dir = config.getString("dir");
        if (!config.success() || (files.length == 0 && dir == null)) {
            displayUsage(parser, config);
        } else {
            String contextPath = config.getString("context");

            ApplicationContext context;
            if (!new File(contextPath).exists()) {
                context = new ClassPathXmlApplicationContext(contextPath);
            } else {
                context = new FileSystemXmlApplicationContext(contextPath);
            }

            IArchetypeService service = (IArchetypeService) context.getBean("archetypeService");
            StaxArchetypeDataLoader loader = new StaxArchetypeDataLoader(service);
            loader.setVerbose(config.getBoolean("verbose"));
            loader.setValidateOnly(config.getBoolean("validateOnly"));
            loader.setBatchSize(config.getInt("batchSaveSize"));
            if (files.length != 0) {
                loader.load(files);
            } else if (dir != null) {
                loader.load(dir);
            }
        }
    } catch (Throwable throwable) {
        log.error(throwable, throwable);
    }
}

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

/**
 * @param args//from w w w  .  ja  v  a2  s  . c  o m
 */
public static void main(String[] args) throws Exception {
    logger.info("Starting ANBG load....");
    long start = System.currentTimeMillis();
    ApplicationContext context = SpringUtils.getContext();
    ANBGDataLoader loader = (ANBGDataLoader) context.getBean(ANBGDataLoader.class);
    loader.load();
    long finish = System.currentTimeMillis();
    logger.info("Data loaded in: " + ((finish - start) / 60000) + " minutes.");
    System.exit(1);
}

From source file:org.ala.harvester.MorphbankHarvester.java

/**
 * Main method for testing this particular Harvester
 *
 * @param args/*from  ww w.  java 2  s .c o  m*/
 */
public static void main(String[] args) throws Exception {
    String[] locations = { "classpath*:spring.xml" };
    ApplicationContext context = new ClassPathXmlApplicationContext(locations);
    MorphbankHarvester h = new MorphbankHarvester();
    Repository r = (Repository) context.getBean("repository");
    h.setRepository(r);

    //set the connection params   
    Map<String, String> connectParams = new HashMap<String, String>();

    if (args.length == 1 && args[0].equals("Coral")) {
        h.setCoral(true);
        connectParams.put("endpoint",
                "http://morphbank-svc.ala.org.au/mb3/request?method=search&objecttype=Image&keywords=Coral+Reef+Research&limit="
                        + RESULT_LIMIT
                        + "&firstResult=0&user=&group=&change=&lastDateChanged=&numChangeDays=1&id=&taxonName=&format=svc");
    } else if (args.length == 1) {
        connectParams.put("endpoint",
                "http://morphbank-svc.ala.org.au/mb3/request?method=search&objecttype=Image&keywords=Australia&limit="
                        + RESULT_LIMIT
                        + "&firstResult=0&user=&group=&change=&lastDateChanged=&numChangeDays=1&id=&taxonName=&format=svc");
        try {
            h.setInit(Integer.valueOf(args[0]));
        } catch (NumberFormatException nfe) {
            System.out.println("Starting id is not a number!");
            System.exit(1);
        }
    } else {
        connectParams.put("endpoint",
                "http://morphbank-svc.ala.org.au/mb3/request?method=search&objecttype=Image&keywords=Australia&limit="
                        + RESULT_LIMIT
                        + "&firstResult=0&user=&group=&change=&lastDateChanged=&numChangeDays=1&id=&taxonName=&format=svc");
    }

    h.setConnectionParams(connectParams);
    h.start(MORPHBANK_INFOSOURCE_ID);
}

From source file:org.mn.z80util.testbench.MZ80TestBench.java

/**
 * The main method. Loads a Spring Framework application context and
 * testbench bean from it./*from  w  w w .ja  v a2s.  c o m*/
 *
 * @see spring-testbench.xml
 */
public static void main(String[] args) {
    System.out.println(COPYRIGHT_NOTICE);
    ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "spring-testbench.xml" });
    testBench = (MZ80TestBench) context.getBean("testbench");

    // The correct way is to initialize the GUI in the event dispatch thread.
    if (testBench.wantGui) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                testBench.createAndShowGUI();
                new Thread(testBench, "Z80-Testbench-with-GUI").start();
            }
        });
    } else {
        new Thread(testBench, "Z80-Testbench-without-GUI").start();
    }
}