Example usage for java.io LineNumberReader getLineNumber

List of usage examples for java.io LineNumberReader getLineNumber

Introduction

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

Prototype

public int getLineNumber() 

Source Link

Document

Get the current line number.

Usage

From source file:org.marketcetera.strategyagent.StrategyAgent.java

/**
 * Parses the commands from the supplied commands file.
 *
 * @param inFile the file path//  ww  w  .  j av  a  2s  .  c  om
 *
 * @throws IOException if there were errors parsing the file.
 *
 * @return the number of errors encountered when parsing the command file.
 */
private int parseCommands(String inFile) throws IOException {
    int numErrors = 0;
    LineNumberReader reader = new LineNumberReader(new UnicodeFileReader(inFile));
    try {
        String line;
        while ((line = reader.readLine()) != null) {
            if (line.startsWith("#") || line.trim().isEmpty()) { //$NON-NLS-1$
                //Ignore comments and empty lines.
                continue;
            }
            int idx = line.indexOf(';'); //$NON-NLS-1$
            if (idx > 0) {
                String key = line.substring(0, idx);
                CommandRunner runner = sRunners.get(key);
                if (runner == null) {
                    numErrors++;
                    Messages.INVALID_COMMAND_NAME.error(this, key, reader.getLineNumber());
                    continue;
                }
                mCommands.add(new Command(runner, line.substring(++idx), reader.getLineNumber()));
            } else {
                numErrors++;
                Messages.INVALID_COMMAND_SYNTAX.error(this, line, reader.getLineNumber());
            }
        }
        return numErrors;
    } finally {
        reader.close();
    }
}

From source file:org.mitre.xcoord.TestScript.java

/**
 * This will accomodate any test file that has at least the following style:
 *
 * FAMILY-XXX COORDINATE TEXT "FAIL"//from  w ww  . j  a  v  a 2 s.com
 *
 * Where the first FAMILY token is
 *
 * @param coordfile
 */
public void fileTestByLines(String coordfile) {

    xcoord.match_UTM(true);
    xcoord.match_MGRS(true);
    xcoord.match_DD(true);
    xcoord.match_DMS(true);
    xcoord.match_DM(true);

    try {

        String _file = coordfile.trim();
        String fname = FilenameUtils.getBaseName(_file);
        TestUtility tester = new TestUtility("./results/xcoord_" + fname + "-lines.csv");

        java.io.LineNumberReader in = FileUtility.getLineReader(coordfile);
        String line = null;
        while ((line = in.readLine()) != null) {

            String text = line.trim();
            if (text.startsWith("#")) {
                continue;
            }
            if (text.isEmpty()) {
                continue;
            }

            String fam = find_family(line);
            int famx = XConstants.get_CCE_family(fam);

            if (famx == XConstants.UNK_PATTERN) {
                log.error("Unknown test pattern TEXT=" + text);
                continue;
            }

            TestCase tst = new TestCase("#" + in.getLineNumber(), fam, text);
            TextMatchResultSet results = xcoord.extract_coordinates(tst.text, tst.id);
            /**
             * tst.family_id
             */
            results.add_trace("Test Payload: " + tst.text);

            if (!results.evaluated) {
                continue;
            }

            log.info("=========FILE TEST " + tst.id + " FOUND:"
                    + (results.matches.isEmpty() ? "NOTHING" : results.matches.size()));
            tester.save_result(tst, results);
        }

        tester.close_report();

        log.info("=== FILE TESTS DONE ===");

    } catch (Exception err) {
        log.error("TEST BY LINES", err);
    }

}

From source file:org.opensextant.extractors.test.TestXCoord.java

/**
 * This will accomodate any test file that has at least the following style:
 *
 * FAMILY-XXX COORDINATE TEXT "FAIL"/* w w  w  .  jav a  2 s .c o  m*/
 *
 * Where the first FAMILY token is
 *
 * @param coordfile
 */
