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:com.fujitsu.dc.common.ads.RollingAdsWriteFailureLog.java

/**
 * ??ADS????.//from  w  w  w  . j  av a  2 s. c om
 * @throws AdsWriteFailureLogException ADS????????
 */
public void openRotatedFile() throws AdsWriteFailureLogException {
    try {
        // default encoding(UTF-8)
        reader = new LineNumberReader(new BufferedReader(new FileReader(this.rotatedAdsWriteFailureLog)));
    } catch (FileNotFoundException e) {
        String messsage = String.format("Failed to open rotated adsWriteFailureLog. [%s]",
                rotatedAdsWriteFailureLog.getAbsolutePath());
        throw new AdsWriteFailureLogException(messsage, e);
    }
}

From source file:com.sunchenbin.store.feilong.core.io.IOReaderUtil.java

/**
 *  {@link LineNumberReaderResolver}? {@link Reader}.
 *
 * @param reader/*from w  w  w.  ja  v  a 2  s  .co m*/
 *            the reader
 * @param lineNumberReaderResolver
 *            the line number reader resolver
 * @since 1.4.1
 */
public static void resolverFile(Reader reader, LineNumberReaderResolver lineNumberReaderResolver) {
    LineNumberReader lineNumberReader = new LineNumberReader(reader);
    try {
        String line = null;
        while ((line = lineNumberReader.readLine()) != null) {
            int lineNumber = lineNumberReader.getLineNumber();
            lineNumberReaderResolver.excute(lineNumber, line);
        }
    } catch (IOException e) {
        LOGGER.error("", e);
        throw new UncheckedIOException(e);
    } finally {
        IOUtils.closeQuietly(lineNumberReader);
        IOUtils.closeQuietly(reader);
    }
}

From source file:org.apache.click.util.ErrorReport.java

/**
 * Create a ErrorReport instance from the given error and page.
 *
 * @param error the cause of the error/*w  w w. ja v a  2 s. c o m*/
 * @param pageClass the Page class which caused the error
 * @param isProductionMode the application is in "production" mode
 * @param request the page request
 * @param servletContext the servlet context
 */
