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:main.java.com.google.api.services.samples.youtube.cmdline.YouTubeSample.java

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

    Properties properties = new Properties();
    try {//  w w w.  ja  va  2 s. c  o  m
        InputStream in = YouTubeSample.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);
    }

    youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, new HttpRequestInitializer() {

        @Override
        public void initialize(HttpRequest arg0) throws IOException {
            // TODO Auto-generated method stub

        }
    }).setApplicationName("youtubeTest").build();

    YouTube.Videos.List videos = youtube.videos().list("snippet");

    String apiKey = properties.getProperty("youtube.apikey");
    videos.setKey(apiKey);
    videos.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);
    videos.setChart("mostPopular");

    VideoListResponse response = videos.execute();

    java.util.List<Video> videoList = response.getItems();

    if (videoList != null) {
        prettyPrint(videoList.iterator());
    } else {
        System.out.println("There were  no results!");
    }

}

From source file:SafeCollectionIteration.java

public static void main(String[] args) {
    List wordList = Collections.synchronizedList(new ArrayList());

    wordList.add("Iterators");
    wordList.add("require");
    wordList.add("special");
    wordList.add("handling");

    synchronized (wordList) {
        Iterator iter = wordList.iterator();
        while (iter.hasNext()) {
            String s = (String) iter.next();
            System.out.println("found string: " + s + ", length=" + s.length());
        }// w  w  w . ja  v a  2s  . c  o  m
    }
}

From source file:Main.java

public static void main(String args[]) {

    List<String[]> left = new ArrayList<String[]>();
    left.add(new String[] { "one", "two" });

    List<String[]> right = new ArrayList<String[]>();
    right.add(new String[] { "one", "two" });

    java.util.Iterator<String[]> leftIterator = left.iterator();
    java.util.Iterator<String[]> rightIterator = right.iterator();
    if (left.size() != right.size()) {
        System.out.println("not equal");
    }/*from  w ww  .j  a v a2  s . c  om*/
    while (leftIterator.hasNext()) {
        if (Arrays.equals(leftIterator.next(), rightIterator.next()))
            continue;
        else {
            System.out.print("not equal");
            break;
        }
    }
}

From source file:com.hp.avmon.snmp.discover.SLPClient.java

/**
 * Test method.//from ww w  .java2 s.c o m
 * 
 * @param args
 *            Ignored
 */
public static void main(String[] args) {

    SLPClient client = new SLPClient();
    List<String> wbemservices = client.findWbemServices();

    Iterator<String> serviceIterator = wbemservices.iterator();
    while (serviceIterator.hasNext()) {
        String url = serviceIterator.next().toString();
        System.out.println(url);
        logger.debug(url);
        List<String> attributes = client.findAttributes(url, SCOPE, new Vector<String>());

        Iterator<String> attributeIterator = attributes.iterator();
        while (attributeIterator.hasNext()) {
            System.out.println(attributeIterator.next());
            logger.debug(attributeIterator.next());
        }
    }

}

From source file:Main.java

public static void main(final String[] args) throws Exception {
    Random RND = new Random();
    ExecutorService es = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    List<Future<String>> results = new ArrayList<>(10);
    for (int i = 0; i < 10; i++) {
        results.add(es.submit(new TimeSliceTask(RND.nextInt(10), TimeUnit.SECONDS)));
    }//from w w  w .  j  a  v  a  2 s . c o m
    es.shutdown();
    while (!results.isEmpty()) {
        Iterator<Future<String>> i = results.iterator();
        while (i.hasNext()) {
            Future<String> f = i.next();
            if (f.isDone()) {
                System.out.println(f.get());
                i.remove();
            }
        }
    }
}

From source file:in.sc.main.ABC.java

