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:de.innovationgate.wgpublisher.design.fs.AbstractDesignFile.java

protected String readCode(DesignMetadata md) throws FileNotFoundException, IOException, WGDesignSyncException,
        InstantiationException, IllegalAccessException {

    // No, filecontainers have no code, but thanks for asking....
    if (getType() == WGDocument.TYPE_FILECONTAINER) {
        return null;
    }/*w  ww . ja  va 2s  .  c o  m*/

    FileObject codeFile = getCodeFile();
    if (!codeFile.exists()) {
        throw new WGDesignSyncException("Code of file '" + getCodeFile().getName().getPath()
                + "' could not be read because the file does not exist.");
    }

    LineNumberReader reader = new LineNumberReader(createReader(codeFile));
    StringWriter writer = new StringWriter();
    int headerLines = 0;
    try {
        String line;
        boolean lookForHeaders = true;
        boolean firstLine = true;

        while ((line = reader.readLine()) != null) {
            if (lookForHeaders == true && line.startsWith("##")) {
                processDesignHeader(line, md.getInfo());
                headerLines++;
            } else {
                lookForHeaders = false;

                if (!firstLine) {
                    writer.write("\n");
                } else {
                    firstLine = false;
                }

                writer.write(line);
            }
        }
    } finally {
        reader.close();
        codeFile.getContent().close();
    }
    writer.close();
    md.setHeaderLines(headerLines);
    String code = writer.toString();
    return code;
}

From source file:com.espertech.esper.example.trivia.TriviaMain.java

private List<String> parseLines(String testdata) {
    List<String> result = new ArrayList<String>();
    StringReader buf = new StringReader(testdata);
    LineNumberReader reader = new LineNumberReader(buf);
    try {/*from  w ww .j av  a2s .  c  o m*/
        while (true) {
            String line = reader.readLine();
            if (line == null) {
                break;
            }
            result.add(line);
        }
    } catch (IOException ex) {
        throw new RuntimeException("Failed to parse lines: " + ex.getMessage(), ex);
    }
    return result;
}

From source file:org.kalypso.wspwin.core.WspCfg.java

private IStatus readWspCfg(final File profDir, final Collection<ZustandBean> zustandBeans) {
    final File wspCfgFile = new File(profDir, WspWinFiles.WSP_CFG);

    try (LineNumberReader reader = new LineNumberReader(new FileReader(wspCfgFile))) {
        final String firstLine = reader.readLine();
        if (firstLine == null || firstLine.length() == 0)
            return new Status(IStatus.ERROR, KalypsoWspWinCorePlugin.PLUGIN_ID,
                    Messages.getString("org.kalypso.wspwin.core.WspCfg.1")); //$NON-NLS-1$

        // ignore the values, we read the count from the linecount
        // just parse the type
        final char type = firstLine.charAt(firstLine.length() - 1);
        setType(type);/*  w w  w .  j  a  v  a  2s.c om*/

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

            final String trimmedLine = line.trim();
            if (trimmedLine.length() == 0 || trimmedLine.length() < 85)
                continue;

            try {
                final String waterName = trimmedLine.substring(0, 15).trim();
                final String name = trimmedLine.substring(15, 30).trim();
                // normally it should always be german, but it depends on the wspwin installation
                final DateFormat dateInstance = SimpleDateFormat.getDateInstance(SimpleDateFormat.SHORT,
                        Locale.GERMAN);
                final String dateString = trimmedLine.substring(30, 41).trim();
                final Date date = dateInstance.parse(dateString);
                final BigDecimal start = new BigDecimal(trimmedLine.substring(41, 56).trim());
                final BigDecimal end = new BigDecimal(trimmedLine.substring(56, 71).trim());
                final String fileName = trimmedLine.substring(71).trim();

                final ZustandBean zustandBean = new ZustandBean(name, waterName, fileName, start, end, date);
                zustandBeans.add(zustandBean);
            } catch (final NumberFormatException e) {
                e.printStackTrace();
                throw new ParseException(
                        Messages.getString("org.kalypso.wspwin.core.WspCfg.3", reader.getLineNumber()), //$NON-NLS-1$
                        reader.getLineNumber());
            }
        }

        return Status.OK_STATUS;
    } catch (final ParseException | IOException e) {
        return new Status(IStatus.ERROR, KalypsoWspWinCorePlugin.PLUGIN_ID, e.getLocalizedMessage(), e);
    }
}

From source file:com.castis.sysComp.PoisConverterSysComp.java

