Example usage for java.io LineNumberReader readLine

List of usage examples for java.io LineNumberReader readLine

Introduction

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

Prototype

public String readLine() throws IOException 

Source Link

Document

Read a line of text.

Usage

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  . ja  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.netscape.cms.logging.LogFile.java

/**
 * This method actually does the logging, and is not overridden
 * by subclasses, so you can call it and know that it will do exactly
 * what you see below.//w w  w .j  av  a  2s  .c om
 */
private synchronized void doLog(ILogEvent event, boolean noFlush) throws ELogException {

    String entry = logEvt2String(event);

    if (mLogWriter == null) {
        String[] params = { mFileName, entry };

        if (mLogSigning) {
            ConsoleError.send(new SystemEvent(CMS.getUserMessage("CMS_LOG_LOGFILE_CLOSED", params)));
            // Failed to write to audit log, shut down CMS
            shutdownCMS();
        }
        throw new ELogException(CMS.getUserMessage("CMS_LOG_LOGFILE_CLOSED", params));
    } else {
        try {
            mLogWriter.write(entry, 0/*offset*/, entry.length());

            if (mLogSigning == true) {
                if (mSignature != null) {
                    // include newline for calculating MAC
                    mSignature.update(entry.getBytes("UTF-8"));
                } else {
                    CMS.debug("LogFile: mSignature is not yet ready... null in log()");
                }
            }
            if (mTrace) {
                CharArrayWriter cw = new CharArrayWriter(200);
                PrintWriter pw = new PrintWriter(cw);
                Exception e = new Exception();
                e.printStackTrace(pw);
                char[] c = cw.toCharArray();
                cw.close();
                pw.close();

                CharArrayReader cr = new CharArrayReader(c);
                LineNumberReader lr = new LineNumberReader(cr);

                String text = null;
                String method = null;
                String fileAndLine = null;
                if (lr.ready()) {
                    text = lr.readLine();
                    do {
                        text = lr.readLine();
                    } while (text.indexOf("logging") != -1);
                    int p = text.indexOf("(");
                    fileAndLine = text.substring(p);

                    String classandmethod = text.substring(0, p);
                    int q = classandmethod.lastIndexOf(".");
                    method = classandmethod.substring(q + 1);
                    mLogWriter.write(fileAndLine, 0/*offset*/, fileAndLine.length());
                    mLogWriter.write(" ", 0/*offset*/, " ".length());
                    mLogWriter.write(method, 0/*offset*/, method.length());
                }
            }
            mLogWriter.newLine();

            if (mLogSigning == true) {
                if (mSignature != null) {
                    mSignature.update(LINE_SEP_BYTE);
                } else {
                    CMS.debug("LogFile: mSignature is null in log() 2");
                }
            }
        } catch (IOException e) {
            ConsoleError.send(new SystemEvent(
                    CMS.getUserMessage("CMS_LOG_WRITE_FAILED", mFileName, entry, e.toString())));
            if (mLogSigning) {
                // Failed to write to audit log, shut down CMS
                e.printStackTrace();
                shutdownCMS();
            }
        } catch (IllegalStateException e) {
            CMS.debug("LogFile: exception thrown in log(): " + e.toString());
            ConsoleError
                    .send(new SignedAuditEvent(CMS.getLogMessage(LOG_SIGNED_AUDIT_EXCEPTION, e.toString())));
        } catch (GeneralSecurityException gse) {
            // DJN: handle error
            CMS.debug("LogFile: exception thrown in log(): " + gse.toString());
            gse.printStackTrace();
            ConsoleError
                    .send(new SignedAuditEvent(CMS.getLogMessage(LOG_SIGNED_AUDIT_EXCEPTION, gse.toString())));
        } catch (Exception ee) { // Make darn sure we got everything
            ConsoleError
                    .send(new SignedAuditEvent(CMS.getLogMessage(LOG_SIGNED_AUDIT_EXCEPTION, ee.toString())));
            if (mLogSigning) {
                // Failed to write to audit log, shut down CMS
                ee.printStackTrace();
                shutdownCMS();
            }

        }

        // XXX
        // Although length will be in Unicode dual-bytes, the PrintWriter
        // will only print out 1 byte per character.  I suppose this could
        // be dependent on the encoding of your log file, but it ain't that
        // smart yet.  Also, add one for the newline. (hmm, on NT, CR+LF)
        int nBytes = entry.length() + 1;

        mBytesWritten += nBytes;
        mBytesUnflushed += nBytes;

        if (mBufferSize > 0 && mBytesUnflushed > mBufferSize && !noFlush) {
            flush();
        }
    }
}

