Example usage for java.io LineNumberReader LineNumberReader

List of usage examples for java.io LineNumberReader LineNumberReader

Introduction

In this page you can find the example usage for java.io LineNumberReader LineNumberReader.

Prototype

public LineNumberReader(Reader in) 

Source Link

Document

Create a new line-numbering reader, using the default input-buffer size.

Usage

From source file:io.fabric8.ConnectorMojo.java

private List<String> loadFile(File file) throws Exception {
    List<String> lines = new ArrayList<>();
    LineNumberReader reader = new LineNumberReader(new FileReader(file));

    String line;// w  ww . ja  v  a  2s . c  om
    do {
        line = reader.readLine();
        if (line != null) {
            lines.add(line);
        }
    } while (line != null);
    reader.close();

    return lines;
}

From source file:org.fuin.esmp.AbstractEventStoreMojo.java

/**
 * Returns the string as list.//from www  .  j  ava2  s . com
 * 
 * @param str
 *            String to split into lines.
 * 
 * @return List of lines.
 * 
 * @throws MojoExecutionException
 *             Error splitting the string into lines.
 */
protected final List<String> asList(final String str) throws MojoExecutionException {
    try {
        final List<String> lines = new ArrayList<String>();
        final LineNumberReader reader = new LineNumberReader(new StringReader(str));
        String line;
        while ((line = reader.readLine()) != null) {
            lines.add(line);
        }
        return lines;
    } catch (final IOException ex) {
        throw new MojoExecutionException("Error creating string list", ex);
    }
}

From source file:org.apache.zookeeper.server.quorum.QuorumPeerMainTest.java

/**
 * This test validates that if a quorum member determines that it is leader without the support of the rest of the
 * quorum (the other members do not believe it to be the leader) it will stop attempting to lead and become a follower.
 *
 * @throws IOException// w  w w  . j  a  va2  s  . c o m
 * @throws InterruptedException
 */
@Test
public void testElectionFraud() throws IOException, InterruptedException {
    // capture QuorumPeer logging
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    WriterAppender appender = getConsoleAppender(os, Level.INFO);
    Logger qlogger = Logger.getLogger(QuorumPeer.class);
    qlogger.addAppender(appender);

    numServers = 3;

    // used for assertions later
    boolean foundLeading = false;
    boolean foundLooking = false;
    boolean foundFollowing = false;

    try {
        // spin up a quorum, we use a small ticktime to make the test run faster
        servers = LaunchServers(numServers, 500);

        // find the leader
        int trueLeader = servers.findLeader();
        Assert.assertTrue("There should be a leader", trueLeader >= 0);

        // find a follower
        int falseLeader = (trueLeader + 1) % numServers;
        Assert.assertTrue("All servers should join the quorum",
                servers.mt[falseLeader].main.quorumPeer.follower != null);

        // to keep the quorum peer running and force it to go into the looking state, we kill leader election
        // and close the connection to the leader
        servers.mt[falseLeader].main.quorumPeer.electionAlg.shutdown();
        servers.mt[falseLeader].main.quorumPeer.follower.getSocket().close();

        // wait for the falseLeader to disconnect
        waitForOne(servers.zk[falseLeader], States.CONNECTING);

        // convince falseLeader that it is the leader
        servers.mt[falseLeader].main.quorumPeer.setPeerState(QuorumPeer.ServerState.LEADING);

        // provide time for the falseleader to realize no followers have connected
        // (this is twice the timeout used in Leader#getEpochToPropose)
        Thread.sleep(2 * servers.mt[falseLeader].main.quorumPeer.initLimit
                * servers.mt[falseLeader].main.quorumPeer.tickTime);

        // Restart leader election
        servers.mt[falseLeader].main.quorumPeer.startLeaderElection();

        // The previous client connection to falseLeader likely closed, create a new one
        servers.zk[falseLeader] = new ZooKeeper("127.0.0.1:" + servers.mt[falseLeader].getClientPort(),
                ClientBase.CONNECTION_TIMEOUT, this);

        // Wait for falseLeader to rejoin the quorum
        waitForOne(servers.zk[falseLeader], States.CONNECTED);

        // and ensure trueLeader is still the leader
        Assert.assertTrue(servers.mt[trueLeader].main.quorumPeer.leader != null);

        // Look through the logs for output that indicates the falseLeader is LEADING, then LOOKING, then FOLLOWING
        LineNumberReader r = new LineNumberReader(new StringReader(os.toString()));
        Pattern leading = Pattern.compile(".*myid=" + falseLeader + ".*LEADING.*");
        Pattern looking = Pattern.compile(".*myid=" + falseLeader + ".*LOOKING.*");
        Pattern following = Pattern.compile(".*myid=" + falseLeader + ".*FOLLOWING.*");

        String line;
        while ((line = r.readLine()) != null) {
            if (!foundLeading) {
                foundLeading = leading.matcher(line).matches();
            } else if (!foundLooking) {
                foundLooking = looking.matcher(line).matches();
            } else if (following.matcher(line).matches()) {
                foundFollowing = true;
                break;
            }
        }
    } finally {
        qlogger.removeAppender(appender);
    }

    Assert.assertTrue("falseLeader never attempts to become leader", foundLeading);
    Assert.assertTrue("falseLeader never gives up on leadership", foundLooking);
    Assert.assertTrue("falseLeader never rejoins the quorum", foundFollowing);
}

