Example usage for java.util List iterator

List of usage examples for java.util List iterator

Introduction

In this page you can find the example usage for java.util List iterator.

Prototype

Iterator<E> iterator();

Source Link

Document

Returns an iterator over the elements in this list in proper sequence.

Usage

From source file:it.jnrpe.server.CJNRPEServer.java

public static void main(String[] args) {
    CommandLine cl = parseCommandLine(args);

    if (cl.hasOption("help") && cl.getOptionValue("help") == null)
        printUsage();/*w  w w. ja  v  a 2  s. c om*/

    if (cl.hasOption("version"))
        printVersion();

    CJNRPEConfiguration.init(cl.getOptionValue("conf"));

    if (cl.hasOption("help") && cl.getOptionValue("help") != null)
        printHelp(cl.getOptionValue("help"));

    if (cl.hasOption("list"))
        printPluginList();

    if (cl.hasOption("generateConfig"))
        generateScheletonConfig(cl.getOptionValue("generateConfig"));

    //        // Configure the timeout watcher
    //        m_ThreadTimeoutWatcher = new ThreadTimeoutWatcher();
    //        m_ThreadTimeoutWatcher.setThreadTimeout(CJNRPEConfiguration.getInstance().getThreadTimeout());
    //        m_ThreadTimeoutWatcher.start();

    List vBindings = CJNRPEConfiguration.getInstance().getServerBindings();

    for (Iterator iterator = vBindings.iterator(); iterator.hasNext();) {
        CBinding binding = (CBinding) iterator.next();
        try {
            CBindingThread bt = new CBindingThread(binding);
            bt.setAcceptedHosts(CJNRPEConfiguration.getInstance().getAcceptedHosts());
            bt.start();
            m_vBindingThreads.add(bt);
        } catch (Exception e) {
            System.out.println("ERROR BINDING TO ADDRESS " + binding.getIP() + ":" + binding.getPort() + " - "
                    + e.getMessage());
            System.exit(-1);
        }
    }
}

From source file:jsonclient.JsonClient.java

public static void main(String args[]) {

    int EPS = 1;/*from   w w w.  ja v  a2s.  c  om*/
    List<Place> countries = new ArrayList<Place>();
    List<Thread> threads = new ArrayList<Thread>();
    Country country;
    countries = getCountries();
    //CountrySearcher countrySearcher = null;
    Iterator<Place> itrCountry = countries.iterator();
    ExecutorService exec = Executors.newFixedThreadPool(4);

    while (itrCountry.hasNext()) {
        country = new Country(itrCountry.next());
        CountrySearcher cs = new CountrySearcher(country, EPS);
        threads.add(cs.thread);
        exec.execute(cs);
    }

    exec.shutdown();

    for (Thread th : threads)
        try {
            th.join();
        } catch (InterruptedException ex) {
            Logger.getLogger(JsonClient.class.getName()).log(Level.SEVERE, null, ex);
        }

}

From source file:co.edu.uniandes.bigdata.ProyectoBigData.logica.FeedsReader.java

@SuppressWarnings("CallToPrintStackTrace")
public static void main(String[] args) throws MalformedURLException, IOException, XQException {

    FeedsReader test = new FeedsReader();
    test.updateFeeds();//from   w ww .j  a va 2  s. c om
    List<Feed> feeds = test.filterFeedsXquery(ALL_CATEGORIES, "title", "food", false);
    //List<Feed> feeds = test.filterFeedsRegex(ALL_CATEGORIES, "the ", true);

    for (Iterator<Feed> iterator = feeds.iterator(); iterator.hasNext();) {
        System.out.println(iterator.next().getTitle());
    }

}

