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.autentia.tnt.manager.data.MigrationManager.java

/**
 * @return the original database version
 * @throws com.autentia.tnt.manager.data.exception.DataException
 */// w  w w .  j av a  2s  . c  om
public Version upgradeDatabase() throws DataException {
    Version ret = null;
    Version db = null;
    Version code = Version.getApplicationVersion();
    Session ses = HibernateUtil.getSessionFactory().openSession();
    Connection con = ses.connection();
    Statement stmt = null;
    LineNumberReader file = null;
    String delimiter = ";";

    try {
        db = Version.getDatabaseVersion();
        ret = db.clone();
        log.info("upgradeDatabase - >>>> STARTING MIGRATION FROM " + db + " TO " + code + " <<<<");

        // Disable auto-commit (just in case...)
        log.info("upgradeDatabase - disabling auto commit");
        con.setAutoCommit(false);

        // Create statement
        stmt = con.createStatement();

        // While necessary, upgrade database
        while (db.compareTo(code, Version.MINOR) < 0) {
            log.info("upgradeDatabase - " + db);

            // Compose script name and open it
            String script = SCRIPT_PREFIX + db.toString(Version.MINOR) + SCRIPT_SUFFIX;
            log.info("upgradeDatabase - loading script " + script);
            InputStream sqlScript = Thread.currentThread().getContextClassLoader().getResourceAsStream(script);
            if (sqlScript == null) {
                throw FileNotFoundException(script);
            }
            file = new LineNumberReader(new InputStreamReader(new BufferedInputStream(sqlScript), "UTF-8"));
            int _c;

            // Add batched SQL sentences to statement
            StringBuilder sentence = new StringBuilder();
            String line;
            while ((line = file.readLine()) != null) {
                line = line.trim();
                if (!line.startsWith("--")) {
                    // Interpret "DELIMITER" sentences
                    if (line.trim().toUpperCase(Locale.ENGLISH).startsWith("DELIMITER")) {
                        delimiter = line.trim().substring("DELIMITER".length()).trim();
                    } else {
                        // Add line to sentence
                        if (line.endsWith(delimiter)) {
                            // Remove delimiter
                            String lastLine = line.substring(0, line.length() - delimiter.length());

                            // Append line to sentence
                            sentence.append(lastLine);

                            // Execute sentence
                            log.info(" " + sentence.toString());
                            stmt.addBatch(sentence.toString());

                            // Prepare new sentence
                            sentence = new StringBuilder();
                        } else {
                            // Append line to sentence
                            sentence.append(line);

                            // Append separator for next line
                            sentence.append(" ");
                        }
                    }
                }
            }

            // Execute batch
            log.info("upgradeDatabase - executing batch of commands");
            stmt.executeBatch();

            // Re-read database version
            Version old = db;
            db = Version.getDatabaseVersion(con);
            if (old.equals(db)) {
                throw new DataException("Script was applied but did not upgrade database: " + script);
            }
            log.info("upgradeDatabase - database upgraded to version " + db);
        }

        // Commit transaction
        log.info("upgradeDatabase - commiting changes to database");
        con.commit();

        // Report end of migration
        log.info("upgradeDatabase - >>>> MIGRATION SUCCESSFULLY FINISHED <<<<");
    } catch (Exception e) {
        log.error("upgradeDatabase - >>>> MIGRATION FAILED: WILL BE ROLLED BACK <<<<", e);
        try {
            con.rollback();
        } catch (SQLException e2) {
            log.error("upgradeDatabase - Error al realizar el rollback");
        }
        throw new DataException("Script was applied but did not upgrade database: ", e);
    } finally {
        if (file != null) {
            try {
                file.close();
            } catch (IOException e2) {
                log.error("upgradeDatabase - Error al cerrar el fichero de script ", e2);
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e2) {
                log.error("upgradeDatabase - Error al cerrar el statement");
            }
        }
        ses.close();
    }

    return ret;
}

From source file:eu.qualimaster.coordination.profiling.SimpleParser.java