public void fileTestByLines(String coordfile) {

    xcoord.match_UTM(true);
    xcoord.match_MGRS(true);
    xcoord.match_DD(true);
    xcoord.match_DMS(true);
    xcoord.match_DM(true);

    try {

        String _file = coordfile.trim();
        String fname = FilenameUtils.getBaseName(_file);
        TestXCoordReporter tester = new TestXCoordReporter("./results/xcoord_" + fname + "-lines.csv");

        java.io.LineNumberReader in = getLineReader(coordfile);
        String line = null;
        while ((line = in.readLine()) != null) {

            String text = line.trim();
            if (text.startsWith("#")) {
                continue;
            }
            if (text.isEmpty()) {
                continue;
            }

            String fam = find_family(line);
            int famx = XConstants.get_CCE_family(fam);

            if (famx == XConstants.UNK_PATTERN) {
                log.error("Unknown test pattern TEXT=" + text);
                continue;
            }

            GeocoordTestCase tst = new GeocoordTestCase("#" + in.getLineNumber(), fam, text);
            TextMatchResult results = xcoord.extract_coordinates(tst.text, tst.id);
            /**
             * tst.family_id
             */
            results.add_trace("Test Payload: " + tst.text);

            if (!results.evaluated) {
                continue;
            }

            log.info("=========FILE TEST " + tst.id + " FOUND:"
                    + (results.matches.isEmpty() ? "NOTHING" : results.matches.size()));
            tester.save_result(tst, results);
        }

        tester.close_report();

        log.info("=== FILE TESTS DONE ===");

    } catch (Exception err) {
        log.error("TEST BY LINES", err);
    }

}

From source file:org.apache.james.core.MimeMessageWrapper.java

/**
 * Corrects JavaMail 1.1 version which always returns -1. Only corrected for
 * content less than 5000 bytes, to avoid memory hogging.
 *//*from  ww w .j av a2  s.co  m*/
@Override
public int getLineCount() throws MessagingException {
    InputStream in;
    try {
        in = getContentStream();
    } catch (Exception e) {
        return -1;
    }
    if (in == null) {
        return -1;
    }
    // Wrap input stream in LineNumberReader
    // Not sure what encoding to use really...
    InputStreamReader isr = null;
    LineNumberReader counter = null;
    try {
        if (getEncoding() != null) {
            isr = new InputStreamReader(in, getEncoding());
            counter = new LineNumberReader(isr);
        } else {
            isr = new InputStreamReader(in);
            counter = new LineNumberReader(isr);
        }
        // Read through all the data
        char[] block = new char[4096];
        while (counter.read(block) > -1) {
            // Just keep reading
        }
        return counter.getLineNumber();
    } catch (IOException ioe) {
        return -1;
    } finally {
        IOUtils.closeQuietly(counter);
        IOUtils.closeQuietly(isr);
        IOUtils.closeQuietly(in);
    }
}

From source file:com.netspective.commons.text.TextUtils.java

/**
 * Retrieve lines of text from an input stream
 *
 * @param is              The input stream to read
 * @param startLineNumber The starting line number
 * @param endLineNumber   The ending line number
 *
 * @return The text contained in line numbers startingLineNumber to endingLineNumber
 *//*from w w w  .  j a  va2 s. c om*/
public String getTextStreamLines(InputStream is, int startLineNumber, int endLineNumber) throws IOException {
    if (is == null)
        return null;

    if (startLineNumber <= 0 && endLineNumber <= 0)
        return null;

    Reader isReader = null;
    LineNumberReader reader = null;
    StringBuffer result = new StringBuffer();

    try {
        isReader = new InputStreamReader(is);
        reader = new LineNumberReader(isReader);

        String line = null;

        if (startLineNumber > 0 && endLineNumber <= 0) {
            while ((line = reader.readLine()) != null) {
                if (reader.getLineNumber() == startLineNumber)
                    return line;
            }

        } else {
            while ((line = reader.readLine()) != null) {
                int lineNumber = reader.getLineNumber();

                if (lineNumber < startLineNumber)
                    continue;

                if (lineNumber > endLineNumber)
                    break;

                result.append(line);
                result.append("\n");
            }
        }
    } finally {
        if (reader != null)
            reader.close();

        if (isReader != null)
            is.close();

        is.close();
    }

    return result.toString();
}