From source file:massbank.BatchJobWorker.java

/**
 * Ytt@C???iHTML`?j//from w w w.j av a 2s .  c o m
 * @param time NGXg 
 * @param resultFile t@C
 * @param htmlFile YtpHTMLt@C
 */
private void createHtmlFile(String time, File resultFile, File htmlFile) {
    NumberFormat nf = NumberFormat.getNumberInstance();
    LineNumberReader in = null;
    PrintWriter out = null;
    try {
        in = new LineNumberReader(new FileReader(resultFile));
        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();
        }
        out.println("<html>");
        out.println("<head><title>MassBank Batch Service Results</title></head>");
        out.println("<body>");
        out.println(
                "<h1><a href=\"http://www.massbank.jp/\" target=\"_blank\">MassBank</a> Batch Service Results</h1>");
        out.println("<hr>");
        out.println("<h2>Request Date : " + time + "<h2>");
        out.println("Instrument Type : " + this.inst + "<br>");
        out.println("Ion Mode : " + reqIonStr + "<br>");
        out.println("<br><hr>");

        // ?o
        String line;
        long queryCnt = 0;
        boolean readName = false;
        boolean readHit = false;
        boolean readNum = false;
        while ((line = in.readLine()) != null) {
            if (in.getLineNumber() < 4) {
                continue;
            }
            if (!readName) {
                queryCnt++;
                out.println("<h2>Query " + nf.format(queryCnt) + "</h2><br>");
                out.println("Name: " + line.trim() + "<br>");
                readName = true;
            } else if (!readHit) {
                out.println("Hit: " + nf.format(Integer.parseInt(line.trim())) + "<br>");
                readHit = true;
            } else if (!readNum) {
                out.println("<table border=\"1\">");
                out.println("<tr><td colspan=\"6\">Top " + line.trim() + " List</td></tr>");
                out.println(
                        "<tr><th>Accession</th><th>Title</th><th>Formula</th><th>Ion</th><th>Score</th><th>Hit</th></tr>");
                readNum = true;
            } else {
                if (!line.trim().equals("")) {
                    String[] data = formatLine(line);
                    String acc = data[0];
                    String title = data[1];
                    String formula = data[2];
                    String ion = data[3];
                    String score = data[4];
                    String hit = data[5];

                    out.println("<tr>");
                    out.println("<td><a href=\"http://www.massbank.jp/jsp/FwdRecord.jsp?id=" + acc
                            + "\" target=\"_blank\">" + acc + "</td>");
                    out.println("<td>" + title + "</td>");
                    out.println("<td>" + formula + "</td>");
                    out.println("<td>" + ion + "</td>");
                    out.println("<td>" + score + "</td>");
                    out.println("<td align=\"right\">" + hit + "</td>");
                    out.println("</tr>");
                } else {
                    out.println("</table>");
                    out.println("<hr>");
                    readName = false;
                    readHit = false;
                    readNum = false;
                }
            }
        }
    } 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

public static Collection<String> breakIntoParas(String input) throws IOException {
    List<String> paras = new ArrayList<String>();
    LineNumberReader lnr = new LineNumberReader(new StringReader(input));

    StringBuilder currentPara = new StringBuilder();

    while (true) {
        String line = lnr.readLine();
        if (line == null)
            break;
        line = line.trim();/*w ww  .  j a v  a2 s . c  o m*/

        if (line.length() == 0) {
            // end para
            if (currentPara.length() > 0)
                paras.add(currentPara.toString());
            currentPara = new StringBuilder();
        } else {
            currentPara.append(line);
            currentPara.append("\n");
        }
    }

    // add any residue
    if (currentPara.length() > 0)
        paras.add(currentPara.toString());
    return paras;
}

