Example usage for java.util Iterator next

List of usage examples for java.util Iterator next

Introduction

In this page you can find the example usage for java.util Iterator next.

Prototype

E next();

Source Link

Document

Returns the next element in the iteration.

Usage

From source file:akori.Impact.java

static public void main(String[] args) throws IOException {
    String PATH = "E:\\Trabajos\\AKORI\\datosmatrizgino\\";
    String PATHIMG = "E:\\NetBeansProjects\\AKORI\\Proccess_1\\ImagesPages\\";
    for (int i = 1; i <= 32; ++i) {
        for (int k = 1; k <= 15; ++k) {
            System.out.println("Matrix " + i + "-" + k);
            BufferedImage img = null;
            try {
                img = ImageIO.read(new File(PATHIMG + i + ".png"));
            } catch (IOException ex) {
                ex.getStackTrace();/*www  .  ja  v  a2  s  .c  o m*/
            }

            int ymax = img.getHeight();
            int xmax = img.getWidth();

            double[][] imagen = new double[ymax][xmax];

            BufferedReader in = null;
            try {
                in = new BufferedReader(new FileReader(PATH + i + "-" + k + ".txt"));
            } catch (FileNotFoundException ex) {
                ex.getStackTrace();
            }

            String linea;
            ArrayList<String> lista = new ArrayList<String>();
            HashMap<String, String> lista1 = new HashMap<String, String>();
            try {
                for (int j = 0; (linea = in.readLine()) != null; ++j) {
                    String[] datos = linea.split(",");
                    int x = (int) Double.parseDouble(datos[1]);
                    int y = (int) Double.parseDouble(datos[2]);
                    if (x >= xmax || y >= ymax || x <= 0 || y <= 0) {
                        continue;
                    }
                    lista.add(x + "," + y);
                }
            } catch (Exception ex) {
                ex.getStackTrace();
            }

            try {
                in.close();
            } catch (IOException ex) {
                ex.getStackTrace();
            }

            Iterator iter = lista.iterator();
            int[][] matrix = new int[lista.size()][2];

            for (int j = 0; iter.hasNext(); ++j) {
                String xy = (String) iter.next();
                String[] datos = xy.split(",");
                matrix[j][0] = Integer.parseInt(datos[0]);
                matrix[j][1] = Integer.parseInt(datos[1]);
            }

            for (int j = 0; j < matrix.length; ++j) {

                int std = 50;
                int x = matrix[j][0];
                int y = matrix[j][1];
                imagen[y][x] += 1;
                double aux;
                normalMatrix(imagen, y, x, std);

            }

            FileWriter fw = new FileWriter(PATH + "Matrix" + i + "-" + k + ".txt");
            BufferedWriter bw = new BufferedWriter(fw);
            for (int j = 0; j < imagen.length; ++j) {
                for (int t = 0; t < imagen[j].length; ++t) {
                    if (t + 1 == imagen[j].length)
                        bw.write(imagen[j][t] + "");
                    else
                        bw.write(imagen[j][t] + ",");
                }
                bw.write("\n");
            }
            bw.close();
        }
    }
}

From source file:edu.umd.cloud9.example.bigram.AnalyzeBigramRelativeFrequencyTuple.java