/**
 * Parses the control file.// www. j  av a 2s .c  o m
 * 
 * @param file the file to read
 * @param considerImport whether imports shall be considered or ignored
 * @param profile the profile to be built
 * @return the actual data file (from {@link IProfile#getDataFile()} if not changed by imports)
 * @throws IOException if loading/parsing the control file fails
 */
private ParseResult parseControlFile(File file, boolean considerImport, IProfile profile) throws IOException {
    ParseResult result = new ParseResult();
    List<Integer> tmpTasks = new ArrayList<Integer>();
    List<Integer> tmpExecutors = new ArrayList<Integer>();
    List<Integer> tmpWorkers = new ArrayList<Integer>();
    result.addDataFile(profile.getDataFile());
    addDataFiles(profile.getDataFile().getParentFile(), result, profile, false);
    if (file.exists()) {
        LineNumberReader reader = new LineNumberReader(new FileReader(file));
        String line;
        do {
            line = reader.readLine();
            if (null != line) {
                line = line.trim();
                if (line.startsWith(IMPORT)) {
                    if (considerImport) {
                        handleImport(line, result, profile);
                    }
                } else if (line.startsWith(PROCESSING)) {
                    line = line.substring(PROCESSING.length()).trim();
                    parseList(line, TASKS, tmpTasks, INT_HELPER);
                    parseList(line, EXECUTORS, tmpExecutors, INT_HELPER);
                    parseList(line, WORKERS, tmpWorkers, INT_HELPER);
                } else if (line.startsWith(PARAMETER)) {
                    line = line.substring(PARAMETER.length()).trim();
                    parseParameter(line, profile, result);
                }
            }
        } while (null != line);
        reader.close();
    }
    result.merge(tmpTasks, tmpExecutors, tmpWorkers);
    return result;
}

From source file:org.kalypso.kalypsomodel1d2d.conv.RMA10S2GmlConv.java

private void parse(final Reader reader) throws IOException {
    Assert.throwIAEOnNullParam(reader, "inputStreamReader"); //$NON-NLS-1$

    m_handler.start();//from  w  ww.  j a  v  a 2 s .c o  m

    final LineNumberReader lnReader = new LineNumberReader(reader);

    for (String line = lnReader.readLine(); line != null; line = lnReader.readLine()) {
        if (m_monitor != null && m_monitor.isCanceled())
            throw new OperationCanceledException();

        if (line.length() < 2)
            continue;

        if (line.startsWith("FP")) //$NON-NLS-1$
            interpreteNodeLine(line);
        else if (line.startsWith("FE")) //$NON-NLS-1$
            interpreteElementLine(line);
        else if (line.startsWith("AR")) //$NON-NLS-1$
            interpreteArcLine(line);
        else if (line.startsWith("RK")) //$NON-NLS-1$
            interpreteRoughnessClassLine(line); //$NON-NLS-1$
        else if (line.startsWith("VA")) //$NON-NLS-1$
            interpreteResultLine(line, RMA10S2GmlConv.RESULTLINES.LINE_VA);
        else if (line.startsWith("VO")) //$NON-NLS-1$
            interpreteResultLine(line, RMA10S2GmlConv.RESULTLINES.LINE_VO);
        else if (line.startsWith("GA")) //$NON-NLS-1$
            interpreteResultLine(line, RMA10S2GmlConv.RESULTLINES.LINE_GA);
        else if (line.startsWith("GO")) //$NON-NLS-1$
            interpreteResultLine(line, RMA10S2GmlConv.RESULTLINES.LINE_GO);
        else if (line.startsWith("DA")) //$NON-NLS-1$
            interpreteTimeLine(line);
        else if (line.startsWith("TL")) //$NON-NLS-1$
            interprete1d2dJunctionElement(line);
        else if (line.startsWith("ZU")) //$NON-NLS-1$
            interpreteNodeInformationLine(line);
        else if (line.startsWith("JE")) //$NON-NLS-1$
            interpreteJunctionInformationLine(line);
        else if (line.startsWith("MM")) //$NON-NLS-1$
            interpretePolynomeMinMaxLine(line);
        else if (line.startsWith("PRA")) //$NON-NLS-1$
            interpretePolynomialRangesLine(line);
        else if (line.startsWith("AP")) //$NON-NLS-1$
            interpreteSplittedPolynomialsLine(line);
        else if (line.startsWith("PRQ")) //$NON-NLS-1$
            interpretePolynomialRangesLine(line);
        else if (line.startsWith("QP")) //$NON-NLS-1$
            interpreteSplittedPolynomialsLine(line);
        else if (line.startsWith("PRB")) //$NON-NLS-1$
            interpretePolynomialRangesLine(line);
        else if (line.startsWith("ALP")) //$NON-NLS-1$
            interpreteSplittedPolynomialsLine(line);
        else if (VERBOSE_MODE)
            System.out.println(Messages.getString("org.kalypso.kalypsomodel1d2d.conv.RMA10S2GmlConv.1") + line); //$NON-NLS-1$
    }

    // signal parsing stop
    m_handler.end();
}

