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.repository.Validator.java

/**
 * Main method//w ww  .  j a va2s . c  om
 *
 * @param args
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    ApplicationContext context = new ClassPathXmlApplicationContext("classpath*:spring.xml");
    Validator validator = (Validator) context.getBean("validator");
    Integer id = 1008;
    if (args.length > 0) {
        id = Integer.parseInt(args[0]);
    }
    validator.setInfoSourceId(id);
    validator.findAndValidateFiles();
}

From source file:org.alfresco.filesys.NFSServerBean.java

/**
 * Runs the NFS server directly/*  w ww  . jav  a2s . c  o  m*/
 * 
 * @param args String[]
 */
public static void main(String[] args) {
    PrintStream out = System.out;

    out.println("NFS Server Test");
    out.println("----------------");

    try {
        // Create the configuration service in the same way that Spring creates it

        ApplicationContext ctx = new ClassPathXmlApplicationContext("alfresco/application-context.xml");

        // Get the NFS server bean

        NFSServerBean server = (NFSServerBean) ctx.getBean("nfsServer");
        if (server == null) {
            throw new AlfrescoRuntimeException("Server bean 'nfsServer' not defined");
        }

        // Stop the FTP server, if running

        NetworkServer srv = server.getConfiguration().findServer("FTP");
        if (srv != null)
            srv.shutdownServer(true);

        // Stop the CIFS server, if running

        srv = server.getConfiguration().findServer("SMB");
        if (srv != null)
            srv.shutdownServer(true);

        // Only wait for shutdown if the NFS server is enabled

        if (server.getConfiguration().hasConfigSection(NFSConfigSection.SectionName)) {

            // NFS server should have automatically started
            // Wait for shutdown via the console

            out.println("Enter 'x' to shutdown ...");
            boolean shutdown = false;

            // Wait while the server runs, user may stop the server by typing a key

            while (shutdown == false) {

                // Wait for the user to enter the shutdown key

                int ch = System.in.read();

                if (ch == 'x' || ch == 'X')
                    shutdown = true;

                synchronized (server) {
                    server.wait(20);
                }
            }

            // Stop the server

            server.stopServer();
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    System.exit(1);
}

From source file:org.apache.s4.MainApp.java

public static void main(String args[]) throws Exception {
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("corehome").hasArg().withDescription("core home").create("c"));

    options.addOption(//from   w ww  . j ava  2s  .  com
            OptionBuilder.withArgName("appshome").hasArg().withDescription("applications home").create("a"));

    options.addOption(OptionBuilder.withArgName("s4clock").hasArg().withDescription("s4 clock").create("d"));

    options.addOption(OptionBuilder.withArgName("seedtime").hasArg()
            .withDescription("event clock initialization time").create("s"));

    options.addOption(
            OptionBuilder.withArgName("extshome").hasArg().withDescription("extensions home").create("e"));

    options.addOption(
            OptionBuilder.withArgName("instanceid").hasArg().withDescription("instance id").create("i"));

    options.addOption(
            OptionBuilder.withArgName("configtype").hasArg().withDescription("configuration type").create("t"));

    CommandLineParser parser = new GnuParser();
    CommandLine commandLine = null;
    String clockType = "wall";

    try {
        commandLine = parser.parse(options, args);
    } catch (ParseException pe) {
        System.err.println(pe.getLocalizedMessage());
        System.exit(1);
    }

    int instanceId = -1;
    if (commandLine.hasOption("i")) {
        String instanceIdStr = commandLine.getOptionValue("i");
        try {
            instanceId = Integer.parseInt(instanceIdStr);
        } catch (NumberFormatException nfe) {
            System.err.println("Bad instance id: %s" + instanceIdStr);
            System.exit(1);
        }
    }

    if (commandLine.hasOption("c")) {
        coreHome = commandLine.getOptionValue("c");
    }

    if (commandLine.hasOption("a")) {
        appsHome = commandLine.getOptionValue("a");
    }

    if (commandLine.hasOption("d")) {
        clockType = commandLine.getOptionValue("d");
    }

    if (commandLine.hasOption("e")) {
        extsHome = commandLine.getOptionValue("e");
    }

    String configType = "typical";
    if (commandLine.hasOption("t")) {
        configType = commandLine.getOptionValue("t");
    }

    long seedTime = 0;
    if (commandLine.hasOption("s")) {
        seedTime = Long.parseLong(commandLine.getOptionValue("s"));
    }

    File coreHomeFile = new File(coreHome);
    if (!coreHomeFile.isDirectory()) {
        System.err.println("Bad core home: " + coreHome);
        System.exit(1);
    }

    File appsHomeFile = new File(appsHome);
    if (!appsHomeFile.isDirectory()) {
        System.err.println("Bad applications home: " + appsHome);
        System.exit(1);
    }

    if (instanceId > -1) {
        System.setProperty("instanceId", "" + instanceId);
    } else {
        System.setProperty("instanceId", "" + S4Util.getPID());
    }

    List loArgs = commandLine.getArgList();

    if (loArgs.size() < 1) {
        // System.err.println("No bean configuration file specified");
        // System.exit(1);
    }

    // String s4ConfigXml = (String) loArgs.get(0);
    // System.out.println("s4ConfigXml is " + s4ConfigXml);

    ClassPathResource propResource = new ClassPathResource("s4-core.properties");
    Properties prop = new Properties();
    if (propResource.exists()) {
        prop.load(propResource.getInputStream());
    } else {
        System.err.println("Unable to find s4-core.properties. It must be available in classpath");
        System.exit(1);
    }

    ApplicationContext coreContext = null;
    String configBase = coreHome + File.separatorChar + "conf" + File.separatorChar + configType;
    String configPath = "";
    List<String> coreConfigUrls = new ArrayList<String>();
    File configFile = null;

    // load clock configuration
    configPath = configBase + File.separatorChar + clockType + "-clock.xml";
    coreConfigUrls.add(configPath);

    // load core config xml
    configPath = configBase + File.separatorChar + "s4-core-conf.xml";
    configFile = new File(configPath);
    if (!configFile.exists()) {
        System.err.printf("S4 core config file %s does not exist\n", configPath);
        System.exit(1);
    }

    coreConfigUrls.add(configPath);
    String[] coreConfigFiles = new String[coreConfigUrls.size()];
    coreConfigUrls.toArray(coreConfigFiles);

    String[] coreConfigFileUrls = new String[coreConfigFiles.length];
    for (int i = 0; i < coreConfigFiles.length; i++) {
        coreConfigFileUrls[i] = "file:" + coreConfigFiles[i];
    }

    coreContext = new FileSystemXmlApplicationContext(coreConfigFileUrls, coreContext);
    ApplicationContext context = coreContext;

    Clock clock = (Clock) context.getBean("clock");
    if (clock instanceof EventClock && seedTime > 0) {
        EventClock s4EventClock = (EventClock) clock;
        s4EventClock.updateTime(seedTime);
        System.out.println("Intializing event clock time with seed time " + s4EventClock.getCurrentTime());
    }

    PEContainer peContainer = (PEContainer) context.getBean("peContainer");

    Watcher w = (Watcher) context.getBean("watcher");
    w.setConfigFilename(configPath);

    // load extension modules
    String[] configFileNames = getModuleConfigFiles(extsHome, prop);
    if (configFileNames.length > 0) {
        String[] configFileUrls = new String[configFileNames.length];
        for (int i = 0; i < configFileNames.length; i++) {
            configFileUrls[i] = "file:" + configFileNames[i];
        }
        context = new FileSystemXmlApplicationContext(configFileUrls, context);
    }

    // load application modules
    configFileNames = getModuleConfigFiles(appsHome, prop);
    if (configFileNames.length > 0) {
        String[] configFileUrls = new String[configFileNames.length];
        for (int i = 0; i < configFileNames.length; i++) {
            configFileUrls[i] = "file:" + configFileNames[i];
        }
        context = new FileSystemXmlApplicationContext(configFileUrls, context);
        // attach any beans that implement ProcessingElement to the PE
        // Container
        String[] processingElementBeanNames = context.getBeanNamesForType(AbstractPE.class);
        for (String processingElementBeanName : processingElementBeanNames) {
            AbstractPE bean = (AbstractPE) context.getBean(processingElementBeanName);
            bean.setClock(clock);
            try {
                bean.setSafeKeeper((SafeKeeper) context.getBean("safeKeeper"));
            } catch (NoSuchBeanDefinitionException ignored) {
                // no safe keeper = no checkpointing / recovery
            }
            // if the application did not specify an id, use the Spring bean name
            if (bean.getId() == null) {
                bean.setId(processingElementBeanName);
            }
            System.out.println("Adding processing element with bean name " + processingElementBeanName + ", id "
                    + ((AbstractPE) bean).getId());
            peContainer.addProcessor((AbstractPE) bean);
        }
    }
}

From source file:com.yizhiyun.test.DingCanTest.java

public static void main(String args[]) {
    ApplicationContext context = new ClassPathXmlApplicationContext(
            "classpath*:/applicationContext-service.xml");
    //        CustomerService customerService = context.getBean(CustomerService.class);
    //        Customer customer = new Customer(0, "??", "178238324234", "?", "178238324234", "178238324234", "178238324234");
    //        customerService.saveCustomer(customer);

    VendorService venderService = context.getBean(VendorService.class);
    //          Vendor vendor = new Vendor(0, "222?", "178238324234", "A", "178238324234", "178238324234", "178238324234", "178238324234", "178238324234", 49.2132, 121.23322); 
    List<Vendor> vendors = venderService.getVendorsByCoordinate(49, 50, 121.5f, 122);
    for (Vendor vendor : vendors) {
        System.out.println(vendor.getRestaurantName());
    }// w  ww  . j av a  2 s .c o m
}

From source file:DataLoader.java

public static void main(String[] args)
        throws IOException, ValidationException, LicenseException, JobExecutionAlreadyRunningException,
        JobRestartException, JobInstanceAlreadyCompleteException, JobParametersInvalidException {

    System.out.println(// w ww . jav  a  2  s. c  o  m
            "System is initialising. Please wait for a few seconds then type your queries below once you see the prompt (->)");

    C24.init().withLicence("/biz/c24/api/license-ads.dat");

    // Create our application context - assumes the Spring configuration is in the classpath in a file called spring-config.xml
    ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");

    // ========================================================================
    // DEMO
    // A simple command-line interface to allow us to query the GemFire regions
    // ========================================================================

    GemfireTemplate template = context.getBean(GemfireTemplate.class);

    BufferedReader br = new BufferedReader(new java.io.InputStreamReader(System.in));

    boolean writePrompt = true;

    try {
        while (true) {
            if (writePrompt) {
                System.out.print("-> ");
                System.out.flush();
                writePrompt = false;
            }
            if (br.ready()) {
                try {

                    String request = br.readLine();
                    System.out.println("Running: " + request);
                    SelectResults<Object> results = template.find(request);
                    System.out.println();
                    System.out.println("Result:");
                    for (Object result : results.asList()) {
                        System.out.println(result.toString());
                    }
                } catch (Exception ex) {
                    System.out.println("Error executing last command " + ex.getMessage());
                    //ex.printStackTrace();
                }

                writePrompt = true;

            } else {
                // Wait for a second and try again
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ioEx) {
                    break;
                }
            }
        }
    } catch (IOException ioe) {
        // Write any exceptions to stderr
        System.err.print(ioe);
    }

}

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

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

    //set the connection params   
    Map<String, String> connectParams = new HashMap<String, String>();
    connectParams.put("endpoint", "http://www.museum.wa.gov.au/waiss/pages/image.htm");

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

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