public static void main(String[] args) {
    List list = new ArrayList();
    list.add("1");
    list.add("2");
    list.add("3");
    Collections.reverse(list);//from  www . j a v  a 2s  . c om
    list.iterator();
    for (Object obj : reverse(list)) {
        System.out.print(obj + ", ");
    }

    D x = (D) new D();
    if (x instanceof I) {
        System.out.println("I");
    }
    if (x instanceof J) {
        System.out.println("J");
    }
    if (x instanceof C) {
        System.out.println("C");
    }
    if (x instanceof D) {
        System.out.println("D");
    }
    xyz x1 = new xyz("Test");
    int x2 = 111;

    Rank abc = Rank.FIRST;
    System.out.println("" + abc.SECOND);
    final int j = 2;
    switch (x2) {
    case 1:
        System.out.println("1");
        break;
    case 10:
        System.out.println("10");
        break;
    case j:
        System.out.println("2");
        break;
    case 5:
        System.out.println("5");
        break;
    default:
        System.out.println("Default");
        break;
    }
    String str1 = "lower", str2 = "LOWER", str3 = "UPPER";
    str1.toUpperCase();
    str1.replace("LOWER", "UPPER");
    System.out
            .println((str1.equals(str2)) + " " + (str1.equals(str3)) + "  " + str1 + "  " + str2 + "  " + str3);
    for (int i = 0; i < 3; i++) {
        System.out.println("" + i);
        switch (i) {
        case 0:
            break;
        case 1:
            System.out.println("one");
        case 2:
            System.out.println("two");
        case 3:
            System.out.println("three");
        }
    }
    System.out.println("done");
    ABC a = new ABC("a", "b");
    ABC b = new ABC(a);
}

From source file:LinkedListTest.java

public static void main(String[] args) {
    List<String> a = new LinkedList<String>();
    a.add("Amy");
    a.add("Carl");
    a.add("Erica");

    List<String> b = new LinkedList<String>();
    b.add("Bob");
    b.add("Doug");
    b.add("Frances");
    b.add("Gloria");

    // merge the words from b into a

    ListIterator<String> aIter = a.listIterator();
    Iterator<String> bIter = b.iterator();

    while (bIter.hasNext()) {
        if (aIter.hasNext())
            aIter.next();//from   ww w  . j  av a2s.  co m
        aIter.add(bIter.next());
    }

    System.out.println(a);

    // remove every second word from b

    bIter = b.iterator();
    while (bIter.hasNext()) {
        bIter.next(); // skip one element
        if (bIter.hasNext()) {
            bIter.next(); // skip next element
            bIter.remove(); // remove that element
        }
    }

    System.out.println(b);

    // bulk operation: remove all words in b from a

    a.removeAll(b);

    System.out.println(a);
}

From source file:com.cloud.test.longrun.PerformanceWithAPI.java

