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.ala.preprocess.ColFamilyNamesProcessor.java

public static void main(String[] args) throws Exception {
    ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "classpath*:spring.xml" });
    ColFamilyNamesProcessor p = new ColFamilyNamesProcessor();
    p.setInfoSourceDAO((InfoSourceDAO) context.getBean("infoSourceDAO"));
    p.setRepository((Repository) context.getBean("repository"));
    p.process();/*from   w  w  w .  ja  v  a  2 s .c o m*/
    System.exit(1);
}

From source file:org.jasig.schedassist.impl.AppointmentTool.java

/**
 * main method to interact with {@link AvailableApplicationTool}.
 * // w w  w. j av a2  s.  c  o m
 * @param args
 * @throws SchedulingException 
 * @throws NotAVisitorException 
 * @throws CalendarAccountNotFoundException 
 */
public static void main(String[] args)
        throws CalendarAccountNotFoundException, NotAVisitorException, SchedulingException {
    // scan the arguments
    if (args.length == 0) {
        System.err.println(
                "Usage: AppointmentTool create [-owner username] [-visitor username] [-start YYYYmmdd-hhmm] [-duration minutes]");
        System.exit(1);

    }

    if (CREATE.equals(args[0])) {
        String visitorUsername = null;
        String ownerUsername = null;
        Date startTime = null;
        int duration = 30;

        for (int i = 1; i < args.length; i++) {
            if (OWNER_ARG.equalsIgnoreCase(args[i])) {
                ownerUsername = args[++i];
            } else if (VISITOR_ARG.equalsIgnoreCase(args[i])) {
                visitorUsername = args[++i];
            } else if (START_ARG.equalsIgnoreCase(args[i])) {
                String start = args[++i];
                SimpleDateFormat df = new SimpleDateFormat(DATE_FORMAT);
                try {
                    startTime = df.parse(start);
                } catch (ParseException e) {
                    System.err.println("Invalid format for start parameter, must match: " + DATE_FORMAT);
                    System.exit(1);
                }
            } else if (DURATION_ARG.equalsIgnoreCase(args[i])) {
                String dur = args[++i];
                duration = Integer.parseInt(dur);
            }
        }

        Validate.notEmpty(ownerUsername, "owner argument cannot be empty");
        Validate.notEmpty(visitorUsername, "visitor argument cannot be empty");
        Validate.notNull(startTime, "start argument cannot be empty");

        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(CONFIG);

        AppointmentTool tool = new AppointmentTool(
                (SchedulingAssistantService) applicationContext.getBean("schedulingAssistantService"),
                (ICalendarAccountDao) applicationContext.getBean("calendarAccountDao"),
                (OwnerDao) applicationContext.getBean("ownerDao"),
                (VisitorDao) applicationContext.getBean("visitorDao"),
                (AvailableScheduleDao) applicationContext.getBean("availableScheduleDao"));

        Date endDate = DateUtils.addMinutes(startTime, duration);
        VEvent event = tool.createAvailableAppointment(visitorUsername, ownerUsername, startTime, endDate);
        System.out.println("Event successfully created: ");
        System.out.println(event.toString());
    } else {
        System.err.println("Unrecognized command: " + args[0]);
        System.exit(1);
    }
}

From source file:ezbake.example.ezmongo.EzMongoSpringDataSampleClient.java

public static void main(String[] args)
        throws VisibilityParseException, ClassificationConversionException, EzMongoBaseException {

    // For XML/*from w ww . ja  va  2s  . c  o m*/
    ApplicationContext ctx = new GenericXmlApplicationContext("springDataConfig.xml");

    // For Annotation
    //ApplicationContext ctx =
    //        new AnnotationConfigApplicationContext(SpringMongoConfig.class);
    MongoOperations mongoOperation = (MongoOperations) ctx.getBean("mongoTemplate");

    User user = new User("mkyong", "password123");

    // Here, we would insert the security tagging fields into the DBObject by calling a utility class (RedactHelper.java).
    Visibility vis = new Visibility();
    // Convert CAPCO to Accumulo-style boolean expression string and set it in the Visibility object.
    String booleanExpressionString = ClassificationUtils.getAccumuloVisibilityStringFromCAPCO("SECRET");
    vis.setFormalVisibility(booleanExpressionString);
    RedactHelper.setSecurityFieldsInDBObject(user, vis, "testAppId");

    // Also set the Name field in the User
    Name name = new Name("testFirstName", "testLastName");
    Visibility nameVis = new Visibility();
    nameVis.setFormalVisibility(booleanExpressionString);
    RedactHelper.setSecurityFieldsInDBObject(name, nameVis, "testAppId");

    user.setName(name);

    // Call the Provenance service to get a unique ID for the document -
    //   the unique ID would be used for the Purge feature.

    // save
    mongoOperation.save(user);

    // now user object got the created id.
    System.out.println("1. user : " + user);

    // query to search user
    Query searchUserQuery = new Query(Criteria.where("username").is("mkyong"));

    // find the saved user again.
    User savedUser = mongoOperation.findOne(searchUserQuery, User.class);
    System.out.println("2. find - savedUser : " + savedUser);

}

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