From source file:net.rptools.maptool.launcher.MapToolLauncher.java

/**
 * Read the given XML file and look for specially formatted lines so that a
 * description of the files purpose and text to display in a tooltip are
 * retrieved. The current process involves looking for XML comments that
 * match the regex <code><b>^&lt;!--\s+(\w+):\s*(.*)\s+--&gt;$</b></code>
 * and pull out the two fields; the first field is the key and the second is
 * the value for storing the information in the returned object.
 * //from w w  w .  ja  va 2  s.c o  m
 * @param xml
 *            <code>File</code> object representing the file to read
 * @return a {@link LoggingConfig} object which stores information about the
 *         XML file
 */
private LoggingConfig readDescFromXmlFile(File xml) {
    final LoggingConfig config = new LoggingConfig(xml, new JCheckBox());
    LineNumberReader lnbr = null;
    final String REGEX = "^<!--\\s+(\\w+):\\s*(.*)\\s+-->$"; //$NON-NLS-1$
    final Pattern pattern = Pattern.compile(REGEX);
    try {
        int count = 0;
        lnbr = new LineNumberReader(new BufferedReader(new FileReader(xml)));
        String line = lnbr.readLine();
        config.addProperty("desc", xml.getName()); //$NON-NLS-1$
        config.addProperty("ttip", xml.getName()); //$NON-NLS-1$
        while (count < 2 && line != null) {
            line = line.trim();
            final Matcher m = pattern.matcher(line);
            if (m.matches()) {
                final String key = m.group(1);
                final String value = m.group(2);
                config.addProperty(key, value);
                count++;
            }
            line = lnbr.readLine();
        }
        if (count < 2) {
            JOptionPane.showMessageDialog(null,
                    CopiedFromOtherJars.getText("msg.error.loggingBadFormat", xml.getName()), //$NON-NLS-1$
                    CopiedFromOtherJars.getText("msg.title.loggingBadFormat", xml), //$NON-NLS-1$
                    ERROR_MESSAGE);
        }
    } catch (final FileNotFoundException e) {
    } catch (final IOException e) {
    } finally {
        CopiedFromOtherJars.closeQuietly(lnbr);
    }
    return config;
}

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

/**
 * Verify boot fails with a bad MetricsProvider
 *//*from  ww w.  jav a 2 s  . c o m*/
@Test
public void testInvalidMetricsProvider() throws Exception {
    ClientBase.setupTestEnv();

    // setup the logger to capture all logs
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    WriterAppender appender = getConsoleAppender(os, Level.WARN);
    Logger qlogger = Logger.getLogger("org.apache.zookeeper.server.quorum");
    qlogger.addAppender(appender);

    try {
        final int CLIENT_PORT_QP1 = PortAssignment.unique();

        String quorumCfgSection = "server.1=127.0.0.1:" + PortAssignment.unique() + ":"
                + PortAssignment.unique() + ";" + CLIENT_PORT_QP1 + "\n" + "server.2=127.0.0.1:"
                + PortAssignment.unique() + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1 + "\n"
                + "metricsProvider.className=BadClass\n";

        MainThread q1 = new MainThread(1, CLIENT_PORT_QP1, quorumCfgSection);
        q1.start();

        boolean isup = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1, 5000);

        Assert.assertFalse("Server never came up", isup);

        q1.shutdown();

        Assert.assertTrue("waiting for server 1 down",
                ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP1, ClientBase.CONNECTION_TIMEOUT));

    } finally {
        qlogger.removeAppender(appender);
    }

    LineNumberReader r = new LineNumberReader(new StringReader(os.toString()));
    String line;
    boolean found = false;
    Pattern p = Pattern.compile(".*BadClass.*");
    while ((line = r.readLine()) != null) {
        found = p.matcher(line).matches();
        if (found) {
            break;
        }
    }
    Assert.assertTrue("complains about metrics provider", found);
}

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

/**
 * Verify handling of quorum defaults/*from  w  ww .ja  v a  2 s.  c  o m*/
 * * default electionAlg is fast leader election
 */