public void parseViewCountFile(File file) throws Exception {
    String line = "";
    FileInputStream in = null;// w  w w.j av  a  2  s  . c om
    Reader isReader = null;
    LineNumberReader bufReader = null;
    if (file.getName().contains("channel")) {
        type = "channel";
    } else {
        type = "vod";
    }

    try {
        String encodingCharset = FILE_CHARSET;

        in = new FileInputStream(file);
        isReader = new InputStreamReader(in, encodingCharset);
        bufReader = new LineNumberReader(isReader);

        boolean first = true;

        while ((line = bufReader.readLine()) != null) {
            if (line.length() == 0) {
                continue;
            }

            InputDataDTO data = new InputDataDTO();
            String result[] = line.split("\\|");
            if (first == true && result.length <= 1) {
                first = false;
                continue;
            }

            if (result[0] == null || result[0].equals("")) {
                throw new DataParsingException("data parsing error(region)");
            }

            if (result[1] == null || result[1].equals("")) {
                throw new DataParsingException("data parsing error(category)");
            }

            if (result[2] == null || result[2].equals("")) {
                throw new DataParsingException("data parsing error(weekday)");
            }

            if (result[3] == null || result[3].equals("")) {
                throw new DataParsingException("data parsing error(hour)");
            }

            if (result[4] == null || result[4].equals("")) {
                throw new DataParsingException("data parsing error(platform)");
            }

            if (result[5] == null || result[5].equals("")) {
                throw new DataParsingException("data parsing error(count)");
            }

            String platform = result[4];

            if (platform != null && platform.equalsIgnoreCase("stb"))
                platform = "STB";
            else if (platform != null && platform.equalsIgnoreCase("mobile")) {
                platform = "Mobile";
            }
            data.setPlatform(platform);

            List<TreeNodeDTO> tree = treeMap.get(platform);

            if (tree == null) {
                tree = getAxis(platform);
                treeMap.put(platform, tree);
            }

            String fullpath = getFullPath(tree, result[0]);

            if (fullpath == "") {
                throw new DataParsingException("region ID[" + result[0] + "] can't find fullpath.");
            }

            data.setRegion(fullpath);
            data.setCategory(result[1]);
            data.setWeekday(result[2]);
            data.setHour(result[3]);
            data.setCount(Integer.parseInt(result[5]));

            insertTreeNode(data);
        }

        for (WeekHourPair key : trees.keySet()) {
            Map<String, TreeNodeForCount> map = trees.get(key);
            calculateCount(map);
        }

        writeFile(file);

    } catch (Exception e) {
        String errorMsg = "Fail to parsing Line.[current line(" + bufReader.getLineNumber() + ") :" + line
                + "] : ";
        log.error(errorMsg, e);
        throw new DataParsingException(errorMsg, e); //throw(e);

    } finally {
        if (in != null)
            in.close();
        if (isReader != null)
            isReader.close();
        if (bufReader != null)
            bufReader.close();
    }
}

From source file:net.ontopia.persistence.rdbms.CSVImport.java

public void importCSV(InputStream csvfile) throws Exception {
    // Execute statements
    try {/*from   www.j a v a  2s.c  om*/

        String[] qmarks = new String[columns.length];
        for (int i = 0; i < qmarks.length; i++) {
            qmarks[i] = "?";
        }

        if (cleartable) {
            String delsql = "delete from " + table;
            Statement delstm = conn.createStatement();
            delstm.executeUpdate(delsql);
            //! conn.commit();
        }

        String sql = "insert into " + table + " (" + StringUtils.join(columns, ", ") + ") values ("
                + StringUtils.join(qmarks, ", ") + ")";
        log.debug("SQL: " + sql);
        PreparedStatement stm = conn.prepareStatement(sql);

        int datatypes[] = new int[columns.length];
        for (int i = 0; i < columns.length; i++) {
            Table tbl = project.getTableByName(table);
            if (tbl == null)
                throw new OntopiaRuntimeException("Unknown table: " + table);
            Column col = tbl.getColumnByName(columns[i]);
            if (col == null)
                throw new OntopiaRuntimeException("Unknown table column: " + columns[i]);
            if (col.getType() == null)
                throw new OntopiaRuntimeException("Column type is null: " + col.getType());
            DataType datatype = project.getDataTypeByName(col.getType(), "generic");
            if (datatype == null)
                throw new OntopiaRuntimeException("Unknown column type: " + col.getType());
            String dtype = datatype.getType();
            if ("varchar".equals(dtype))
                datatypes[i] = Types.VARCHAR;
            else if ("integer".equals(dtype))
                datatypes[i] = Types.INTEGER;
            else
                throw new OntopiaRuntimeException("Unknown datatype: " + dtype);
        }

        LineNumberReader reader = new LineNumberReader(new InputStreamReader(csvfile));

        // Ignore first X lines
        for (int i = 0; i < ignorelines; i++) {
            String line = reader.readLine();
            if (line == null)
                break;
        }

        // Process input
        log.debug("[" + StringUtils.join(columns, ", ") + "]");
        int lineno = 0;
        while (true) {
            lineno++;
            String line = reader.readLine();
            if (line == null)
                break;
            try {
                String[] cols = StringUtils.split(line, separator);
                if (cols.length > columns.length && !ignorecolumns)
                    log.debug("Ignoring columns: " + (columns.length + 1) + "-" + cols.length + " '" + line
                            + "'");
                log.debug("CVALUES: " + (columns.length + 1) + "-" + cols.length + " '" + line + "'");

                String dmesg = "(";
                for (int i = 0; i < columns.length; i++) {
                    String col = cols[i];
                    // If first column character is '"' strip quotes.
                    if (stripquotes) {
                        int len = col.length();
                        if (len > 1 && ((col.charAt(0) == '"' && col.charAt(len - 1) == '"')
                                || (col.charAt(0) == '\'' && col.charAt(len - 1) == '\'')))
                            col = col.substring(1, len - 1);
                    }
                    if (col != null && col.equals(""))
                        col = null;

                    dmesg = dmesg + col;
                    if (i < columns.length - 1)
                        dmesg = dmesg + ", ";
                    stm.setObject(i + 1, col, datatypes[i]);
                }
                dmesg = dmesg + ")";
                log.debug(dmesg);
                stm.execute();
            } catch (Exception e) {
                conn.rollback();
                throw new OntopiaRuntimeException("Cannot read line " + lineno + ": '" + line + "'", e);
            }
        }
        conn.commit();
    } finally {
        if (conn != null)
            conn.close();
    }
}