public static void main(String[] args) throws Exception {
    String[] locations = { "classpath*:spring.xml" };

    ApplicationContext context = new ClassPathXmlApplicationContext(locations);
    WikipediaImageHarvester h = new WikipediaImageHarvester();
    Repository r = (Repository) context.getBean("repository");
    h.setRepository(r);// w w w  .  j  av  a 2  s  .  com
    if (args.length == 1 && "--download".equals(args[0])) {
        h.setDownloaded(false);
    }
    h.start(1036);
}

From source file:org.lieuofs.extraction.etatpays.ExtractionEtat.java

/**
 * @param args/*w  w  w  .j  a  va  2 s . c  o m*/
 */
public static void main(String[] args) throws IOException {
    ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "beans_lieuofs.xml" });
    EtatTerritoireCritere critere = new EtatTerritoireCritere();
    critere.setEstEtat(Boolean.TRUE);
    // critere.setValide(Boolean.TRUE);

    EtatTerritoireDao dao = (EtatTerritoireDao) context.getBean("etatTerritoireDao");
    Set<EtatTerritoirePersistant> etats = dao.rechercher(critere);

    EtatWriter etatWriter = new CsvPlatEtatWriter();
    BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream("Etat.txt"), "UTF-8"));

    List<EtatTerritoirePersistant> listeTriee = new ArrayList<EtatTerritoirePersistant>(etats);
    Collections.sort(listeTriee, new Comparator<EtatTerritoirePersistant>() {

        @Override
        public int compare(EtatTerritoirePersistant o1, EtatTerritoirePersistant o2) {
            //return o1.getFormeCourte("fr").compareTo(o2.getFormeCourte("fr"));
            return o1.getNumeroOFS() - o2.getNumeroOFS();
        }

    });

    for (EtatTerritoirePersistant etat : listeTriee) {
        String etatStr = etatWriter.ecrireEtat(etat);
        if (null != etatStr) {
            writer.append(etatStr);
        }
    }
    writer.close();
}

From source file:org.openvpms.tools.data.migration.DetailsMigrator.java

/**
 * Main line.//from   www  .  ja  v a2 s  .  com
 *
 * @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");

            ApplicationContext context;
            if (!new File(contextPath).exists()) {
                context = new ClassPathXmlApplicationContext(contextPath);
            } else {
                context = new FileSystemXmlApplicationContext(contextPath);
            }
            DataSource source = (DataSource) context.getBean("dataSource");
            DetailsMigrator migrator = new DetailsMigrator(source);
            migrator.export();
        }
    } catch (Throwable throwable) {
        throwable.printStackTrace();
    }
}

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

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

    //set the connection params   
    h.start(BLUE_TIER_INFOSOURCE_ID);
}