@Test
public void testQuorumDefaults() throws Exception {
    ClientBase.setupTestEnv();

    // setup the logger to capture all logs
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    WriterAppender appender = getConsoleAppender(os, Level.INFO);
    appender.setImmediateFlush(true);
    Logger zlogger = Logger.getLogger("org.apache.zookeeper");
    zlogger.addAppender(appender);

    try {
        final int CLIENT_PORT_QP1 = PortAssignment.unique();
        final int CLIENT_PORT_QP2 = PortAssignment.unique();

        String quorumCfgSection = "server.1=127.0.0.1:" + PortAssignment.unique() + ":"
                + PortAssignment.unique() + ";" + CLIENT_PORT_QP1 + "\nserver.2=127.0.0.1:"
                + PortAssignment.unique() + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP2;

        MainThread q1 = new MainThread(1, CLIENT_PORT_QP1, quorumCfgSection);
        MainThread q2 = new MainThread(2, CLIENT_PORT_QP2, quorumCfgSection);
        q1.start();
        q2.start();

        Assert.assertTrue("waiting for server 1 being up",
                ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1, CONNECTION_TIMEOUT));
        Assert.assertTrue("waiting for server 2 being up",
                ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP2, CONNECTION_TIMEOUT));

        q1.shutdown();
        q2.shutdown();

        Assert.assertTrue("waiting for server 1 down",
                ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP1, ClientBase.CONNECTION_TIMEOUT));
        Assert.assertTrue("waiting for server 2 down",
                ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP2, ClientBase.CONNECTION_TIMEOUT));

    } finally {
        zlogger.removeAppender(appender);
    }
    os.close();
    LineNumberReader r = new LineNumberReader(new StringReader(os.toString()));
    String line;
    boolean found = false;
    Pattern p = Pattern.compile(".*FastLeaderElection.*");
    while ((line = r.readLine()) != null) {
        found = p.matcher(line).matches();
        if (found) {
            break;
        }
    }
    Assert.assertTrue("fastleaderelection used", found);
}

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

/**
 * Verify boot fails with a MetricsProvider with fails to start
 *//*  www  .  j  a  v  a  2  s.  co  m*/
@Test
public void testFaultyMetricsProviderOnStart() throws Exception {
    ClientBase.setupTestEnv();

    // setup the logger to capture all logs
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    WriterAppender appender = getConsoleAppender(os, Level.WARN);
    Logger qlogger = Logger.getLogger("org.apache.zookeeper.server.quorum");
    qlogger.addAppender(appender);

    try {
        final int CLIENT_PORT_QP1 = PortAssignment.unique();

        String quorumCfgSection = "server.1=127.0.0.1:" + PortAssignment.unique() + ":"
                + PortAssignment.unique() + ";" + CLIENT_PORT_QP1 + "\n" + "server.2=127.0.0.1:"
                + PortAssignment.unique() + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1 + "\n"
                + "metricsProvider.className="
                + BaseTestMetricsProvider.MetricsProviderWithErrorInStart.class.getName() + "\n";

        MainThread q1 = new MainThread(1, CLIENT_PORT_QP1, quorumCfgSection);
        q1.start();

        boolean isup = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1, 5000);

        Assert.assertFalse("Server never came up", isup);

        q1.shutdown();

        Assert.assertTrue("waiting for server 1 down",
                ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP1, ClientBase.CONNECTION_TIMEOUT));

    } finally {
        qlogger.removeAppender(appender);
    }

    LineNumberReader r = new LineNumberReader(new StringReader(os.toString()));
    String line;
    boolean found = false;
    Pattern p = Pattern.compile(".*MetricsProviderLifeCycleException.*");
    while ((line = r.readLine()) != null) {
        found = p.matcher(line).matches();
        if (found) {
            break;
        }
    }
    Assert.assertTrue("complains about metrics provider MetricsProviderLifeCycleException", found);
}

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

/**
 * Verify boot fails with a MetricsProvider with fails to start
 */// ww w. j  a  v a 2s.c  o  m