From source file:tsp.TSPTestSpring.java

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

    ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
    ITSPAlgorithm tspBruteForce = (ITSPAlgorithm) context.getBean("tspBruteForce");
    ITSPAlgorithm tspNearestNeighbor = (ITSPAlgorithm) context.getBean("tspNearestNeighbor");
    ITSPAlgorithm tspRandomSelection = (ITSPAlgorithm) context.getBean("tspRandomSelection");
    ITSPAlgorithm tspGeneticAlgorithm = (ITSPAlgorithm) context.getBean("tspGeneticAlgorithm");

    // test//w w  w  . j a  v a  2 s  .  c  o m
    ITSPAlgorithm tspGeneticAlgorithm2 = (ITSPAlgorithm) context.getBean("tspGeneticAlgorithm");
    if (tspGeneticAlgorithm == tspGeneticAlgorithm2)
        System.out.println("[TEST] The Same instance!!!");

    List<TSPPath> bestPathList;
    Iterator it;

    tspBruteForce.getGraph().printGraph();

    // Brute Force
    // if (g.getNumVertex()>100) return;
    System.out.printf("The Best Routes Found By Brute Force:\n");
    bestPathList = tspBruteForce.getBestPathList(3);
    it = bestPathList.iterator();
    while (it.hasNext()) {
        TSPPath path = ((TSPPath) it.next());
        path.printPathStartingFrom(0);
    }
    System.out.println("");

    // Select the best XXX routes from a randomly generated sample pool
    System.out.printf("The Best Routes Found (Approximation By Random Selection and Ranking):\n");
    // System.out.printf("Sample Size: %d\n", tspRandomSelection.getSampleSize());
    bestPathList = tspRandomSelection.getBestPathList(3);
    it = bestPathList.iterator();
    while (it.hasNext()) {
        TSPPath path = ((TSPPath) it.next());
        path.printPathStartingFrom(0);
    }
    System.out.println("");

    // Select the best XXX routes by Nearest Neighbor
    System.out.printf("The Best Routes Found (Approximation By Nearest Neighbor):\n");
    bestPathList = tspNearestNeighbor.getBestPathList(3);
    it = bestPathList.iterator();
    while (it.hasNext()) {
        TSPPath path = ((TSPPath) it.next());
        path.printPathStartingFrom(0);
    }
    System.out.println("");

    // Select the best XXX routes by Genetic Algorithm
    System.out.printf("The Best Routes Found (Approximation By Genetic Algorithm):\n");
    // System.out.printf("Population Size: %d\n", tspGeneticAlgorithm.getPopSize());
    bestPathList = tspGeneticAlgorithm.getBestPathList(3);
    it = bestPathList.iterator();
    while (it.hasNext()) {
        TSPPath path = ((TSPPath) it.next());
        path.printPathStartingFrom(0);
    }
    System.out.println("");

}

From source file:Main.java

public static void main(String[] args) throws Exception {
    XMLEventFactory eventFactory = XMLEventFactory.newInstance();
    XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(System.out);

    Namespace ns1 = eventFactory.createNamespace("ns1", "http://www.e.com/ns1");
    Namespace ns2 = eventFactory.createNamespace("ns2", "http://www.e.com/ns2");
    List<Namespace> namespaceList = new ArrayList<Namespace>();
    namespaceList.add(ns1);//from   w w w  . j  a  v a 2  s  .co  m
    namespaceList.add(ns2);

    Attribute attribute = eventFactory.createAttribute(ns2.getPrefix(), ns2.getNamespaceURI(), "attribute",
            "true");

    writer.add(eventFactory.createStartElement(ns1.getPrefix(), ns1.getNamespaceURI(), "sample",
            Collections.singletonList(attribute).iterator(), namespaceList.iterator()));
    writer.add(eventFactory.createEndDocument());
    writer.flush();
}

From source file:edu.harvard.med.iccbl.dev.HibernateConsole.java

public static void main(String[] args) {
    BufferedReader br = null;//from  w  w  w. j  a  va  2s .  c  om
    try {
        CommandLineApplication app = new CommandLineApplication(args);
        app.processOptions(true, false);
        br = new BufferedReader(new InputStreamReader(System.in));

        EntityManagerFactory emf = (EntityManagerFactory) app.getSpringBean("entityManagerFactory");
        EntityManager em = emf.createEntityManager();

        do {
            System.out.println("Enter HQL query (blank to quit): ");
            String input = br.readLine();
            if (input.length() == 0) {
                System.out.println("Goodbye!");
                System.exit(0);
            }
            try {
                List list = ((Session) em.getDelegate()).createQuery(input).list(); // note: this uses the Hibernate Session object, to allow HQL (and JPQL)
                // List list = em.createQuery(input).getResultList();  // note: this JPA method supports JPQL

                System.out.println("Result:");
                for (Iterator iter = list.iterator(); iter.hasNext();) {
                    Object item = iter.next();
                    // format output from multi-item selects ("select a, b, c, ... from ...")
                    if (item instanceof Object[]) {
                        List<Object> fields = Arrays.asList((Object[]) item);
                        System.out.println(StringUtils.makeListString(fields, ", "));
                    }
                    // format output from single-item selected ("select a from ..." or "from ...")
                    else {
                        System.out.println("[" + item.getClass().getName() + "]: " + item);
                    }
                }
                System.out.println("(" + list.size() + " rows)\n");
            } catch (Exception e) {
                System.out.println("Hibernate Error: " + e.getMessage());
                log.error("Hibernate error", e);
            }
            System.out.println();
        } while (true);
    } catch (Exception e) {
        System.err.println("Fatal Error: " + e.getMessage());
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(br);
    }
}