From source file:io.fabric8.ConnectorMojo.java

private List<String> loadFile(InputStream fis) throws Exception {
    List<String> lines = new ArrayList<>();
    LineNumberReader reader = new LineNumberReader(new InputStreamReader(fis));

    String line;//from  www. j  a  v  a2 s. co  m
    do {
        line = reader.readLine();
        if (line != null) {
            lines.add(line);
        }
    } while (line != null);
    reader.close();

    return lines;
}

From source file:org.fbk.cit.hlt.dirha.Evaluator.java

private Map<Integer, Sentence> read(File fin) throws IOException {
    LineNumberReader lr = new LineNumberReader(new InputStreamReader(new FileInputStream(fin), "UTF-8"));

    String line = null;/*from  w  w  w.  j  a v  a2 s . c o  m*/
    Map<Integer, Sentence> sentenceMap = new HashMap<>();
    String sid = null;
    int count = 0;
    Sentence sentence = null;
    while ((line = lr.readLine()) != null) {

        String[] s = line.split("\t", -1);
        if (s.length > 5) {

            if (sid == null) {
                sid = s[0];
                sentence = new Sentence(sid);
            }
            if (!s[0].equalsIgnoreCase(sid)) {
                sentenceMap.put(Integer.parseInt(sid), sentence);
                sid = s[0];
                sentence = new Sentence(sid);
            }
            if (!s[6].trim().equalsIgnoreCase("O")) {
                ClassifierResults res = ClassifierResults.fromTSV(s, 2);
                sentence.add(s[0], res.getFrame(), res.getRole(), res.getToken().replace(" ", ""));
            }

        }

    }
    sentenceMap.put(Integer.parseInt(sid), sentence);
    return sentenceMap;
}

From source file:org.gofleet.module.routing.RoutingMap.java

private int getNumberLines(File f) {
    LineNumberReader lineCounter;
    try {/* w w w  .  java 2 s  .co  m*/
        lineCounter = new LineNumberReader(new InputStreamReader(new FileInputStream(f.getPath())));

        while (lineCounter.readLine() != null)
            ;
        return lineCounter.getLineNumber();
    } catch (Exception done) {
        log.error(done, done);
        return -1;
    }

}

From source file:massbank.BatchSearchWorker.java

/**
 * T}t@C???iHTML`?j/*from  w  w  w . j ava  2  s .c o  m*/
 * @param resultFile t@C
 * @param htmlFile YtpHTMLt@C
 */