/**
 * Main method for testing this particular Harvester
 *
 * @param args//w  w  w .  j  a v  a  2  s.  c o  m
 */
public static void main(String[] args) throws Exception {

    if (args.length != 3) {
        printUsage();
        System.exit(1);
    }

    String infosourceId = args[0];
    String siteMap = args[1];
    String documentMapperClass = args[2];

    String[] locations = { "classpath*:spring.xml" };
    ApplicationContext context = new ClassPathXmlApplicationContext(locations);
    RawFileHarvester h = (RawFileHarvester) context.getBean("rawFileHarvester");
    h.setDocumentMapper((DocumentMapper) Class.forName(documentMapperClass).newInstance());
    HashMap<String, String> connectParams = new HashMap<String, String>();
    connectParams.put("sitemap", siteMap);
    h.setConnectionParams(connectParams);
    h.start(Integer.parseInt(infosourceId));
}

From source file:hotelregistration.HotelRegistration.java

/**
 * @param args the command line arguments
 *//*from  w  w w.  j  av  a  2s . c  om*/
public static void main(String[] args) {

    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

    DBConnection dbCon = new DBConnection();
    dbCon.getConnetion();

    try {

        Statement st = dbCon.getConnetion().createStatement();
        ResultSet rs = st.executeQuery("SELECT NAME, ADDRESS FROM HOTEL");
        Hotel hotel = (Hotel) context.getBean("hotel");
        while (rs.next()) {
            hotel.setName(rs.getString("name"));
            hotel.setAddress(rs.getString("address"));
            System.out.println("1. Nombre: " + hotel.getName() + ", Direccion: " + hotel.getAddress());
        }

        HotelDao hotelDao = (HotelDao) context.getBean("hotelDao");
        Hotel hotel1 = hotelDao.findHotel("Moon");

        Hotel hotel2 = new Hotel();
        hotel2.setName("Jupiter");
        hotel2.setAddress("Jupiter");
        hotelDao.insertHotel(hotel2);

        System.out.println("2. Nombre: " + hotel1.getName() + ", Direccion: " + hotel1.getAddress());

    } catch (SQLException ex) {
        Logger.getLogger(HotelRegistration.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:uk.co.onehp.trickle.routing.ServiceCustomT.java

/**
 * @param args//from   w  w  w .  j a  v a 2  s.c o  m
 * @throws Exception
 * @throws CamelExecutionException
 */
public static void main(String[] args) throws CamelExecutionException, Exception {
    final ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
            "classpath:/spring-trickle.xml");
    //      final BetfairService betfairService = (BetfairService) applicationContext
    //      .getBean("betfairService");

    final ScheduledService scheduledService = (ScheduledService) applicationContext.getBean("scheduledService");

    //      final DomainService domainService = (DomainService) applicationContext
    //      .getBean("domainService");
    //
    //      System.out.println(domainService.getCompleteBets());

    scheduledService.login();
    //      scheduledService.getUkMarket();
    //      scheduledService.getAllMeetings();
    //      scheduledService.getAllRaces();
    //      scheduledService.getAllRacePrices();

    //      final Strategy strategy = new Strategy();
    //      strategy.setAspect(BettingAspect.BACK);
    //      strategy.setBetSecondsBeforeStartTime(Lists.newArrayList(60,120,180));
    //      strategy.setChasePriceByTick(0);
    //      strategy.setLiability(new BigDecimal("6.00"));
    //      strategy.setMaxOdds(new BigDecimal("1000"));
    //      strategy.setMinOdds(new BigDecimal("1.01"));
    //
    //      final Race race = new Race(102325207, "kemp 4:25", new LocalDateTime(2011,2,26,14,25,0));
    //      final Horse horse = new Horse();
    //      horse.setRaceId(102325207);
    //      horse.setRunnerId(4512035);
    //      horse.setRace(race);
    //      horse.setPrices(Lists.newArrayList(new Pricing(new BigDecimal("1.09"),new BigDecimal("100.50"),BettingAspect.BACK),
    //                                 new Pricing(new BigDecimal("1.08"),new BigDecimal("100.50"),BettingAspect.BACK),
    //                                 new Pricing(new BigDecimal("1.01"),new BigDecimal("100.50"),BettingAspect.LAY),
    //                                 new Pricing(new BigDecimal("1.02"),new BigDecimal("100.50"),BettingAspect.LAY)));
    //      horse.setName("Captain Chris");
    //
    //      final Bet bet = new  Bet(horse, strategy);
    //
    //      betfairService.placeBet(bet);
}

From source file:koper.demo.performance.SendDataEventMsgPerf.java

/**
 * DataEventMsg ?/*w w  w  . ja  v a2s  .  com*/
 * @param args ?:???
 *             ?:?????? sleep 
 */
public static void main(String[] args) throws Exception {
    ApplicationContext context = new ClassPathXmlApplicationContext("kafka/context-data-message.xml",
            "kafka/context-data-producer.xml");

    Order order = new Order();
    order.setId(100);
    order.setOrderNo("order_no");
    order.setCreatedTime("oroder_created_time");

    OrderService orderService = (OrderService) context.getBean("orderServiceImpl");

    int threadNum = 1;
    long sleepMs = 1000L;
    if (args.length >= 1) {
        threadNum = Integer.parseInt(args[0]);
        sleepMs = Long.parseLong(args[1]);
    }
    final long finalSleepMs = sleepMs;
    ExecutorService executorService = Executors.newFixedThreadPool(threadNum);
    for (int i = 0; i < threadNum; ++i) {
        executorService.execute(() -> {
            while (true) {
                orderService.insertOrder(order);
                try {
                    Thread.sleep(finalSleepMs);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

From source file:org.jasig.schedassist.impl.InitializeSchedulingAssistantDatabase.java

/**
 * Optionally accepts 1 argument./*from  www  .j a  v a2s .co  m*/
 * If the argument evaluates to true ({@link Boolean#parseBoolean(String)}, the main method
 * will NOT run the SQL statements in the "destroyDdl" Resource.
 * 
 * @param args
 */
public static void main(String[] args) throws Exception {
    LOG.info("loading applicationContext: " + CONFIG);
    ApplicationContext context = new ClassPathXmlApplicationContext(CONFIG);

    boolean firstRun = false;
    if (args.length == 1) {
        firstRun = Boolean.parseBoolean(args[0]);
    }
    InitializeSchedulingAssistantDatabase init = new InitializeSchedulingAssistantDatabase();
    init.setDataSource((DataSource) context.getBean("dataSource"));

    if (!firstRun) {
        Resource destroyDdl = (Resource) context.getBean("destroyDdl");
        if (null != destroyDdl) {
            String destroySql = IOUtils.toString(destroyDdl.getInputStream());
            init.executeDdl(destroySql);
            LOG.warn("existing tables removed");
        }
    }

    Resource createDdl = (Resource) context.getBean("createDdl");
    String createSql = IOUtils.toString(createDdl.getInputStream());

    init.executeDdl(createSql);
    LOG.info("database initialization complete");
}

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

/**
 * Main method for testing this particular Harvester
 *
 * @param args//  w w w  . j av a  2 s .  c  om
 */
public static void main(String[] args) throws Exception {

    if (args.length != 3) {
        printUsage();
        System.exit(1);
    }

    String infosourceId = args[0];
    String siteMap = args[1];
    String documentMapperClass = args[2];

    String[] locations = { "classpath*:spring.xml" };
    ApplicationContext context = new ClassPathXmlApplicationContext(locations);
    CSVHarvester h = (CSVHarvester) context.getBean("csvHarvester");
    h.setDocumentMapper((DocumentMapper) Class.forName(documentMapperClass).newInstance());
    HashMap<String, String> connectParams = new HashMap<String, String>();
    connectParams.put("sitemap", siteMap);
    h.setConnectionParams(connectParams);
    h.start(Integer.parseInt(infosourceId));
}

From source file:streaming.gui.JFramePrincipale.java

/**
 * @param args the command line arguments
 *//*w  w  w .j  a  v a  2  s. c om*/
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(JFramePrincipale.class.getName()).log(java.util.logging.Level.SEVERE,
                null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(JFramePrincipale.class.getName()).log(java.util.logging.Level.SEVERE,
                null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(JFramePrincipale.class.getName()).log(java.util.logging.Level.SEVERE,
                null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(JFramePrincipale.class.getName()).log(java.util.logging.Level.SEVERE,
                null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {

            ApplicationContext context = new FileSystemXmlApplicationContext(
                    "file:/C:\\Users\\admin\\Documents\\NetBeansProjects\\Streaming\\application-context.xml");
            JFramePrincipale jfp = context.getBean(JFramePrincipale.class);
            jfp.setSize(800, 600);
            jfp.setVisible(true);

        }
    });
}