From source file:de.micromata.tpsb.doc.StaticTestDocGenerator.java

public static void main(String[] args) {

    ParserConfig.Builder bCfg = new ParserConfig.Builder();
    ParserConfig.Builder tCfg = new ParserConfig.Builder();
    tCfg.generateIndividualFiles(true);/*from   w w  w .java 2  s.  c o m*/
    bCfg.generateIndividualFiles(true);
    List<String> la = Arrays.asList(args);
    Iterator<String> it = la.iterator();
    boolean baseDirSet = false;
    boolean ignoreLocalSettings = false;
    List<String> addRepos = new ArrayList<String>();
    StringResourceLoader.setRepository(StringResourceLoader.REPOSITORY_NAME_DEFAULT,
            new StringResourceRepositoryImpl());
    try {
        while (it.hasNext()) {
            String arg = it.next();
            String value = null;

            if ((value = getArgumentOption(it, arg, "--project-root", "-pr")) != null) {
                File f = new File(value);
                if (f.exists() == false) {
                    System.err.print("project root doesn't exists: " + f.getAbsolutePath());
                    continue;
                }
                TpsbEnvironment.get().addProjectRoots(f);
                File ts = new File(f, "src/test");
                if (ts.exists() == true) {
                    tCfg.addSourceFileRespository(new FileSystemSourceFileRepository(ts.getAbsolutePath()));
                    bCfg.addSourceFileRespository(new FileSystemSourceFileRepository(ts.getAbsolutePath()));
                }
                continue;
            }
            if ((value = getArgumentOption(it, arg, "--test-input", "-ti")) != null) {
                File f = new File(value);
                if (f.exists() == false) {
                    System.err.print("test-input doesn't exists: " + f.getAbsolutePath());
                }
                tCfg.addSourceFileRespository(new FileSystemSourceFileRepository(value));
                bCfg.addSourceFileRespository(new FileSystemSourceFileRepository(value));
                continue;
            }
            if ((value = getArgumentOption(it, arg, "--output-path", "-op")) != null) {
                if (baseDirSet == false) {
                    tCfg.outputDir(value);
                    bCfg.outputDir(value);
                    TpsbEnvironment.setBaseDir(value);
                    baseDirSet = true;
                } else {
                    addRepos.add(value);
                }
                continue;
            }
            if ((value = getArgumentOption(it, arg, "--index-vmtemplate", "-ivt")) != null) {
                try {
                    String content = FileUtils.readFileToString(new File(value), CharEncoding.UTF_8);
                    StringResourceRepository repo = StringResourceLoader.getRepository();
                    repo.putStringResource("customIndexTemplate", content, CharEncoding.UTF_8);
                    tCfg.indexTemplate("customIndexTemplate");
                } catch (IOException ex) {
                    throw new RuntimeException(
                            "Cannot load file " + new File(value).getAbsolutePath() + ": " + ex.getMessage(),
                            ex);
                }
                continue;
            }
            if ((value = getArgumentOption(it, arg, "--test-vmtemplate", "-tvt")) != null) {
                try {
                    String content = FileUtils.readFileToString(new File(value), CharEncoding.UTF_8);
                    StringResourceRepository repo = StringResourceLoader.getRepository();
                    repo.putStringResource("customTestTemplate", content, CharEncoding.UTF_8);
                    tCfg.testTemplate("customTestTemplate");
                } catch (IOException ex) {
                    throw new RuntimeException(
                            "Cannot load file " + new File(value).getAbsolutePath() + ": " + ex.getMessage(),
                            ex);
                }
                continue;
            }
            if (arg.equals("--singlexml") == true) {
                tCfg.generateIndividualFiles(false);
                bCfg.generateIndividualFiles(false);
            } else if (arg.equals("--ignore-local-settings") == true) {
                ignoreLocalSettings = true;
                continue;
            }
        }
    } catch (RuntimeException ex) {
        System.err.print(ex.getMessage());
        return;
    }
    if (ignoreLocalSettings == false) {
        readLocalSettings(bCfg, tCfg);
    }
    bCfg// .addSourceFileFilter(new MatcherSourceFileFilter("*Builder,*App,*builder")) //
            .addSourceFileFilter(new AnnotationSourceFileFilter(TpsbBuilder.class)) //
            .addSourceFileFilter(new AnnotationSourceFileFilter(TpsbApplication.class)) //
    ;
    tCfg// .addSourceFileFilter(new MatcherSourceFileFilter("*Test,*TestCase")) //
            .addSourceFileFilter(new AnnotationSourceFileFilter(TpsbTestSuite.class)) //
    ;

    StaticTestDocGenerator docGenerator = new StaticTestDocGenerator(bCfg.build(), tCfg.build());
    TpsbEnvironment env = TpsbEnvironment.get();
    if (addRepos.isEmpty() == false) {
        env.setIncludeRepos(addRepos);
    }
    docGenerator.parseTestBuilders();
    docGenerator.parseTestCases();
}

