Example usage for java.io LineNumberReader close

List of usage examples for java.io LineNumberReader close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Usage

From source file:org.jboss.as.test.integration.domain.suites.ResponseStreamTestCase.java

private void readLogStream(InputStream stream, boolean forServer, boolean forMaster) throws IOException {

    LineNumberReader reader = new LineNumberReader(new InputStreamReader(stream, StandardCharsets.UTF_8));

    String expected = LogStreamExtension.getLogMessage(logMessageContent);
    boolean readRegisteredServer = false;
    boolean readRegisteredSlave = false;
    boolean readExpected = false;
    String read;/*from   www  .jav a2s  .c om*/
    while ((read = reader.readLine()) != null) {
        readRegisteredServer = readRegisteredServer || read.contains("WFLYHC0020");
        readRegisteredSlave = readRegisteredSlave || read.contains("WFLYHC0019");
        readExpected = readExpected || read.contains(expected);
    }

    if (forServer) {
        Assert.assertFalse(readRegisteredServer);
    } else if (forMaster) {
        Assert.assertTrue(readRegisteredSlave);
    } else {
        Assert.assertFalse(readRegisteredSlave);
        Assert.assertTrue(readRegisteredServer);
    }
    Assert.assertTrue(readExpected);

    reader.close();

}

From source file:org.kalypso.model.wspm.tuhh.schema.simulation.BuildingPolygonReader.java

public void read(final File buildingFile) throws IOException {
    LineNumberReader reader = null;
    try {// www .  j  a va  2  s .  co m
        reader = new LineNumberReader(new FileReader(buildingFile));

        /* Ingore first line */
        if (reader.ready())
            reader.readLine();

        while (reader.ready()) {
            final String line = reader.readLine();
            if (line == null)
                break;

            try {
                readBuildingLine(line.trim(), buildingFile);
            } catch (final NumberFormatException nfe) {
                /* A good line but bad content. Give user a hint that something might be wrong. */
                m_log.log(false,
                        Messages.getString(
                                "org.kalypso.model.wspm.tuhh.schema.simulation.PolynomeProcessor.25"), //$NON-NLS-1$
                        buildingFile.getName(), reader.getLineNumber(), nfe.getLocalizedMessage());
            } catch (final Throwable e) {
                // should never happen
                m_log.log(e,
                        Messages.getString(
                                "org.kalypso.model.wspm.tuhh.schema.simulation.PolynomeProcessor.25"), //$NON-NLS-1$
                        buildingFile.getName(), reader.getLineNumber(), e.getLocalizedMessage());
            }

        }
        reader.close();
    } finally {
        IOUtils.closeQuietly(reader);
    }
}

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

/**
 * Parses the commands from the supplied commands file.
 *
 * @param inFile the file path/*from w ww.j  a v a 2 s.c o  m*/
 *
 * @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.agnitas.web.ImportWizardForm.java

/**
 * Tries to read csv file Reads database column structure reads first line
 * splits line into tokens/*from   w  ww .  ja v a2  s.  c  o m*/
 */
protected ActionErrors parseFirstline(HttpServletRequest req) {
    ApplicationContext aContext = this.getWebApplicationContext();
    DataSource ds = (DataSource) aContext.getBean("dataSource");
    String csvString = new String("");
    String firstline = null;
    ActionErrors errors = new ActionErrors();
    int colNum = 0;

    // try to read csv file:
    try {
        csvString = new String(this.getCsvFile().getFileData(), status.getCharset());
    } catch (Exception e) {
        AgnUtils.logger().error("parseFirstline: " + e);
        errors.add("global", new ActionMessage("error.import.charset"));
        return errors;
    }

    if (csvString.length() == 0) {
        errors.add("global", new ActionMessage("error.import.no_file"));
    }

    // read out DB column structure:
    this.readDBColumns(this.getCompanyID(req), ds);
    this.csvAllColumns = new ArrayList();
    LineNumberReader aReader = new LineNumberReader(new StringReader(csvString));

    try {
        // read first line:
        if ((firstline = aReader.readLine()) != null) {
            aReader.close(); // 

            // split line into tokens:
            CsvTokenizer st = new CsvTokenizer(firstline, status.getSeparator(), status.getDelimiter());
            String curr = "";
            CsvColInfo aCol = null;
            List<String> tempList = new ArrayList<String>();
            while ((curr = st.nextToken()) != null) {

                // curr = (String)st.nextElement();
                curr = curr.trim();
                curr = curr.toLowerCase();
                aCol = new CsvColInfo();
                aCol.setName(curr);
                aCol.setActive(false);
                aCol.setType(CsvColInfo.TYPE_UNKNOWN);

                // add column to csvAllColumns:
                if (!tempList.contains(aCol.getName())) {
                    tempList.add(aCol.getName());
                } else {
                    errors.add("global", new ActionMessage("error.import.column"));
                }
                csvAllColumns.add(aCol);
                colNum++;
                this.csvMaxUsedColumn = colNum;
            }
        }

    } catch (Exception e) {
        AgnUtils.logger().error("parseFirstline: " + e);
    }

    return errors;
}