From source file:org.apache.cocoon.generation.TextGenerator.java

/**
 * Generate XML data.//from   w  w w  . j a  v a  2 s.c  o m
 *
 * @throws IOException
 * @throws ProcessingException
 * @throws SAXException
 */
public void generate() throws IOException, SAXException, ProcessingException {
    InputStreamReader in = null;

    try {
        final InputStream sis = this.inputSource.getInputStream();
        if (sis == null) {
            throw new ProcessingException("Source '" + this.inputSource.getURI() + "' not found");
        }

        if (encoding != null) {
            in = new InputStreamReader(sis, encoding);
        } else {
            in = new InputStreamReader(sis);
        }
    } catch (SourceException se) {
        throw new ProcessingException("Error during resolving of '" + this.source + "'.", se);
    }

    LocatorImpl locator = new LocatorImpl();

    locator.setSystemId(this.inputSource.getURI());
    locator.setLineNumber(1);
    locator.setColumnNumber(1);

    contentHandler.setDocumentLocator(locator);
    contentHandler.startDocument();
    contentHandler.startPrefixMapping("", URI);

    AttributesImpl atts = new AttributesImpl();
    if (localizable) {
        atts.addAttribute("", "source", "source", "CDATA", locator.getSystemId());
        atts.addAttribute("", "line", "line", "CDATA", String.valueOf(locator.getLineNumber()));
        atts.addAttribute("", "column", "column", "CDATA", String.valueOf(locator.getColumnNumber()));
    }

    contentHandler.startElement(URI, "text", "text", atts);

    LineNumberReader reader = new LineNumberReader(in);
    String line;
    String newline = null;

    while (true) {
        if (newline == null) {
            line = convertNonXmlChars(reader.readLine());
        } else {
            line = newline;
        }
        if (line == null) {
            break;
        }
        newline = convertNonXmlChars(reader.readLine());
        if (newline != null) {
            line += SystemUtils.LINE_SEPARATOR;
        }
        locator.setLineNumber(reader.getLineNumber());
        locator.setColumnNumber(1);
        contentHandler.characters(line.toCharArray(), 0, line.length());
        if (newline == null) {
            break;
        }
    }
    reader.close();
    contentHandler.endElement(URI, "text", "text");
    contentHandler.endPrefixMapping("");
    contentHandler.endDocument();
}

From source file:com.jkoolcloud.tnt4j.streams.configure.state.AbstractFileStreamStateHandler.java

/**
 * Check if file has persisted state defined line and returns corresponding line number in file.
 *
 * @param file/*w w  w .j a v  a  2s  . co  m*/
 *            file to find line matching CRC
 * @param fileAccessState
 *            persisted streamed files access state
 *
 * @return line number matching CRC, or {@code 0} if line not found
 *
 * @throws IOException
 *             if I/O exception occurs
 */