From source file:com.google.api.services.samples.youtube.cmdline.data.Topics.java

/**
 * Execute a search request that starts by calling the Freebase API to
 * retrieve a topic ID matching a user-provided term. Then initialize a
 * YouTube object to search for YouTube videos and call the YouTube Data
 * API's youtube.search.list method to retrieve a list of videos associated
 * with the selected Freebase topic and with another search query term,
 * which the user also enters. Finally, display the titles, video IDs, and
 * thumbnail images for the first five videos in the YouTube Data API
 * response.//www .  j a  v  a2  s .c om
 *
 * @param args This application does not use command line arguments.
 */
public static void main(String[] args) {
    // Read the developer key from the properties file.
    Properties properties = new Properties();
    try {
        InputStream in = Topics.class.getResourceAsStream("/" + PROPERTIES_FILENAME);
        properties.load(in);

    } catch (IOException e) {
        System.err.println("There was an error reading " + PROPERTIES_FILENAME + ": " + e.getCause() + " : "
                + e.getMessage());
        System.exit(1);
    }

    try {
        // Retrieve a Freebase topic ID based on a user-entered query term.
        String topicsId = getTopicId();
        if (topicsId.length() < 1) {
            System.out.println("No topic id will be applied to your search.");
        }

        // Prompt the user to enter a search query term. This term will be
        // used to retrieve YouTube search results related to the topic
        // selected above.
        String queryTerm = getInputQuery("search");

        // This object is used to make YouTube Data API requests. The last
        // argument is required, but since we don't need anything
        // initialized when the HttpRequest is initialized, we override
        // the interface and provide a no-op function.
        youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {
            public void initialize(HttpRequest request) throws IOException {
            }
        }).setApplicationName("youtube-cmdline-search-sample").build();

        YouTube.Search.List search = youtube.search().list("id,snippet");

        // Set your developer key from the {{ Google Cloud Console }} for
        // non-authenticated requests. See:
        // {{ https://cloud.google.com/console }}
        String apiKey = properties.getProperty("youtube.apikey");
        search.setKey(apiKey);
        search.setQ(queryTerm);
        if (topicsId.length() > 0) {
            search.setTopicId(topicsId);
        }

        // Restrict the search results to only include videos. See:
        // https://developers.google.com/youtube/v3/docs/search/list#type
        search.setType("video");

        // To increase efficiency, only retrieve the fields that the
        // application uses.
        search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)");
        search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);
        SearchListResponse searchResponse = search.execute();

        List<SearchResult> searchResultList = searchResponse.getItems();

        if (searchResultList != null) {
            prettyPrint(searchResultList.iterator(), queryTerm, topicsId);
        } else {
            System.out.println("There were no results for your query.");
        }
    } catch (GoogleJsonResponseException e) {
        System.err.println(
                "There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:com.google.api.services.samples.youtube.cmdline.Topics.java

/**
 * Execute a search request that starts by calling the Freebase API to
 * retrieve a topic ID matching a user-provided term. Then initialize a
 * YouTube object to search for YouTube videos and call the YouTube Data
 * API's youtube.search.list method to retrieve a list of videos associated
 * with the selected Freebase topic and with another search query term,
 * which the user also enters. Finally, display the titles, video IDs, and
 * thumbnail images for the first five videos in the YouTube Data API
 * response.//from ww  w .j  av a  2s  . com
 *
 * @param args This application does not use command line arguments.
 */
public static void main(String[] args) {
    // Read the developer key from the properties file.
    Properties properties = new Properties();
    try {
        InputStream in = Topics.class.getResourceAsStream("/" + PROPERTIES_FILENAME);
        properties.load(in);

    } catch (IOException e) {
        System.err.println("There was an error reading " + PROPERTIES_FILENAME + ": " + e.getCause() + " : "
                + e.getMessage());
        System.exit(1);
    }

    try {
        // Retrieve a Freebase topic ID based on a user-entered query term.
        String topicsId = getTopicId();
        if (topicsId.length() < 1) {
            System.out.println("No topic id will be applied to your search.");
        }

        // Prompt the user to enter a search query term. This term will be
        // used to retrieve YouTube search results related to the topic
        // selected above.
        String queryTerm = getInputQuery("search");

        // This object is used to make YouTube Data API requests. The last
        // argument is required, but since we don't need anything
        // initialized when the HttpRequest is initialized, we override
        // the interface and provide a no-op function.
        youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {
            public void initialize(HttpRequest request) throws IOException {
            }
        }).setApplicationName("youtube-cmdline-search-sample").build();

        YouTube.Search.List search = youtube.search().list("id,snippet");

        // Set your developer key from the Google Developers Console for
        // non-authenticated requests. See:
        // https://cloud.google.com/console
        String apiKey = properties.getProperty("youtube.apikey");
        search.setKey(apiKey);
        search.setQ(queryTerm);
        if (topicsId.length() > 0) {
            search.setTopicId(topicsId);
        }

        // Restrict the search results to only include videos. See:
        // https://developers.google.com/youtube/v3/docs/search/list#type
        search.setType("video");

        // To increase efficiency, only retrieve the fields that the
        // application uses.
        search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)");
        search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);
        SearchListResponse searchResponse = search.execute();

        List<SearchResult> searchResultList = searchResponse.getItems();

        if (searchResultList != null) {
            prettyPrint(searchResultList.iterator(), queryTerm, topicsId);
        } else {
            System.out.println("There were no results for your query.");
        }
    } catch (GoogleJsonResponseException e) {
        System.err.println(
                "There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:com.google.api.services.samples.youtube.cmdline.youtube_cmdline_topics_sample.Topics.java

/**
 * Method kicks off a search via the Freebase API for a topics id.  It initializes a YouTube
 * object to search for videos on YouTube (Youtube.Search.List) using that topics id to make the
 * search more specific.  The program then prints the names and thumbnails of each of the videos
 * (only first 5 videos).  Please note, user input is taken for both search on Freebase and on
 * YouTube./*from w  w  w .j a  v  a  2s .c om*/
 *
 * @param args command line args not used.
*/
public static void main(String[] args) {
    // Read the developer key from youtube.properties
    Properties properties = new Properties();
    try {
        InputStream in = Topics.class.getResourceAsStream("/" + PROPERTIES_FILENAME);
        properties.load(in);

    } catch (IOException e) {
        System.err.println("There was an error reading " + PROPERTIES_FILENAME + ": " + e.getCause() + " : "
                + e.getMessage());
        System.exit(1);
    }

    try {
        // Gets a topic id via the Freebase API based on user input.
        String topicsId = getTopicId();
        if (topicsId.length() < 1) {
            System.out.println("No topic id will be applied to your search.");
        }

        /*
         * Get query term from user.  The "search" parameter is just used as output to clarify that
         * we want a "search" term (vs. a "topics" term).
         */
        String queryTerm = getInputQuery("search");

        /*
         * The YouTube object is used to make all API requests.  The last argument is required, but
         * because we don't need anything initialized when the HttpRequest is initialized, we
         * override the interface and provide a no-op function.
         */
        youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, new HttpRequestInitializer() {
            public void initialize(HttpRequest request) throws IOException {
            }
        }).setApplicationName("youtube-cmdline-search-sample").build();

        YouTube.Search.List search = youtube.search().list("id,snippet");
        /*
         * It is important to set your developer key from the Google Developer Console for
         * non-authenticated requests (found under the API Access tab at this link:
         * code.google.com/apis/). This is good practice and increases your quota.
         */
        String apiKey = properties.getProperty("youtube.apikey");
        search.setKey(apiKey);
        search.setQ(queryTerm);
        if (topicsId.length() > 0) {
            search.setTopicId(topicsId);
        }

        /*
         * We are only searching for videos (not playlists or channels).  If we were searching for
         * more, we would add them as a string like this: "video,playlist,channel".
         */
        search.setType("video");
        /*
         * This method reduces the info returned to only the fields we need.  It makes things more
         * efficient, because we are transmitting less data.
         */
        search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)");
        search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);
        SearchListResponse searchResponse = search.execute();

        List<SearchResult> searchResultList = searchResponse.getItems();

        if (searchResultList != null) {
            prettyPrint(searchResultList.iterator(), queryTerm, topicsId);
        } else {
            System.out.println("There were no results for your query.");
        }
    } catch (GoogleJsonResponseException e) {
        System.err.println(
                "There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
        e.printStackTrace();
    }
}