@SuppressWarnings({ "static-access" })
public static void main(String[] args) throws Exception {
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input path").create(INPUT));

    CommandLine cmdline = null;//from   ww w .j  a v a2  s  .  c  o  m
    CommandLineParser parser = new GnuParser();

    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(INPUT)) {
        System.out.println("args: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(120);
        formatter.printHelp(AnalyzeBigramRelativeFrequencyJson.class.getName(), options);
        ToolRunner.printGenericCommandUsage(System.out);
        System.exit(-1);
    }

    String inputPath = cmdline.getOptionValue(INPUT);
    System.out.println("input path: " + inputPath);

    List<PairOfWritables<Tuple, FloatWritable>> pairs = SequenceFileUtils.readDirectory(new Path(inputPath));

    List<PairOfWritables<Tuple, FloatWritable>> list1 = Lists.newArrayList();
    List<PairOfWritables<Tuple, FloatWritable>> list2 = Lists.newArrayList();

    for (PairOfWritables<Tuple, FloatWritable> p : pairs) {
        Tuple bigram = p.getLeftElement();

        if (bigram.get(0).equals("light")) {
            list1.add(p);
        }

        if (bigram.get(0).equals("contain")) {
            list2.add(p);
        }
    }

    Collections.sort(list1, new Comparator<PairOfWritables<Tuple, FloatWritable>>() {
        @SuppressWarnings("unchecked")
        public int compare(PairOfWritables<Tuple, FloatWritable> e1, PairOfWritables<Tuple, FloatWritable> e2) {
            if (e1.getRightElement().compareTo(e2.getRightElement()) == 0) {
                return e1.getLeftElement().compareTo(e2.getLeftElement());
            }

            return e2.getRightElement().compareTo(e1.getRightElement());
        }
    });

    Iterator<PairOfWritables<Tuple, FloatWritable>> iter1 = Iterators.limit(list1.iterator(), 10);
    while (iter1.hasNext()) {
        PairOfWritables<Tuple, FloatWritable> p = iter1.next();
        Tuple bigram = p.getLeftElement();
        System.out.println(bigram + "\t" + p.getRightElement());
    }

    Collections.sort(list2, new Comparator<PairOfWritables<Tuple, FloatWritable>>() {
        @SuppressWarnings("unchecked")
        public int compare(PairOfWritables<Tuple, FloatWritable> e1, PairOfWritables<Tuple, FloatWritable> e2) {
            if (e1.getRightElement().compareTo(e2.getRightElement()) == 0) {
                return e1.getLeftElement().compareTo(e2.getLeftElement());
            }

            return e2.getRightElement().compareTo(e1.getRightElement());
        }
    });

    Iterator<PairOfWritables<Tuple, FloatWritable>> iter2 = Iterators.limit(list2.iterator(), 10);
    while (iter2.hasNext()) {
        PairOfWritables<Tuple, FloatWritable> p = iter2.next();
        Tuple bigram = p.getLeftElement();
        System.out.println(bigram + "\t" + p.getRightElement());
    }
}

From source file:MyMap.java

public static void main(String[] argv) {

    // Construct and load the hash. This simulates loading a
    // database or reading from a file, or wherever the data is.

    Map map = new MyMap();

    // The hash maps from company name to address.
    // In real life this might map to an Address object...
    map.put("Adobe", "Mountain View, CA");
    map.put("Learning Tree", "Los Angeles, CA");
    map.put("IBM", "White Plains, NY");
    map.put("Netscape", "Mountain View, CA");
    map.put("Microsoft", "Redmond, WA");
    map.put("Sun", "Mountain View, CA");
    map.put("O'Reilly", "Sebastopol, CA");

    // Two versions of the "retrieval" phase.
    // Version 1: get one pair's value given its key
    // (presumably the key would really come from user input):
    String queryString = "O'Reilly";
    System.out.println("You asked about " + queryString + ".");
    String resultString = (String) map.get(queryString);
    System.out.println("They are located in: " + resultString);
    System.out.println();/*from w w  w .  ja v a 2  s  . c o m*/

    // Version 2: get ALL the keys and pairs 
    // (maybe to print a report, or to save to disk)
    Iterator k = map.keySet().iterator();
    while (k.hasNext()) {
        String key = (String) k.next();
        System.out.println("Key " + key + "; Value " + (String) map.get(key));
    }

    // Step 3 - try out the entrySet() method.
    Set es = map.entrySet();
    System.out.println("entrySet() returns " + es.size() + " Map.Entry's");
}

From source file:com.github.xbn.examples.io.non_xbn.ReadInActiveAccountsFromFile.java

public static final void main(String[] rqdInputPathInStrArray) {
    //Read command-line
    String sSrc = null;//from w w  w.  j  a va 2 s  . c o  m
    try {
        sSrc = rqdInputPathInStrArray[0];
    } catch (IndexOutOfBoundsException ibx) {
        System.out.println("Missing one-and-only required parameter: The full path to Java source-code file.");
        return;
    }

    //Open input file
    File inputFile = new File(sSrc);
    Iterator<String> lineItr = null;
    try {
        lineItr = FileUtils.lineIterator(inputFile);
    } catch (IOException iox) {
        System.out.println("Cannot open \"" + sSrc + "\". " + iox);
        return;
    }

    while (lineItr.hasNext()) {
        String line = lineItr.next();
        String[] userPassIsActive = line.split(" ");
        String username = userPassIsActive[0];
        String password = userPassIsActive[1];
        boolean isActive = Boolean.parseBoolean(userPassIsActive[2]);

        System.out.println("username=" + username + ", password=" + password + ", isActive=" + isActive + "");
    }
}

From source file:com.github.xbn.examples.io.non_xbn.SudokuTxtFileDataXmpl.java