private void createSummary(File resultFile, File htmlFile) {
    LineNumberReader in = null;
    PrintWriter out = null;
    try {
        //(1) t@C?
        String line;
        int cnt = 0;
        ArrayList<String> nameList = new ArrayList<String>();
        ArrayList<String> top1LineList = new ArrayList<String>();
        TreeSet<String> top1IdList = new TreeSet<String>();
        in = new LineNumberReader(new FileReader(resultFile));
        while ((line = in.readLine()) != null) {
            line = line.trim();
            if (line.equals("")) {
                cnt = 0;
            } else {
                cnt++;
                if (cnt == 1) {
                    nameList.add(line);
                } else if (cnt == 2) {
                    if (line.equals("-1")) {
                        top1LineList.add("Invalid");
                    }
                    if (line.equals("0")) {
                        top1LineList.add("0");
                    }
                } else if (cnt == 4) {
                    String[] vals = line.split("\t");
                    String id = vals[0];
                    top1IdList.add(id);
                    top1LineList.add(line);
                }
            }
        }

        //? http://www.massbank.jp/ T?[o??KEGG???s
        HashMap<String, ArrayList> massbank2mapList = new HashMap<String, ArrayList>(); //(2)p
        HashMap<String, String> massbank2keggList = new HashMap<String, String>(); //(2)p
        HashMap<String, ArrayList> map2keggList = new HashMap<String, ArrayList>(); //(3)p
        ArrayList<String> mapNameList = new ArrayList<String>(); //(4)p
        boolean isKeggReturn = false;
        //         if (serverUrl.indexOf("www.massbank.jp") == -1) {
        //            isKeggReturn = false;
        //         }
        if (isKeggReturn) {

            //(2) KEGG ID, Map IDDB
            String where = "where MASSBANK in(";
            Iterator it = top1IdList.iterator();
            while (it.hasNext()) {
                String id = (String) it.next();
                where += "'" + id + "',";
            }
            where = where.substring(0, where.length() - 1);
            where += ")";
            String sql = "select MASSBANK, t1.KEGG, MAP from " + "(SELECT MASSBANK,KEGG FROM OTHER_DB_IDS "
                    + where + ") t1, PATHWAY_CPDS t2" + " where t1.KEGG=t2.KEGG order by MAP,MASSBANK";

            ArrayList<String> mapList = null;
            try {
                Class.forName("com.mysql.jdbc.Driver");
                String connectUrl = "jdbc:mysql://localhost/MassBank_General";
                Connection con = DriverManager.getConnection(connectUrl, "bird", "bird2006");
                Statement stmt = con.createStatement();
                ResultSet rs = stmt.executeQuery(sql);
                String prevId = "";
                while (rs.next()) {
                    String id = rs.getString(1);
                    String kegg = rs.getString(2);
                    String map = rs.getString(3);
                    if (!id.equals(prevId)) {
                        if (!prevId.equals("")) {
                            massbank2mapList.put(prevId, mapList);
                        }
                        mapList = new ArrayList<String>();
                        massbank2keggList.put(id, kegg);
                    }
                    mapList.add(map);
                    prevId = id;
                }
                massbank2mapList.put(prevId, mapList);

                rs.close();
                stmt.close();
                con.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (mapList != null) {

                //(3) Pathway Map?FtXg??
                it = massbank2mapList.keySet().iterator();
                while (it.hasNext()) {
                    String id = (String) it.next();
                    String kegg = (String) massbank2keggList.get(id);

                    ArrayList<String> list1 = massbank2mapList.get(id);
                    for (int i = 0; i < list1.size(); i++) {
                        String map = list1.get(i);
                        ArrayList<String> list2 = null;
                        if (map2keggList.containsKey(map)) {
                            list2 = map2keggList.get(map);
                            list2.add(kegg);
                        } else {
                            list2 = new ArrayList<String>();
                            list2.add(kegg);
                            map2keggList.put(map, list2);
                        }
                    }
                }

                //(4) SOAPPathway Map?Ft?\bh?s
                it = map2keggList.keySet().iterator();
                List<Callable<HashMap<String, String>>> tasks = new ArrayList();
                while (it.hasNext()) {
                    String map = (String) it.next();
                    mapNameList.add(map);
                    ArrayList<String> list = map2keggList.get(map);
                    String[] cpds = list.toArray(new String[] {});
                    Callable<HashMap<String, String>> task = new ColorPathway(map, cpds);
                    tasks.add(task);
                }
                Collections.sort(mapNameList);

                // Xbhv?[10
                ExecutorService exsv = Executors.newFixedThreadPool(10);
                List<Future<HashMap<String, String>>> results = exsv.invokeAll(tasks);

                // Pathway mapi[??
                String saveRootPath = MassBankEnv.get(MassBankEnv.KEY_TOMCAT_APPTEMP_PATH) + "pathway";
                File rootDir = new File(saveRootPath);
                if (!rootDir.exists()) {
                    rootDir.mkdir();
                }
                //               String savePath = saveRootPath + File.separator + this.jobId;
                //               File newDir = new File(savePath);
                //               if ( !newDir.exists() ) {
                //                  newDir.mkdir();
                //               }

                //(6) Pathway mapURL
                for (Future<HashMap<String, String>> future : results) {
                    HashMap<String, String> res = future.get();
                    it = res.keySet().iterator();
                    String map = (String) it.next();
                    String mapUrl = res.get(map);
                    String filePath = saveRootPath + File.separator + this.jobId + "_" + map + ".png";
                    FileUtil.downloadFile(mapUrl, filePath);
                }
            }
        }

        //(7) ?o
        out = new PrintWriter(new BufferedWriter(new FileWriter(htmlFile)));
        // wb_?[?o
        String reqIonStr = "Both";
        try {
            if (Integer.parseInt(this.ion) > 0) {
                reqIonStr = "Positive";
            } else if (Integer.parseInt(this.ion) < 0) {
                reqIonStr = "Negative";
            }
        } catch (NumberFormatException nfe) {
            nfe.printStackTrace();
        }
        String title = "Summary of Batch Service Results";
        out.println("<html>");
        out.println("<head>");
        out.println("<title>" + title + "</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>" + title + "</h1>");
        out.println("<hr>");
        out.println("<h3>Request Date : " + this.time + "</h3>");
        out.println("Instrument Type : " + this.inst + "<br>");
        out.println("MS Type : " + this.ms + "<br>");
        out.println("Ion Mode : " + reqIonStr + "<br>");
        out.println("<br>");
        out.println("<hr>");
        out.println("<table border=\"1\" cellspacing=\"0\" cellpadding=\"2\">");
        String cols = String.valueOf(mapNameList.size());
        out.println("<tr>");
        out.println("<th bgcolor=\"LavenderBlush\" rowspan=\"1\">No.</th>");
        out.println("<th bgcolor=\"LavenderBlush\" rowspan=\"1\">Query&nbsp;Name</th>");
        out.println("<th bgcolor=\"LightCyan\" rowspan=\"1\">Score</th>");
        out.println("<th bgcolor=\"LightCyan\" rowspan=\"1\">Hit</th>");
        out.println("<th bgcolor=\"LightCyan\" rowspan=\"1\">MassBank&nbsp;ID</th>");
        out.println("<th bgcolor=\"LightCyan\" rowspan=\"1\">Record&nbsp;Title</th>");
        out.println("<th bgcolor=\"LightCyan\" rowspan=\"1\">Formula</th>");
        out.println("<th bgcolor=\"LightCyan\" rowspan=\"1\">Exact Mass</th>");
        if (isKeggReturn) {
            out.println("<th bgcolor=\"LightYellow\" rowspan=\"2\">KEGG&nbsp;ID</th>");
            out.println(
                    "<th bgcolor=\"LightYellow\" colspan=\"" + cols + "\">Colored&nbsp;Pathway&nbsp;Maps</th>");
        }
        out.println("</tr>");
        out.print("<tr bgcolor=\"moccasin\">");
        for (int i = 0; i < mapNameList.size(); i++) {
            out.print("<th>MAP" + String.valueOf(i + 1) + "</th>");
        }
        out.println("</tr>");

        for (int i = 0; i < nameList.size(); i++) {
            out.println("<tr>");
            String no = String.format("%5d", i + 1);
            no = no.replace(" ", "&nbsp;");
            out.println("<td>" + no + "</td>");
            // Query Name
            String queryName = nameList.get(i);
            out.println("<td nowrap>" + queryName + "</td>");

            line = top1LineList.get(i);
            if (line.equals("0")) {
                if (isKeggReturn) {
                    cols = String.valueOf(mapNameList.size() + 5);
                } else {
                    cols = String.valueOf(6);
                }
                out.println("<td colspan=\"" + cols + "\">No Hit Record</td>");
            } else if (line.equals("Invalid")) {
                if (isKeggReturn) {
                    cols = String.valueOf(mapNameList.size() + 5);
                } else {
                    cols = String.valueOf(4);
                }
                out.println("<td colspan=\"" + cols + "\">Invalid Query</td>");
            } else {
                String[] data = formatLine(line);
                String id = data[0];
                String recTitle = data[1];
                String formula = data[2];
                String emass = data[3];
                String score = data[4];
                String hit = data[5];

                boolean isHiScore = false;
                if (Integer.parseInt(hit) >= 3 && Double.parseDouble(score) >= 0.8) {
                    isHiScore = true;
                }

                // Score
                if (isHiScore) {
                    out.println("<td><b>" + score + "</b></td>");
                } else {
                    out.println("<td>" + score + "</td>");
                }

                // hit peak
                if (isHiScore) {
                    out.println("<td align=\"right\"><b>" + hit + "</b></td>");
                } else {
                    out.println("<td align=\"right\">" + hit + "</td>");
                }

                // MassBank ID & Link
                out.println("<td><a href=\"" + serverUrl + "jsp/FwdRecord.jsp?id=" + id
                        + "\" target=\"_blank\">" + id + "</td>");
                // Record Title
                out.println("<td>" + recTitle + "</td>");

                // Formula
                out.println("<td nowrap>" + formula + "</td>");

                // Exact Mass
                out.println("<td nowrap>" + emass + "</td>");

                // KEGG ID & Link
                if (isKeggReturn) {
                    String keggLink = "&nbsp;&nbsp;-";
                    if (massbank2keggList.containsKey(id)) {
                        String keggUrl = "http://www.genome.jp/dbget-bin/www_bget?";
                        String kegg = massbank2keggList.get(id);
                        switch (kegg.charAt(0)) {
                        case 'C':
                            keggUrl += "cpd:" + kegg;
                            break;
                        case 'D':
                            keggUrl += "dr:" + kegg;
                            break;
                        case 'G':
                            keggUrl += "gl:" + kegg;
                            break;
                        }
                        keggLink = "<a href=\"" + keggUrl + "\" target=\"_blank\">" + kegg + "</a>";
                    }
                    out.println("<td>" + keggLink + "</td>");
                    // Pathway Map Link
                    if (massbank2mapList.containsKey(id)) {
                        ArrayList<String> list = massbank2mapList.get(id);
                        for (int l1 = mapNameList.size() - 1; l1 >= 0; l1--) {
                            boolean isFound = false;
                            String map = "";
                            for (int l2 = list.size() - 1; l2 >= 0; l2--) {
                                map = list.get(l2);
                                if (map.equals(mapNameList.get(l1))) {
                                    isFound = true;
                                    break;
                                }
                            }
                            if (isFound) {
                                ArrayList<String> list2 = map2keggList.get(map);
                                String mapUrl = serverUrl + "temp/pathway/" + this.jobId + "_" + map + ".png";
                                out.println("<td nowrap><a href=\"" + mapUrl + "\" target=\"_blank\">map:" + map
                                        + "(" + list2.size() + ")</a></td>");
                            } else {
                                out.println("<td>&nbsp;&nbsp;-</td>");
                            }
                        }
                    } else {
                        for (int l1 = mapNameList.size() - 1; l1 >= 0; l1--) {
                            out.println("<td>&nbsp;&nbsp;-</td>");
                        }
                    }
                }
            }
            out.println("</tr>");
        }
        out.println("</table>");
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
        }
        if (out != null) {
            out.flush();
            out.close();
        }
    }
}