From source file:de.innovationgate.wgpublisher.WGPDeployer.java

public String preprocessCode(WGTMLModule mod, String code, int codeOffset) throws WGAPIException {

    // First pass. Process preprocessor tags
    try {/*  w  w w . j  ava 2s.  com*/
        PPTagsPreProcessor preProcessor = new PPTagsPreProcessor(_core, mod);
        code = WGUtils.strReplace(code, "{%", preProcessor, true);
    } catch (RuntimeException e) {
        LOG.error("Error preprocessing WebTML module " + mod.getDocumentKey(), e);
    }

    // Process <@ preprocessor if enabled
    if (mod.isPreprocess()) {
        try {
            //code = code.replaceAll("@@([\\w|\\$]+)", "<tml:item name=\"$1\"/>");
            PPPreProcessor pppreProcessor = new PPPreProcessor(_core, mod);
            code = WGUtils.strReplace(code, "@{", pppreProcessor, true);
        } catch (RuntimeException e) {
            LOG.error("Error preprocessing WebTML module " + mod.getDocumentKey(), e);
        }
    }

    // Second pass. Process WebTML tags
    LineNumberReader reader = new LineNumberReader(new StringReader(code));
    StringBuffer out = new StringBuffer();
    TMLTagsPreProcessor linePreProcessor = new TMLTagsPreProcessor();
    String line;
    boolean firstLine = true;
    try {
        while ((line = reader.readLine()) != null) {
            if (!firstLine) {
                out.append("\n");
            } else {
                firstLine = false;
            }
            linePreProcessor.setLineNumber(codeOffset + reader.getLineNumber());
            out.append(WGUtils.strReplace(line, "<tml:", linePreProcessor, true));
        }
        code = out.toString();
    } catch (IOException e) {
        LOG.error("Error adding line numbers to WebTML code", e);
    }

    // Third pass. Process WebTML close tags
    code = WGUtils.strReplace(code, "</tml:", new TMLCloseTagsPreProcessor(), true);

    return code;
}

From source file:org.lockss.plugin.metapress.LocalRisMetadataExtractor.java

/**
 * Extract metadata from the content of the cu, which should be an RIS file.
 * Reads line by line inserting the 2 character code and value into the raw map.
 * The first line should be a material type witch if it is book or journal will 
 * determine if we interpret the SN tag as IS beltSN or ISBN.
 * @param target/*  w  w w .  jav  a  2s  . c  o  m*/
 * @param cu
 */
public final ArticleMetadata extract(MetadataTarget target, CachedUrl cu) throws IOException, PluginException {
    if (cu == null) {
        throw new IllegalArgumentException();
    }

    log.debug2("Parsing " + cu.getUrl());

    am = new ArticleMetadata();
    refType = null;
    currentTag = null;
    currentValue = new StringBuilder();
    boolean hasBegun = false;

    LineNumberReader reader = new LineNumberReader(cu.openForReading());
    try {
        for (String line = reader.readLine(); line != null; line = reader.readLine()) {
            // Skip empty lines at beginning of file
            if (!hasBegun && line.trim().isEmpty()) {
                continue;
            }
            hasBegun = true;

            Matcher mat = risPattern.matcher(line);
            if (mat.find()) {
                // process old tag
                processTag();
                // set up new tag
                currentTag = mat.group(1);
                currentValue = new StringBuilder(mat.group(2).trim());
            } else {
                if (currentTag == null) {
                    log.debug(String.format("%s line %d: ignoring continuation line in preamble", cu.getUrl(),
                            reader.getLineNumber()));
                    continue;
                }
                // process continuation of current tag
                String continuation = line.trim();
                if (!continuation.isEmpty()) {
                    currentValue.append(' ');
                    currentValue.append(continuation);
                }
            }
        }
        processTag();
    } finally {
        IOUtil.safeClose(reader);
    }

    am.cook(risTagToMetadataField);
    return am;
}

From source file:org.apache.pdfbox.text.BidiTest.java