public static final void main(String[] as_1RqdPathToInput) {
    //Read command-line
    String sSrc = null;// w  w w.j  a va2 s  .  com
    try {
        sSrc = as_1RqdPathToInput[0];
    } catch (IndexOutOfBoundsException ibx) {
        System.out.println("Missing one-and-only required parameter: The full path to Java source-code file.");
        return;
    }

    //Open input file
    File fSrc = new File(sSrc);
    Iterator<String> li = null;
    try {
        li = FileUtils.lineIterator(fSrc);
    } catch (IOException iox) {
        System.out.println("Cannot open \"" + sSrc + "\". " + iox);
        return;
    }

    String[] asNineElementsRow1 = getAndOutputDataRow(li.next());
    String[] asNineElementsRow2 = getAndOutputDataRow(li.next());
    String[] asNineElementsRow3 = getAndOutputDataRow(li.next());

    li.next(); //blank line
    System.out.println("-----------------------");

    String[] asNineElementsRow4 = getAndOutputDataRow(li.next());
    String[] asNineElementsRow5 = getAndOutputDataRow(li.next());
    String[] asNineElementsRow6 = getAndOutputDataRow(li.next());

    li.next(); //blank line
    System.out.println("-----------------------");

    String[] asNineElementsRow7 = getAndOutputDataRow(li.next());
    String[] asNineElementsRow8 = getAndOutputDataRow(li.next());
    String[] asNineElementsRow9 = getAndOutputDataRow(li.next());

}

From source file:edu.umd.cloud9.example.bigram.AnalyzeBigramRelativeFrequency.java

@SuppressWarnings({ "static-access" })
public static void main(String[] args) {
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input path").create(INPUT));

    CommandLine cmdline = null;/*from ww w .j a va2 s  . c  o  m*/
    CommandLineParser parser = new GnuParser();

    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(INPUT)) {
        System.out.println("args: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(120);
        formatter.printHelp(AnalyzeBigramRelativeFrequency.class.getName(), options);
        ToolRunner.printGenericCommandUsage(System.out);
        System.exit(-1);
    }

    String inputPath = cmdline.getOptionValue(INPUT);
    System.out.println("input path: " + inputPath);

    List<PairOfWritables<PairOfStrings, FloatWritable>> pairs = SequenceFileUtils
            .readDirectory(new Path(inputPath));

    List<PairOfWritables<PairOfStrings, FloatWritable>> list1 = Lists.newArrayList();
    List<PairOfWritables<PairOfStrings, FloatWritable>> list2 = Lists.newArrayList();

    for (PairOfWritables<PairOfStrings, FloatWritable> p : pairs) {
        PairOfStrings bigram = p.getLeftElement();

        if (bigram.getLeftElement().equals("light")) {
            list1.add(p);
        }
        if (bigram.getLeftElement().equals("contain")) {
            list2.add(p);
        }
    }

    Collections.sort(list1, new Comparator<PairOfWritables<PairOfStrings, FloatWritable>>() {
        public int compare(PairOfWritables<PairOfStrings, FloatWritable> e1,
                PairOfWritables<PairOfStrings, FloatWritable> e2) {
            if (e1.getRightElement().compareTo(e2.getRightElement()) == 0) {
                return e1.getLeftElement().compareTo(e2.getLeftElement());
            }

            return e2.getRightElement().compareTo(e1.getRightElement());
        }
    });

    Iterator<PairOfWritables<PairOfStrings, FloatWritable>> iter1 = Iterators.limit(list1.iterator(), 10);
    while (iter1.hasNext()) {
        PairOfWritables<PairOfStrings, FloatWritable> p = iter1.next();
        PairOfStrings bigram = p.getLeftElement();
        System.out.println(bigram + "\t" + p.getRightElement());
    }

    Collections.sort(list2, new Comparator<PairOfWritables<PairOfStrings, FloatWritable>>() {
        public int compare(PairOfWritables<PairOfStrings, FloatWritable> e1,
                PairOfWritables<PairOfStrings, FloatWritable> e2) {
            if (e1.getRightElement().compareTo(e2.getRightElement()) == 0) {
                return e1.getLeftElement().compareTo(e2.getLeftElement());
            }

            return e2.getRightElement().compareTo(e1.getRightElement());
        }
    });

    Iterator<PairOfWritables<PairOfStrings, FloatWritable>> iter2 = Iterators.limit(list2.iterator(), 10);
    while (iter2.hasNext()) {
        PairOfWritables<PairOfStrings, FloatWritable> p = iter2.next();
        PairOfStrings bigram = p.getLeftElement();
        System.out.println(bigram + "\t" + p.getRightElement());
    }
}