int checkLine(T file, FileAccessState fileAccessState) throws IOException {
    LineNumberReader reader = null;
    try {
        reader = new LineNumberReader(openFile(file));
        // skip lines until reaching line with number: persisted line number
        // - LINE_SHIFT_TOLERANCE
        int lastAccessedLine = getLastReadLineNumber();

        int startCompareLineIndex = lastAccessedLine - LINE_SHIFT_TOLERANCE;
        int endCompareLineIndex = lastAccessedLine + LINE_SHIFT_TOLERANCE;
        String line;
        int li = 0;
        while (((line = reader.readLine()) != null) && (li <= endCompareLineIndex)) {
            li = reader.getLineNumber();

            if (li >= startCompareLineIndex) {
                if (checkCrc(line, fileAccessState.currentLineCrc)) {
                    return li;
                }
            }
        }
    } finally {
        Utils.close(reader);
    }

    return 0;
}

From source file:scott.barleydb.test.TestBase.java

public static void executeScript(String script, boolean continueOnError) throws Exception {
    System.out.println("EXECUTING SCRIPT " + script);
    LineNumberReader in = new LineNumberReader(
            new InputStreamReader(new ClassPathResource(script).getInputStream(), "UTF-8"));
    List<String> statements = new LinkedList<>();
    JdbcTestUtils.splitSqlScript(JdbcTestUtils.readScript(in), ';', statements);
    try (Connection c = dataSource.getConnection();) {
        c.setAutoCommit(false);/*from  w  w  w.j  a  v  a  2 s.co m*/
        try (Statement s = c.createStatement();) {
            for (String line : statements) {
                try {
                    s.addBatch(line);
                } catch (Exception x) {
                    if (!continueOnError) {
                        c.rollback();
                        throw x;
                    }
                    System.err.println(x.getMessage());
                }
            }
            try {
                s.executeBatch();
            } catch (Exception x) {
                if (!continueOnError) {
                    c.rollback();
                    throw x;
                }
                System.err.println(x.getMessage());
            }
            c.commit();
        }
    } catch (Exception x) {
        if (!continueOnError)
            throw x;
    }
    System.out.println("FINISHED EXECUTING SCRIPT " + script);
}

From source file:com.smartgwt.extensions.fileuploader.server.TestServiceImpl.java

/**
 * This files a test file that contains a response for all CRUD operations. See example
 * profile.xq.xml file.//from   w w  w.ja va  2  s . c  o  m
 * @param out
 * @param context
 * @param model
 * @param xq
 * @param op
 * @throws Exception
 */
private void getResponse(PrintWriter out, String context, String model, String xq, String op) throws Exception {
    String path = "src/test/webapp/WEB-INF/models/" + model + "/" + xq + ".xml";
    System.out.println("getting datafile " + path);
    LineNumberReader in = null;
    File f = new File(path);
    if (!f.exists()) {
        System.out.println("File not found:" + path);
        out.println("<response>");
        out.println("  <status>1</status");
        out.println("</response>");
        return;
    }
    try {
        String start = "<" + op + ">";
        String end = "</" + op + ">";
        in = new LineNumberReader(new FileReader(f));
        String line = null;
        boolean inOp = false;
        while ((line = in.readLine()) != null) {
            if (line.indexOf(start) > 0)
                inOp = true;
            else if (line.indexOf(end) > 0)
                inOp = false;
            else if (inOp)
                out.println(line);
            //System.out.println(line);
        }
    } catch (FileNotFoundException fnf) {
        throw new Exception(fnf);
    } finally {
        if (in != null)
            try {
                in.close();
            } catch (Exception e) {
            }
        ;
    }
}

From source file:FinalProject.Employee_Login.java

private void Submit_ButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Submit_ButtonActionPerformed
    String Password = Arrays.toString(Password_Input.getPassword());
    String password = Password.replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("\\, ", "");
    String username = Employee_Input.getText();

    try {/*from   w w  w .j a  v  a  2 s . c  o  m*/
        File user = new File("Username.txt");
        File pass = new File("Password.txt");
        Scanner scanner = new Scanner(user);
        FileReader frU = new FileReader(user);
        LineNumberReader u = new LineNumberReader(frU);
        FileReader frP = new FileReader(pass);
        LineNumberReader p = new LineNumberReader(frP);

        int linenumberU = 0;
        while (scanner.hasNextLine() && u.readLine() != null) {
            linenumberU++;
            String lineFromFile = scanner.nextLine();

            if (lineFromFile.contains(username)) // a match!
            {
                break;
            }
        }

        String pssLine = (String) FileUtils.readLines(pass).get(linenumberU - 1);
        String usrLine = (String) FileUtils.readLines(user).get(linenumberU - 1);

        if (username.equals(usrLine) && password.equals(pssLine)) {
            this.setVisible(false);
            Employee_Interface f = new Employee_Interface();
            f.setVisible(true);
            f.ID_Number.setText(usrLine + "!");
        }

        else {
            Error_Message.setVisible(true);
        }

    } catch (FileNotFoundException ex) {
    } catch (IOException ex) {
    }
}