From source file:com.googlecode.jweb1t.JWeb1TSearcherInMemory.java

private void initialize(final File baseDir) throws NumberFormatException, IOException {
    ngramCountMap = new HashMap<Integer, Long>();
    ngramDistinctCountMap = new HashMap<Integer, Long>();

    final File countFile = new File(baseDir, JWeb1TAggregator.AGGREGATED_COUNTS_FILE);
    if (countFile.exists()) {
        final LineNumberReader lineReader = new LineNumberReader(new FileReader(countFile));
        String line;/*from  w  w  w.j av a  2 s .c  om*/
        while ((line = lineReader.readLine()) != null) {
            final String[] parts = line.split("\t");

            if (parts.length != 3) {
                continue;
            }

            final int ngramSize = Integer.valueOf(parts[0]);
            final long ngramDistinctCount = Long.valueOf(parts[1]);
            final long ngramCount = Long.valueOf(parts[2]);

            ngramCountMap.put(ngramSize, ngramCount);
            ngramDistinctCountMap.put(ngramSize, ngramDistinctCount);
        }
        lineReader.close();
    }

}

From source file:tokyo.northside.jrst.AdvancedReader.java

/**
 * /*from w w  w  . j a  v  a 2  s .  co m*/
 * @param in the io reader
 */
public AdvancedReader(Reader in) {
    this.in = new LineNumberReader(in);
    buffer = new ArrayCharList();
}

From source file:com.marklogic.contentpump.ZipDelimitedJSONReader.java

protected boolean hasMoreEntryInZip() throws IOException {
    ByteArrayOutputStream byteArrayOStream;
    ZipInputStream zipIStream = (ZipInputStream) zipIn;

    while ((currZipEntry = zipIStream.getNextEntry()) != null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("ZipEntry: " + currZipEntry.getName());
        }/*from ww  w  .j  a v a 2 s . com*/
        if (currZipEntry.getSize() == 0) {
            continue;
        }
        subId = currZipEntry.getName();
        long size = currZipEntry.getSize();
        if (size == -1) {
            byteArrayOStream = new ByteArrayOutputStream();
        } else {
            byteArrayOStream = new ByteArrayOutputStream((int) size);
        }
        int numOfBytes = -1;
        while ((numOfBytes = zipIStream.read(buf, 0, buf.length)) != -1) {
            byteArrayOStream.write(buf, 0, numOfBytes);
        }
        configFileNameAsCollection(conf, file);
        instream = new InputStreamReader(new ByteArrayInputStream(byteArrayOStream.toByteArray()), encoding);
        byteArrayOStream.close();
        reader = new LineNumberReader(instream);
        return true;
    }
    return false;
}

From source file:edu.umn.msi.tropix.common.io.IOUtilsTest.java

@Test(groups = "unit")
public void lineReader() {
    final LineNumberReader reader = new LineNumberReader(new StringReader("Moo Cow\nMoo Cow 2"));
    assert ioUtils.readLine(reader).equals("Moo Cow");
}