@Test
public void testFaultyMetricsProviderOnConfigure() throws Exception {
    ClientBase.setupTestEnv();

    // setup the logger to capture all logs
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    WriterAppender appender = getConsoleAppender(os, Level.WARN);
    Logger qlogger = Logger.getLogger("org.apache.zookeeper.server.quorum");
    qlogger.addAppender(appender);

    try {
        final int CLIENT_PORT_QP1 = PortAssignment.unique();

        String quorumCfgSection = "server.1=127.0.0.1:" + PortAssignment.unique() + ":"
                + PortAssignment.unique() + ";" + CLIENT_PORT_QP1 + "\n" + "server.2=127.0.0.1:"
                + PortAssignment.unique() + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1 + "\n"
                + "metricsProvider.className="
                + BaseTestMetricsProvider.MetricsProviderWithErrorInConfigure.class.getName() + "\n";

        MainThread q1 = new MainThread(1, CLIENT_PORT_QP1, quorumCfgSection);
        q1.start();

        boolean isup = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1, 5000);

        Assert.assertFalse("Server never came up", isup);

        q1.shutdown();

        Assert.assertTrue("waiting for server 1 down",
                ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP1, ClientBase.CONNECTION_TIMEOUT));

    } finally {
        qlogger.removeAppender(appender);
    }

    LineNumberReader r = new LineNumberReader(new StringReader(os.toString()));
    String line;
    boolean found = false;
    Pattern p = Pattern.compile(".*MetricsProviderLifeCycleException.*");
    while ((line = r.readLine()) != null) {
        found = p.matcher(line).matches();
        if (found) {
            break;
        }
    }
    Assert.assertTrue("complains about metrics provider MetricsProviderLifeCycleException", found);
}

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

/**
 * Test verifies that the server shouldn't be affected but runtime errors on stop()
 *//*from www .j a  v  a 2  s .  c o  m*/
@Test
public void testFaultyMetricsProviderOnStop() throws Exception {
    ClientBase.setupTestEnv();
    BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.reset();

    // setup the logger to capture all logs
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    WriterAppender appender = getConsoleAppender(os, Level.WARN);
    Logger qlogger = Logger.getLogger("org.apache.zookeeper.server.quorum");
    qlogger.addAppender(appender);

    try {
        final int CLIENT_PORT_QP1 = PortAssignment.unique();
        final int CLIENT_PORT_QP2 = PortAssignment.unique();

        String quorumCfgSectionServer = "server.1=127.0.0.1:" + PortAssignment.unique() + ":"
                + PortAssignment.unique() + ";" + CLIENT_PORT_QP1 + "\n" + "server.2=127.0.0.1:"
                + PortAssignment.unique() + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP2 + "\n";

        // server 1 boots with a MetricsProvider
        String quorumCfgSectionServer1 = quorumCfgSectionServer + "metricsProvider.className="
                + BaseTestMetricsProvider.MetricsProviderWithErrorInStop.class.getName() + "\n";

        MainThread q1 = new MainThread(1, CLIENT_PORT_QP1, quorumCfgSectionServer1);
        MainThread q2 = new MainThread(2, CLIENT_PORT_QP2, quorumCfgSectionServer);
        q1.start();
        q2.start();

        boolean isup1 = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1, 30000);
        boolean isup2 = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP2, 30000);
        Assert.assertTrue("Server 1 never came up", isup1);
        Assert.assertTrue("Server 2 never came up", isup2);

        q1.shutdown();
        q2.shutdown();

        Assert.assertTrue("waiting for server 1 down",
                ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP1, ClientBase.CONNECTION_TIMEOUT));

        Assert.assertTrue("waiting for server 2 down",
                ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP2, ClientBase.CONNECTION_TIMEOUT));
    } finally {
        qlogger.removeAppender(appender);
    }

    Assert.assertTrue("metrics provider lifecycle error",
            BaseTestMetricsProvider.MetricsProviderWithErrorInStop.stopCalled.get());

    LineNumberReader r = new LineNumberReader(new StringReader(os.toString()));
    String line;
    boolean found = false;
    Pattern p = Pattern.compile(".*Error while stopping metrics.*");
    while ((line = r.readLine()) != null) {
        found = p.matcher(line).matches();
        if (found) {
            break;
        }
    }
    Assert.assertTrue("complains about metrics provider", found);
}