From source file:edu.stanford.muse.util.Util.java

/**
 * returns collection of lines from given file (UTF-8).
 * trims spaces from the lines,//w w  w.j a v  a 2  s.  c o m
 * ignores lines starting with # if ignoreCommentLines is true
 */
public static List<String> getLinesFromReader(Reader reader, boolean ignoreCommentLines) throws IOException {
    LineNumberReader lnr = new LineNumberReader(reader);
    List<String> result = new ArrayList<String>();
    while (true) {
        String line = lnr.readLine();
        if (line == null)
            break;
        line = line.trim();

        if (ignoreCommentLines && (line.length() == 0 || line.charAt(0) == '#'))
            continue;

        result.add(line);
    }
    return result;
}

From source file:com.google.ratel.service.error.ErrorReport.java

/**
 * Return Java Source LineNumberReader for the given filename, or null if not found.
 *
 * @param filename the name of the Java source file, e.g. /examples/Page.java
 * @return LineNumberReader for the given source filename, or null if not found
 * @throws FileNotFoundException if file could not be found
 *///from  w w w . ja  va 2s . com
protected LineNumberReader getJavaSourceReader(String filename) throws FileNotFoundException {

    if (serviceClass == null) {
        return null;
    }

    // Look for source file on classpath
    InputStream is = serviceClass.getResourceAsStream(filename);
    if (is != null) {
        return new LineNumberReader(new InputStreamReader(is));
    }

    // Else search for source file under WEB-INF
    String rootPath = ratelConfig.getServletContext().getRealPath("/");

    String webInfPath = rootPath + File.separator + "WEB-INF";

    File sourceFile = null;

    File webInfDir = new File(webInfPath);
    if (webInfDir.isDirectory() && webInfDir.canRead()) {
        File[] dirList = webInfDir.listFiles();
        if (dirList != null) {
            for (File file : dirList) {
                if (file.isDirectory() && file.canRead()) {
                    String sourcePath = file.toString() + filename;
                    sourceFile = new File(sourcePath);
                    if (sourceFile.isFile() && sourceFile.canRead()) {

                        FileInputStream fis = new FileInputStream(sourceFile);
                        return new LineNumberReader(new InputStreamReader(fis));
                    }
                }
            }
        }
    }

    return null;
}

From source file:net.sf.keystore_explorer.crypto.signing.JarSigner.java

private static String getManifestMainAttrs(JarFile jar) throws IOException {

    // Get full manifest content
    String manifestContent = getManifest(jar);

    LineNumberReader lnr = new LineNumberReader(new StringReader(manifestContent));

    try {/*  w  ww  .ja  v a2  s .c  om*/
        StringBuilder sb = new StringBuilder();

        String line = null;

        // Keep reading until a blank line is found - the end of the main
        // attributes
        while ((line = lnr.readLine()) != null) {
            if (line.trim().length() == 0) {
                break;
            }

            // Append attribute line
            sb.append(line);
            sb.append(CRLF);
        }

        return sb.toString();
    } finally {
        IOUtils.closeQuietly(lnr);
    }
}