public ErrorReport(Throwable error, Class<? extends Page> pageClass, boolean isProductionMode,
        HttpServletRequest request, ServletContext servletContext) {

    this.error = error;
    this.pageClass = pageClass;
    this.isProductionMode = isProductionMode;
    this.request = request;
    this.servletContext = servletContext;

    if (error instanceof TemplateException && ((TemplateException) error).isParseError()) {

        TemplateException te = (TemplateException) error;

        if (te.getTemplateName().charAt(0) == '/') {
            sourceName = te.getTemplateName();
        } else {
            sourceName = '/' + te.getTemplateName();
        }
        lineNumber = te.getLineNumber();
        columnNumber = te.getColumnNumber();

        InputStream is = servletContext.getResourceAsStream(sourceName);

        sourceReader = new LineNumberReader(new InputStreamReader(is));
        isParseError = true;

    } else {
        isParseError = false;
        sourceName = null;
        columnNumber = -1;

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        getCause().printStackTrace(pw);

        StringTokenizer tokenizer = new StringTokenizer(sw.toString(), "\n");

        try {
            tokenizer.nextToken();
            String line = tokenizer.nextToken();
            if (getCause() instanceof IllegalArgumentException) {
                line = tokenizer.nextToken();

                if (line.indexOf("org.apache.commons.lang.Validate") != -1) {
                    line = tokenizer.nextToken();
                }
            }

            int nameStart = line.indexOf("at ");
            int nameEnd = line.indexOf("(");
            nameEnd = line.lastIndexOf(".", nameEnd);
            if (line.indexOf("$") != -1) {
                nameEnd = line.indexOf("$");
            }

            if (nameStart != -1 && nameEnd != -1) {
                String classname = line.substring(nameStart + 3, nameEnd);

                int lineStart = line.indexOf(":");
                if (lineStart != -1) {
                    int lineEnd = line.indexOf(")");
                    String lineNumber = line.substring(lineStart + 1, lineEnd);

                    this.lineNumber = Integer.parseInt(lineNumber);

                    String filename = "/" + classname.replace('.', '/') + ".java";

                    sourceReader = getJavaSourceReader(filename);
                }
            }

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

From source file:com.novartis.opensource.yada.format.RESTResultDelimitedConverter.java

/**
 * Converts hierarchical data in a JSON result to a
 * {@link java.lang.StringBuffer} containing tabular data delimited
 * accordingly per request parameters/*from  w w  w .  ja va2s . c om*/
 * 
 * @param rs
 *          the result set to convert
 * @throws YADAConverterException 
 * @throws SQLException
 *           when {@link ResultSet} or {@link ResultSetMetaData} iteration
 *           fails
 */
protected void getDelimitedRows(Object result) throws YADAConverterException {
    String harm = (String) result;
    List<List<String>> convertedResults = new ArrayList<>();
    Harmonizer harmonizer = getHarmonizer();
    Object map = getHarmonyMap().toString();
    Object[] o = new Object[] { result, map };
    if (map != null) {
        harm = harmonizer.call(HARMONIZE, o);
    }
    o = new Object[] { harm };
    String delimited = harmonizer.call(FLATTEN, o), s = "";
    try (LineNumberReader lnr = new LineNumberReader(new StringReader(delimited))) {
        while ((s = lnr.readLine()) != null) {
            if (lnr.getLineNumber() == 1)
                this.yqr.setConvertedHeader(Arrays.asList(s.split(",")));
            else
                convertedResults.add(Arrays.asList(s.split(",")));
        }
    } catch (IOException e) {
        String msg = "Rhino javascript result could not be parsed.";
        throw new YADAConverterException(msg, e);
    }
    this.yqr.getConvertedResults().add(convertedResults);
}

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
 *//*ww w. ja va 2  s .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:org.openanzo.jdbc.opgen.ant.DDLTask.java

private void writeFile(Writer writer, String filename, String file, String outputFormat)
        throws FileNotFoundException, IOException {
    Reader in = new InputStreamReader(new FileInputStream(file), "UTF-8");
    LineNumberReader lnr = new LineNumberReader(in);
    StringBuilder content = new StringBuilder();
    String line;//from ww w.  ja v a2s .  c o  m
    while ((line = lnr.readLine()) != null) {
        line = StringUtils.trim(line);
        if (line.length() == 0 || line.startsWith("#"))
            continue;
        line = Pattern.compile("[\\s+]", Pattern.MULTILINE).matcher(line).replaceAll(" ");
        line = Pattern.compile(";+", Pattern.MULTILINE).matcher(line).replaceAll(";;");
        line = Pattern.compile("&sc", Pattern.MULTILINE).matcher(line).replaceAll(";");
        line = Pattern.compile("&plus", Pattern.MULTILINE).matcher(line).replaceAll("+");
        content.append(line);
        content.append(" ");
    }
    writer.write(content.toString());
    in.close();
    lnr.close();
}

From source file:org.springframework.test.jdbc.SimpleJdbcTestUtils.java

/**
 * Execute the given SQL script./*from  w  w w.j  a v  a 2 s  . co m*/
 * <p>The script will normally be loaded by classpath. There should be one statement
 * per line. Any semicolons will be removed. <b>Do not use this method to execute
 * DDL if you expect rollback.</b>
 * @param simpleJdbcTemplate the SimpleJdbcTemplate with which to perform JDBC operations
 * @param resource the resource (potentially associated with a specific encoding)
 * to load the SQL script from.
 * @param continueOnError whether or not to continue without throwing an
 * exception in the event of an error.
 * @throws DataAccessException if there is an error executing a statement
 * and continueOnError was {@code false}
 */
public static void executeSqlScript(SimpleJdbcTemplate simpleJdbcTemplate, EncodedResource resource,
        boolean continueOnError) throws DataAccessException {

    if (logger.isInfoEnabled()) {
        logger.info("Executing SQL script from " + resource);
    }

    long startTime = System.currentTimeMillis();
    List<String> statements = new LinkedList<String>();
    LineNumberReader reader = null;
    try {
        reader = new LineNumberReader(resource.getReader());
        String script = JdbcTestUtils.readScript(reader);
        char delimiter = ';';
        if (!JdbcTestUtils.containsSqlScriptDelimiters(script, delimiter)) {
            delimiter = '\n';
        }
        JdbcTestUtils.splitSqlScript(script, delimiter, statements);
        for (String statement : statements) {
            try {
                int rowsAffected = simpleJdbcTemplate.update(statement);
                if (logger.isDebugEnabled()) {
                    logger.debug(rowsAffected + " rows affected by SQL: " + statement);
                }
            } catch (DataAccessException ex) {
                if (continueOnError) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("SQL: " + statement + " failed", ex);
                    }
                } else {
                    throw ex;
                }
            }
        }
        long elapsedTime = System.currentTimeMillis() - startTime;
        if (logger.isInfoEnabled()) {
            logger.info("Done executing SQL scriptBuilder from " + resource + " in " + elapsedTime + " ms.");
        }
    } catch (IOException ex) {
        throw new DataAccessResourceFailureException("Failed to open SQL script from " + resource, ex);
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (IOException ex) {
            // ignore
        }

    }
}

From source file:org.commoncrawl.service.crawler.RobotRulesParser.java

/** command-line main for testing */
public static void main(String[] argv) {
    if (argv.length < 3) {
        System.out.println("Usage:");
        System.out.println("   java <robots-file> <url-file> <agent-name>+");
        System.out.println("");
        System.out.println("The <robots-file> will be parsed as a robots.txt file,");
        System.out.println("using the given <agent-name> to select rules.  URLs ");
        System.out.println("will be read (one per line) from <url-file>, and tested");
        System.out.println("against the rules.");
        System.exit(-1);//from ww w . j a  va2  s.  c  o  m
    }
    try {
        FileInputStream robotsIn = new FileInputStream(argv[0]);
        File testsInFile = new File(argv[1]);
        LineNumberReader testsIn = null;
        String singleTestLine = null;
        if (testsInFile.isFile())
            testsIn = new LineNumberReader(new FileReader(argv[1]));
        else
            singleTestLine = argv[1];

        String[] robotNames = new String[argv.length - 2];

        for (int i = 0; i < argv.length - 2; i++)
            robotNames[i] = argv[i + 2];

        ArrayList bufs = new ArrayList();
        byte[] buf = new byte[BUFSIZE];
        int totBytes = 0;

        int rsize = robotsIn.read(buf);
        while (rsize >= 0) {
            totBytes += rsize;
            if (rsize != BUFSIZE) {
                byte[] tmp = new byte[rsize];
                System.arraycopy(buf, 0, tmp, 0, rsize);
                bufs.add(tmp);
            } else {
                bufs.add(buf);
                buf = new byte[BUFSIZE];
            }
            rsize = robotsIn.read(buf);
        }

        byte[] robotsBytes = new byte[totBytes];
        int pos = 0;

        for (int i = 0; i < bufs.size(); i++) {
            byte[] currBuf = (byte[]) bufs.get(i);
            int currBufLen = currBuf.length;
            System.arraycopy(currBuf, 0, robotsBytes, pos, currBufLen);
            pos += currBufLen;
        }

        RobotRulesParser parser = new RobotRulesParser(robotNames);
        RobotRuleSet rules = parser.parseRules(robotsBytes, 0, robotsBytes.length);
        System.out.println("Rules:");
        System.out.println(rules);
        System.out.println();
        if (testsIn != null) {
            String testPath = testsIn.readLine().trim();
            while (testPath != null) {
                System.out.println((rules.isAllowed(testPath) ? "allowed" : "not allowed") + ":\t" + testPath);
                testPath = testsIn.readLine();
            }
        } else {
            System.out.println(
                    (rules.isAllowed(singleTestLine) ? "allowed" : "not allowed") + ":\t" + singleTestLine);
        }

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

From source file:edu.stanford.muse.index.NER.java

public static void readLocationNamesToSuppress() {
    String suppress_file = "suppress.locations.txt.gz";
    try {//  w w  w  . jav  a 2s . co  m
        InputStream is = new GZIPInputStream(NER.class.getClassLoader().getResourceAsStream(suppress_file));
        LineNumberReader lnr = new LineNumberReader(new InputStreamReader(is, "UTF-8"));
        while (true) {
            String line = lnr.readLine();
            if (line == null)
                break;
            StringTokenizer st = new StringTokenizer(line);
            if (st.hasMoreTokens()) {
                String s = st.nextToken();
                if (!s.startsWith("#"))
                    locationsToSuppress.add(s.toLowerCase());
            }
        }
        is.close();
    } catch (Exception e) {
        log.warn("Error: unable to read " + suppress_file);
        Util.print_exception(e);
    }
    log.info(locationsToSuppress.size() + " names to suppress as locations");
}

From source file:com.aionemu.commons.scripting.AionScriptEngineManager.java

public void executeScriptList(File list) throws IOException {
    if (list.isFile()) {
        LineNumberReader lnr = new LineNumberReader(new FileReader(list));
        String line;/*  w  ww.ja v a2 s .c o m*/
        File file;

        while ((line = lnr.readLine()) != null) {
            String[] parts = line.trim().split("#");

            if (parts.length > 0 && !parts[0].startsWith("#") && parts[0].length() > 0) {
                line = parts[0];

                if (line.endsWith("/**")) {
                    line = line.substring(0, line.length() - 3);
                } else if (line.endsWith("/*")) {
                    line = line.substring(0, line.length() - 2);
                }

                file = new File(SCRIPT_FOLDER, line);

                if (file.isDirectory() && parts[0].endsWith("/**")) {
                    this.executeAllScriptsInDirectory(file, true, 32);
                } else if (file.isDirectory() && parts[0].endsWith("/*")) {
                    this.executeAllScriptsInDirectory(file);
                } else if (file.isFile()) {
                    try {
                        this.executeScript(file);
                    } catch (ScriptException e) {
                        reportScriptFileError(file, e);
                    }
                } else {
                    log.warn("Failed loading: (" + file.getCanonicalPath() + ") @ " + list.getName() + ":"
                            + lnr.getLineNumber() + " - Reason: doesnt exists or is not a file.");
                }
            }
        }
        lnr.close();
    } else {
        throw new IllegalArgumentException(
                "Argument must be an file containing a list of scripts to be loaded");
    }
}