From source file:org.chenillekit.demo.components.LeftSideMenu.java

/**
 * build the menu item list.//w ww.j a  v a 2s .c  om
 *
 * @return list of menu items
 */
private List<MenuConfiguration> buildMenuItemList() {
    List<MenuConfiguration> menuEntryList = CollectionFactory.newList();
    LineNumberReader lineNumberReader = null;

    try {
        lineNumberReader = new LineNumberReader(new FileReader(new File(configFile.toURL().toURI())));

        String readedLine;
        while ((readedLine = lineNumberReader.readLine()) != null) {
            String[] values = StringUtils.split(readedLine, '|');
            if (!values[0].equalsIgnoreCase("separator")) {
                Object[] contextParameters = null;
                if (values.length == 4 && parameters != null) {
                    String[] placeHolders = values[3].split(",");
                    contextParameters = new Object[placeHolders.length];
                    for (int i = 0; i < placeHolders.length; i++) {
                        String placeHolder = placeHolders[i];
                        contextParameters[i] = parameters.get(placeHolder);
                    }
                }

                menuEntryList.add(new MenuConfiguration(values[0].trim(), values[1].trim(), values[2].trim(),
                        contextParameters));
            } else
                menuEntryList.add(new MenuConfiguration());
        }

        return menuEntryList;
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            if (lineNumberReader != null)
                lineNumberReader.close();
        } catch (IOException e) {
        }
    }
}

From source file:lineage2.gameserver.Config.java

/**
 * Method abuseLoad./*from  w w w  .j  ava2s.  c o  m*/
 */
public static void abuseLoad() {
    List<Pattern> tmp = new ArrayList<Pattern>();
    LineNumberReader lnr = null;
    try {
        String line;
        lnr = new LineNumberReader(new InputStreamReader(new FileInputStream(ANUSEWORDS_CONFIG_FILE), "UTF-8"));
        while ((line = lnr.readLine()) != null) {
            StringTokenizer st = new StringTokenizer(line, "\n\r");
            if (st.hasMoreTokens()) {
                tmp.add(Pattern.compile(".*" + st.nextToken() + ".*",
                        Pattern.DOTALL | Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE));
            }
        }
        ABUSEWORD_LIST = tmp.toArray(new Pattern[tmp.size()]);
        tmp.clear();
        _log.info("Abuse: Loaded " + ABUSEWORD_LIST.length + " abuse words.");
    } catch (IOException e1) {
        _log.warn("Error reading abuse: " + e1);
    } finally {
        try {
            if (lnr != null) {
                lnr.close();
            }
        } catch (Exception e2) {
        }
    }
}

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 av  a 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.latticesoft.util.common.FileUtil.java

/**
 * Read lines from an inputstream.//from   w  w w  . j  a  v a  2s  . co m
 * @param is the InputStream
 * @param close if set to true, after reading the input stream would be closed.
 * @param start the line of the file to read from. Line starts from 0. 
 * If count is 1, 1 line would be skipped.
 * @param end the line of the file to stop reading. The end line is included.
 * @return an collection of the lines read
 */
public static List readLinesFromStream(InputStream is, boolean close, int start, int end) {
    if (is == null) {
        return null;
    }
    ArrayList a = new ArrayList();
    Reader r = null;
    LineNumberReader lr = null;
    try {
        r = new InputStreamReader(is);
        lr = new LineNumberReader(r);
        String line = null;
        do {
            line = lr.readLine();
            int currLine = lr.getLineNumber();
            if (start > 0 && end > 0 && currLine >= start && currLine <= end) {
                if (line != null) {
                    a.add(line);
                }
            }
            if (start == START_OF_FILE && end == END_OF_FILE) {
                if (line != null) {
                    a.add(line);
                }
            }
            if (end > 0 && currLine > end) {
                break;
            }
        } while (line != null);
    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error(e);
        }
    } finally {
        if (close) {
            try {
                lr.close();
            } catch (Exception e) {
            }
            try {
                r.close();
            } catch (Exception e) {
            }
        }
        lr = null;
        r = null;
    }
    return a;
}

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
 *///w  w  w.j a v a2 s.  com
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:org.agnitas.web.ImportWizardForm.java

/**
 * read all lines of the file/*from  w w w.  j a  v  a 2  s .c  o m*/
 * @param aForm
 * @param req
 * @return
 * @throws IOException
 */
public int getLinesOKFromFile(HttpServletRequest req) throws IOException {
    String csvString = new String(this.getCsvFile().getFileData(), this.getStatus().getCharset());
    LineNumberReader aReader = new LineNumberReader(new StringReader(csvString));
    String myline = "";
    int linesOK = 0;
    this.getUniqueValues().clear();
    aReader.readLine(); // skip header
    while ((myline = aReader.readLine()) != null) {
        if (myline.trim().length() > 0) {
            if (this.parseLine(myline,
                    (Locale) req.getSession().getAttribute(org.apache.struts.Globals.LOCALE_KEY)) != null) {
                linesOK++;
            }
        }
    }
    aReader.close();
    return linesOK;
}