/**
 * Validate text extraction on a single file.
 *
 * @param inFile The PDF file to validate
 * @param outDir The directory to store the output in
 * @param bLogResult Whether to log the extracted text
 * @param bSort Whether or not the extracted text is sorted
 * @throws Exception when there is an exception
 *///from ww  w. j a  va  2s.c  o  m
public void doTestFile(File inFile, File outDir, boolean bLogResult, boolean bSort) throws IOException {
    if (bSort) {
        log.info("Preparing to parse " + inFile.getName() + " for sorted test");
    } else {
        log.info("Preparing to parse " + inFile.getName() + " for standard test");
    }

    if (!outDir.exists()) {
        if (!outDir.mkdirs()) {
            throw (new IOException("Error creating " + outDir.getAbsolutePath() + " directory"));
        }
    }

    PDDocument document = PDDocument.load(inFile);
    try {
        File outFile;
        File expectedFile;

        if (bSort) {
            outFile = new File(outDir, inFile.getName() + "-sorted.txt");
            expectedFile = new File(inFile.getParentFile(), inFile.getName() + "-sorted.txt");
        } else {
            outFile = new File(outDir, inFile.getName() + ".txt");
            expectedFile = new File(inFile.getParentFile(), inFile.getName() + ".txt");
        }

        OutputStream os = new FileOutputStream(outFile);
        try {
            Writer writer = new OutputStreamWriter(os, ENCODING);
            try {
                //Allows for sorted tests 
                stripper.setSortByPosition(bSort);
                stripper.writeText(document, writer);
            } finally {
                // close the written file before reading it again
                writer.close();
            }
        } finally {
            os.close();
        }

        if (bLogResult) {
            log.info("Text for " + inFile.getName() + ":");
            log.info(stripper.getText(document));
        }

        if (!expectedFile.exists()) {
            this.bFail = true;
            fail("FAILURE: Input verification file: " + expectedFile.getAbsolutePath() + " did not exist");
            return;
        }

        LineNumberReader expectedReader = new LineNumberReader(
                new InputStreamReader(new FileInputStream(expectedFile), ENCODING));
        LineNumberReader actualReader = new LineNumberReader(
                new InputStreamReader(new FileInputStream(outFile), ENCODING));

        while (true) {
            String expectedLine = expectedReader.readLine();
            while (expectedLine != null && expectedLine.trim().length() == 0) {
                expectedLine = expectedReader.readLine();
            }
            String actualLine = actualReader.readLine();
            while (actualLine != null && actualLine.trim().length() == 0) {
                actualLine = actualReader.readLine();
            }
            if (!stringsEqual(expectedLine, actualLine)) {
                this.bFail = true;
                fail("FAILURE: Line mismatch for file " + inFile.getName() + " (sort = " + bSort + ")"
                        + " at expected line: " + expectedReader.getLineNumber() + " at actual line: "
                        + actualReader.getLineNumber() + "\nexpected line was: \"" + expectedLine + "\""
                        + "\nactual line was:   \"" + actualLine + "\"" + "\n");

                //lets report all lines, even though this might produce some verbose logging
                //break;
            }

            if (expectedLine == null || actualLine == null) {
                break;
            }
        }
        expectedReader.close();
        actualReader.close();
    } finally {
        document.close();
    }
}

From source file:fitnesserefactor.FitnesseRefactor.java

public int CountLines(File filename) throws FileNotFoundException, IOException {
    LineNumberReader reader = new LineNumberReader(new FileReader(filename));
    int cnt = 0;/*ww  w.j a  v  a2s.  co  m*/
    String lineRead = "";
    while ((lineRead = reader.readLine()) != null) {
    }
    cnt = reader.getLineNumber();
    reader.close();
    return cnt;
}

From source file:org.agnitas.util.AgnUtils.java

public static int getLineCountOfFile(File file) throws IOException {
    LineNumberReader lineNumberReader = null;
    try {/*from   w  w w. ja  v  a 2 s .  c  o m*/
        lineNumberReader = new LineNumberReader(new InputStreamReader(new FileInputStream(file)));
        while (lineNumberReader.readLine() != null) {
        }

        return lineNumberReader.getLineNumber();
    } finally {
        IOUtils.closeQuietly(lineNumberReader);
    }
}