From source file:com.hsbc.frc.SevenHero.ClientProxyAuthentication.java

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

    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {//  ww w.ja  v a  2 s .com
        httpclient.getCredentialsProvider().setCredentials(new AuthScope("133.13.162.149", 8080),
                new UsernamePasswordCredentials("43668069", "wf^O^2013"));

        HttpHost targetHost = new HttpHost("pt.3g.qq.com");
        HttpHost proxy = new HttpHost("133.13.162.149", 8080);

        BasicClientCookie netscapeCookie = null;

        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        // httpclient.getCookieStore().addCookie(netscapeCookie);
        httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

        HttpGet httpget = new HttpGet("/");
        httpget.addHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");

        System.out.println("executing request: " + httpget.getRequestLine());
        System.out.println("via proxy: " + proxy);
        System.out.println("to target: " + targetHost);

        HttpResponse response = httpclient.execute(targetHost, httpget);

        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());

        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        InputStream is = entity.getContent();
        StringBuffer sb = new StringBuffer(200);
        byte data[] = new byte[65536];
        int n = 1;
        do {
            n = is.read(data);
            if (n > 0) {
                sb.append(new String(data));
            }
        } while (n > 0);

        // System.out.println(sb);
        EntityUtils.consume(entity);

        System.out.println("----------------------------------------");
        Header[] headerlist = response.getAllHeaders();
        for (int i = 0; i < headerlist.length; i++) {
            Header header = headerlist[i];
            if (header.getName().equals("Set-Cookie")) {
                String setCookie = header.getValue();
                String cookies[] = setCookie.split(";");
                for (int j = 0; j < cookies.length; j++) {
                    String cookie[] = cookies[j].split("=");
                    CookieManager.cookie.put(cookie[0], cookie[1]);
                }
            }
            System.out.println(header.getName() + ":" + header.getValue());
        }
        String sid = getSid(sb.toString(), "&");
        System.out.println("sid: " + sid);

        httpclient = new DefaultHttpClient();
        httpclient.getCredentialsProvider().setCredentials(new AuthScope("133.13.162.149", 8080),
                new UsernamePasswordCredentials("43668069", "wf^O^2013"));
        String url = Constant.openUrl + "&" + sid;
        targetHost = new HttpHost(url);

        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        httpget = new HttpGet("/");
        httpget.addHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");
        Iterator it = CookieManager.cookie.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            Object key = entry.getKey();
            Object value = entry.getValue();
            netscapeCookie = new BasicClientCookie((String) (key), (String) (value));
            netscapeCookie.setVersion(0);
            netscapeCookie.setDomain(".qq.com");
            netscapeCookie.setPath("/");
            // httpclient.getCookieStore().addCookie(netscapeCookie);
        }

        response = httpclient.execute(targetHost, httpget);

    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:edu.gslis.ts.ChunkToFile.java

public static void main(String[] args) {
    try {//from w  ww .  ja v a 2s .c o  m
        // Get the commandline options
        Options options = createOptions();
        CommandLineParser parser = new GnuParser();
        CommandLine cmd = parser.parse(options, args);

        String inputPath = cmd.getOptionValue("input");
        String indexPath = cmd.getOptionValue("index");
        String eventsPath = cmd.getOptionValue("events");
        String stopPath = cmd.getOptionValue("stop");
        String outputPath = cmd.getOptionValue("output");

        IndexWrapper index = IndexWrapperFactory.getIndexWrapper(indexPath);
        Stopper stopper = new Stopper(stopPath);
        Map<Integer, FeatureVector> queries = readEvents(eventsPath, stopper);

        // Setup the filter
        ChunkToFile f = new ChunkToFile();
        if (inputPath != null) {
            File infile = new File(inputPath);
            if (infile.isDirectory()) {
                Iterator<File> files = FileUtils.iterateFiles(infile, null, true);

                while (files.hasNext()) {
                    File file = files.next();
                    System.err.println(file.getAbsolutePath());
                    f.filter(file, queries, index, stopper, outputPath);
                }
            } else
                System.err.println(infile.getAbsolutePath());
            f.filter(infile, queries, index, stopper, outputPath);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

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();//from  ww  w .  j  a va  2  s .co 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:com.github.xbn.examples.io.non_xbn.DelimitWordsInATextFile.java

public static final void main(String[] as_1RqdPathToInput) {
    //Read command-line
    String sSrc = null;/* w  w w.  j a va2s .  co  m*/
    try {
        sSrc = as_1RqdPathToInput[0];
    } catch (IndexOutOfBoundsException ibx) {
        System.out.println("Missing one-and-only required parameter: The full path to input file.");
        return;
    }

    //Open input file
    File fSrc = new File(sSrc);
    Iterator<String> lineItr = null;
    try {
        lineItr = FileUtils.lineIterator(fSrc);
    } catch (IOException iox) {
        System.out.println("Cannot open \"" + sSrc + "\". " + iox);
        return;
    }

    int i = 0;
    while (lineItr.hasNext()) {
        i++;
        String as[] = lineItr.next().split(" ");
        System.out.println("Line " + i + ": " + Arrays.toString(as));
    }
}