From source file:org.opensha.commons.util.FileUtils.java

/**
 * Loads in each line to a text file into an ArrayList ( i.e. a vector ). Each
 * element in the ArrayList represents one line from the file.
 *
 * @param fileName                  File to load in
 * @return                          ArrayList each element one line from the file
 * @throws FileNotFoundException    If the filename doesn't exist
 * @throws IOException              Unable to read from the file
 *///from ww  w  .j  a  v  a 2s  .  c  o m
public static ArrayList<String> loadFile(String fileName, boolean skipBlankLines)
        throws FileNotFoundException, IOException {

    // Debugging
    String S = C + ": loadFile(): ";
    if (D)
        System.out.println(S + "Starting");
    if (D)
        System.out.println(S + fileName);
    // Allocate variables
    ArrayList<String> list = new ArrayList<String>();
    File f = new File(fileName);

    // Read in data if it exists
    if (f.exists()) {

        if (D)
            System.out.println(S + "Found " + fileName + " and loading.");

        boolean ok = true;
        int counter = 0;
        String str;
        FileReader in = new FileReader(fileName);
        LineNumberReader lin = new LineNumberReader(in);

        while (ok) {
            try {
                str = lin.readLine();

                if (str != null) {
                    //omit the blank line
                    if (skipBlankLines && str.trim().equals(""))
                        continue;

                    list.add(str);
                    if (D) {
                        System.out.println(S + counter + ": " + str);
                        counter++;
                    }
                } else
                    ok = false;
            } catch (IOException e) {
                ok = false;
            }
        }
        lin.close();
        in.close();

        if (D)
            System.out.println(S + "Read " + counter + " lines from " + fileName + '.');

    } else if (D)
        System.out.println(S + fileName + " does not exist.");

    // Done
    if (D)
        System.out.println(S + "Ending");
    return list;

}

From source file:org.guzz.config.LocalFileConfigServer.java

/**
 * A file contains the paths of all resource files separated by new lines.
 * A resource file name starts with a star(*) makes it a optional one.
 * Lines start with # is treated as comments.
 *//*w  w  w .  j a va2  s  . c  o  m*/
public void setResourceList(Resource r) {
    LineNumberReader lr = null;
    try {
        lr = new LineNumberReader(new InputStreamReader(r.getInputStream(), "UTF-8"));
        String line = null;

        while ((line = lr.readLine()) != null) {
            line = line.trim();

            if (line.length() == 0)
                continue;
            if (line.startsWith("#"))
                continue;

            boolean resourceMustBeValid = true;

            if (line.charAt(0) == '*') {
                line = line.substring(1);
                resourceMustBeValid = false;
            }

            this.addResource(new FileResource(r, line), resourceMustBeValid);
        }
    } catch (UnsupportedEncodingException e) {
        throw new InvalidConfigurationException(r.toString(), e);
    } catch (IOException e) {
        throw new InvalidConfigurationException(r.toString(), e);
    } finally {
        CloseUtil.close(lr);
    }
}

From source file:ru.jkff.antro.ProfileListener.java

private Map<String, AnnotatedFile> getAnnotatedFiles() {
    Map<String, AnnotatedFile> res = new HashMap<String, AnnotatedFile>();

    Map<OurLocation, Stat> statsByLoc = getStatsByLocation();
    for (String file : getUsedBuildFiles()) {
        List<String> lines = new ArrayList<String>();
        List<Stat> stats = new ArrayList<Stat>();

        try {/*from   w w w  . ja v  a  2 s  .c om*/
            LineNumberReader r = new LineNumberReader(new FileReader(file));
            String line;
            while (null != (line = r.readLine())) {
                OurLocation loc = new OurLocation(file, r.getLineNumber());

                Stat stat = statsByLoc.get(loc);
                lines.add(line);
                stats.add(stat);
            }
        } catch (IOException e) {
        }

        res.put(file, new AnnotatedFile(lines.toArray(new String[0]), stats.toArray(new Stat[0]), file));
    }

    return res;
}