public static void main(String[] args) {

    List<String> argsList = Arrays.asList(args);
    Iterator<String> iter = argsList.iterator();
    String host = "http://localhost";
    int numThreads = 1;

    while (iter.hasNext()) {
        String arg = iter.next();
        if (arg.equals("-h")) {
            host = "http://" + iter.next();
        }//from w w  w. j a v a  2 s . c  o m
        if (arg.equals("-t")) {
            numThreads = Integer.parseInt(iter.next());
        }
        if (arg.equals("-n")) {
            numVM = Integer.parseInt(iter.next());
        }
    }

    final String server = host + ":" + _apiPort + "/";
    final String developerServer = host + ":" + _developerPort + _apiUrl;

    s_logger.info("Starting test in " + numThreads + " thread(s). Each thread is launching " + numVM + " VMs");

    for (int i = 0; i < numThreads; i++) {
        new Thread(new Runnable() {
            public void run() {
                try {

                    String username = null;
                    String singlePrivateIp = null;
                    String singlePublicIp = null;
                    Random ran = new Random();
                    username = Math.abs(ran.nextInt()) + "-user";

                    //Create User
                    User myUser = new User(username, username, server, developerServer);
                    try {
                        myUser.launchUser();
                        myUser.registerUser();
                    } catch (Exception e) {
                        s_logger.warn("Error code: ", e);
                    }

                    if (myUser.getUserId() != null) {
                        s_logger.info("User " + myUser.getUserName()
                                + " was created successfully, starting VM creation");
                        //create VMs for the user
                        for (int i = 0; i < numVM; i++) {
                            //Create a new VM, add it to the list of user's VMs
                            VirtualMachine myVM = new VirtualMachine(myUser.getUserId());
                            myVM.deployVM(_zoneId, _serviceOfferingId, _templateId, myUser.getDeveloperServer(),
                                    myUser.getApiKey(), myUser.getSecretKey());
                            myUser.getVirtualMachines().add(myVM);
                            singlePrivateIp = myVM.getPrivateIp();

                            if (singlePrivateIp != null) {
                                s_logger.info(
                                        "VM with private Ip " + singlePrivateIp + " was successfully created");
                            } else {
                                s_logger.info("Problems with VM creation for a user" + myUser.getUserName());
                                break;
                            }

                            //get public IP address for the User            
                            myUser.retrievePublicIp(_zoneId);
                            singlePublicIp = myUser.getPublicIp().get(myUser.getPublicIp().size() - 1);
                            if (singlePublicIp != null) {
                                s_logger.info("Successfully got public Ip " + singlePublicIp + " for user "
                                        + myUser.getUserName());
                            } else {
                                s_logger.info("Problems with getting public Ip address for user"
                                        + myUser.getUserName());
                                break;
                            }

                            //create ForwardProxy rules for user's VMs
                            int responseCode = CreateForwardingRule(myUser, singlePrivateIp, singlePublicIp,
                                    "22", "22");
                            if (responseCode == 500)
                                break;
                        }

                        s_logger.info("Deployment successful..." + numVM
                                + " VMs were created. Waiting for 5 min before performance test");
                        Thread.sleep(300000L); // Wait 

                        //Start performance test for the user
                        s_logger.info("Starting performance test for Guest network that has "
                                + myUser.getPublicIp().size() + " public IP addresses");
                        for (int j = 0; j < myUser.getPublicIp().size(); j++) {
                            s_logger.info("Starting test for user which has "
                                    + myUser.getVirtualMachines().size() + " vms. Public IP for the user is "
                                    + myUser.getPublicIp().get(j) + " , number of retries is " + _retry
                                    + " , private IP address of the machine is"
                                    + myUser.getVirtualMachines().get(j).getPrivateIp());
                            guestNetwork myNetwork = new guestNetwork(myUser.getPublicIp().get(j), _retry);
                            myNetwork.setVirtualMachines(myUser.getVirtualMachines());
                            new Thread(myNetwork).start();
                        }

                    }
                } catch (Exception e) {
                    s_logger.error(e);
                }
            }
        }).start();

    }
}

From source file:com.cloud.test.utils.SubmitCert.java

public static void main(String[] args) {
    // Parameters
    List<String> argsList = Arrays.asList(args);
    Iterator<String> iter = argsList.iterator();
    while (iter.hasNext()) {
        String arg = iter.next();

        if (arg.equals("-c")) {
            certFileName = iter.next();/*w  w w . ja va2  s.  c  o m*/
        }

        if (arg.equals("-s")) {
            secretKey = iter.next();
        }

        if (arg.equals("-a")) {
            apiKey = iter.next();
        }

        if (arg.equals("-action")) {
            url = "Action=" + iter.next();
        }
    }

    Properties prop = new Properties();
    try {
        prop.load(new FileInputStream("conf/tool.properties"));
    } catch (IOException ex) {
        s_logger.error("Error reading from conf/tool.properties", ex);
        System.exit(2);
    }

    host = prop.getProperty("host");
    port = prop.getProperty("port");

    if (url.equals("Action=SetCertificate") && certFileName == null) {
        s_logger.error("Please set path to certificate (including file name) with -c option");
        System.exit(1);
    }

    if (secretKey == null) {
        s_logger.error("Please set secretkey  with -s option");
        System.exit(1);
    }

    if (apiKey == null) {
        s_logger.error("Please set apikey with -a option");
        System.exit(1);
    }

    if (host == null) {
        s_logger.error("Please set host in tool.properties file");
        System.exit(1);
    }

    if (port == null) {
        s_logger.error("Please set port in tool.properties file");
        System.exit(1);
    }

    TreeMap<String, String> param = new TreeMap<String, String>();

    String req = "GET\n" + host + ":" + prop.getProperty("port") + "\n/" + prop.getProperty("accesspoint")
            + "\n";
    String temp = "";

    if (certFileName != null) {
        cert = readCert(certFileName);
        param.put("cert", cert);
    }

    param.put("AWSAccessKeyId", apiKey);
    param.put("Expires", prop.getProperty("expires"));
    param.put("SignatureMethod", prop.getProperty("signaturemethod"));
    param.put("SignatureVersion", "2");
    param.put("Version", prop.getProperty("version"));

    StringTokenizer str1 = new StringTokenizer(url, "&");
    while (str1.hasMoreTokens()) {
        String newEl = str1.nextToken();
        StringTokenizer str2 = new StringTokenizer(newEl, "=");
        String name = str2.nextToken();
        String value = str2.nextToken();
        param.put(name, value);
    }

    //sort url hash map by key
    Set c = param.entrySet();
    Iterator it = c.iterator();
    while (it.hasNext()) {
        Map.Entry me = (Map.Entry) it.next();
        String key = (String) me.getKey();
        String value = (String) me.getValue();
        try {
            temp = temp + key + "=" + URLEncoder.encode(value, "UTF-8") + "&";
        } catch (Exception ex) {
            s_logger.error("Unable to set parameter " + value + " for the command " + param.get("command"), ex);
        }

    }
    temp = temp.substring(0, temp.length() - 1);
    String requestToSign = req + temp;
    String signature = UtilsForTest.signRequest(requestToSign, secretKey);
    String encodedSignature = "";
    try {
        encodedSignature = URLEncoder.encode(signature, "UTF-8");
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    String url = "http://" + host + ":" + prop.getProperty("port") + "/" + prop.getProperty("accesspoint") + "?"
            + temp + "&Signature=" + encodedSignature;
    s_logger.info("Sending request with url:  " + url + "\n");
    sendRequest(url);
}

From source file:net.wedjaa.elasticparser.tester.ESSearchTester.java

public static void main(String[] args) {

    System.out.println("ES Search Testing started.");

    System.out.println("Starting local node...");

    Settings nodeSettings = ImmutableSettings.settingsBuilder().put("transport.tcp.port", "9600-9700")
            .put("http.port", "9500").put("http.max_content_length", "104857600").build();

    Node node = NodeBuilder.nodeBuilder().settings(nodeSettings).clusterName("elasticparser.unittest").node();

    node.start();//from w  w  w .  j  a  v  a  2s .  co m

    // Populate our test index
    System.out.println("Preparing Unit Test Index - this may take a while...");
    populateTest();

    try {
        System.out.println("...OK - Executing query!");
        // Try our searches
        ESSearch search = new ESSearch(null, null, ESSearch.ES_MODE_AGGS, "localhost", 9600,
                "elasticparser.unittest");
        search.search(getQuery("test-aggs.json"));
        Map<String, Object> hit = null;
        while ((hit = search.next()) != null) {
            System.out.println("Hit: {");
            for (String key : hit.keySet()) {
                System.out.println("  " + key + ": " + hit.get(key));
            }
            System.out.println("};");
        }
        search.close();
        Map<String, Class<?>> fields = search.getFields(getQuery("test-aggs.json"));
        List<String> sortedKeys = new ArrayList<String>(fields.keySet());
        Collections.sort(sortedKeys);
        Iterator<String> sortedKeyIter = sortedKeys.iterator();
        while (sortedKeyIter.hasNext()) {
            String fieldname = sortedKeyIter.next();
            System.out.println(" --> " + fieldname + "[" + fields.get(fieldname).getCanonicalName() + "]");
        }

    } catch (Exception ex) {
        System.out.println("Exception: " + ex);
    } finally {
        System.out.println("Stopping Test Node");
        node.stop();
    }
}