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:com.jkoolcloud.tnt4j.streams.utils.Utils.java

/**
 * Counts text lines available in input.
 *
 * @param reader/*from ww w.ja v  a2 s  .  c o  m*/
 *            a {@link java.io.Reader} object to provide the underlying input stream
 * @return number of lines currently available in input
 * @throws java.io.IOException
 *             If an I/O error occurs
 * @deprecated use {@link #countLines(java.io.InputStream)} instead
 */
@Deprecated
public static int countLines(Reader reader) throws IOException {
    int lCount = 0;
    LineNumberReader lineReader = null;
    try {
        lineReader = new LineNumberReader(reader);
        lineReader.skip(Long.MAX_VALUE);
        // NOTE: Add 1 because line index starts at 0
        lCount = lineReader.getLineNumber() + 1;
    } finally {
        close(lineReader);
    }

    return lCount;
}

From source file:org.eclipse.ice.client.widgets.moose.MOOSEFormEditor.java

/**
 * This private method is used to decide whether or not the given
 * ICEResource contains valid Postprocessor data to plot. Basically, for now
 * it naively checks that there is more than one line in the file, because
 * if there was 1 or less, then we would have no data or just the feature
 * line describing the data.//from   w w w  .  j a  v a  2 s  . co  m
 * 
 * @param r
 * @return validData Whether or not there is valid data in the resource
 */
private boolean hasValidPostprocessorData(ICEResource r) {

    // Simply count the number of lines in the resource file
    try {
        LineNumberReader reader = new LineNumberReader(new FileReader(r.getPath().getPath()));
        int cnt = 0;
        String lineRead = "";
        while ((lineRead = reader.readLine()) != null) {
        }

        cnt = reader.getLineNumber();
        reader.close();

        if (cnt <= 1) {
            return false;
        } else {
            return true;
        }
    } catch (IOException e) {
        logger.error(getClass().getName() + " Exception!", e);
        return false;
    }
}

From source file:org.kalypso.ogc.sensor.timeseries.wq.at.AtTable.java

/**
 * Reads a .at file from an InpuStream into a WQTableSet.
 *
 * @throws IOException/* w w  w  . ja  v  a  2 s . c om*/
 * @throws IOException
 */
private static AtTable readAt(final InputStream is) throws IOException {
    final LineNumberReader reader = new LineNumberReader(new InputStreamReader(is));

    final String firstLine = reader.readLine();
    if (firstLine == null)
        throw new IOException(Messages.getString("org.kalypso.ogc.sensor.timeseries.wq.at.AtTable.1")); //$NON-NLS-1$
    final String secondLine = reader.readLine();
    if (secondLine == null)
        throw new IOException(Messages.getString("org.kalypso.ogc.sensor.timeseries.wq.at.AtTable.2")); //$NON-NLS-1$

    final Matcher matcher = PATTERN_SECOND_LINE.matcher(secondLine);
    if (!matcher.matches())
        throw new IOException(
                Messages.getString("org.kalypso.ogc.sensor.timeseries.wq.at.AtTable.3", secondLine)); //$NON-NLS-1$

    final int size = Integer.parseInt(matcher.group(1));
    final String typeFrom = matcher.group(2);
    final String typeTo = matcher.group(3);

    // TODO: first line ist not parsed yet
    final String name = firstLine;
    final int elbaNr = -1;
    final BigDecimal min = null;
    final BigDecimal max = null;
    final Date validity = null;
    // TODO: get validity from a) the stream b) the atDictionary
    // TODO: discuss with moni?

    final List<WQPair> wqList = new ArrayList<>(size);

    // TODO: read table from stream
    while (reader.ready()) {
        final String line = reader.readLine();
        if (line == null)
            break;

        final String[] strings = line.trim().split("\\s+"); //$NON-NLS-1$
        if (strings.length != 2)
            throw new IOException(Messages.getString("org.kalypso.ogc.sensor.timeseries.wq.at.AtTable.6", //$NON-NLS-1$
                    reader.getLineNumber(), line));

        try {
            final double w = Double.parseDouble(strings[0]);
            final double q = Double.parseDouble(strings[1]);

            wqList.add(new WQPair(w, q));
        } catch (final NumberFormatException e) {
            throw new IOException(Messages.getString("org.kalypso.ogc.sensor.timeseries.wq.at.AtTable.8", //$NON-NLS-1$
                    reader.getLineNumber(), line));
        }
    }

    if (wqList.size() != size) {
        // ignore; maybe produce a warning?
    }

    final WQPair[] pairs = wqList.toArray(new WQPair[wqList.size()]);

    return new AtTable(name, elbaNr, min, max, typeFrom, typeTo, validity, pairs);
}

From source file:org.apache.isis.objectstore.nosql.db.file.server.FileServer.java

private void readTransaction(final LineNumberReader reader) throws IOException {
    final ArrayList<FileContent> files = new ArrayList<FileContent>();
    final DataFileWriter content = new DataFileWriter(files);
    String header;//  w w  w .  j  a  v a 2s.c o m
    while ((header = reader.readLine()) != null) {
        if (header.startsWith("#transaction ended")) {
            LOG.debug("transaction read in (ending " + reader.getLineNumber() + ")");
            content.writeData();
            reader.readLine();
            return;
        }
        if (header.startsWith("S")) {
            final String[] split = header.substring(1).split(" ");
            final String key = split[0];
            final String name = split[1];
            server.saveService(key, name);
            reader.readLine();
        } else if (header.startsWith("B")) {
            final String[] split = header.substring(1).split(" ");
            final String name = split[0];
            final long nextBatch = Long.valueOf(split[1]);
            server.saveNextBatch(name, nextBatch);
            reader.readLine();
        } else {
            FileContent elementData;
            elementData = readElementData(header, reader);
            files.add(elementData);
        }
    }
    LOG.warn("transaction has no ending marker so is incomplete and will not be restored (ending "
            + reader.getLineNumber() + ")");
}

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

public void read(final File buildingFile) throws IOException {
    LineNumberReader reader = null;
    try {/*  w  w w .  j  a v a 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.apache.jackrabbit.oak.plugins.blob.MarkSweepGarbageCollector.java

/**
 * Returns the stats related to GC for all repos
 * //from  w  w  w  .  ja v  a2  s .c om
 * @return a list of GarbageCollectionRepoStats objects
 * @throws Exception
 */
@Override
public List<GarbageCollectionRepoStats> getStats() throws Exception {
    List<GarbageCollectionRepoStats> stats = newArrayList();
    if (SharedDataStoreUtils.isShared(blobStore)) {
        // Get all the references available
        List<DataRecord> refFiles = ((SharedDataStore) blobStore)
                .getAllMetadataRecords(SharedStoreRecordType.REFERENCES.getType());
        Map<String, DataRecord> references = Maps.uniqueIndex(refFiles, new Function<DataRecord, String>() {
            @Override
            public String apply(DataRecord input) {
                return SharedStoreRecordType.REFERENCES.getIdFromName(input.getIdentifier().toString());
            }
        });

        // Get all the markers available
        List<DataRecord> markerFiles = ((SharedDataStore) blobStore)
                .getAllMetadataRecords(SharedStoreRecordType.MARKED_START_MARKER.getType());
        Map<String, DataRecord> markers = Maps.uniqueIndex(markerFiles, new Function<DataRecord, String>() {
            @Override
            public String apply(DataRecord input) {
                return SharedStoreRecordType.MARKED_START_MARKER
                        .getIdFromName(input.getIdentifier().toString());
            }
        });

        // Get all the repositories registered
        List<DataRecord> repoFiles = ((SharedDataStore) blobStore)
                .getAllMetadataRecords(SharedStoreRecordType.REPOSITORY.getType());

        for (DataRecord repoRec : repoFiles) {
            String id = SharedStoreRecordType.REFERENCES.getIdFromName(repoRec.getIdentifier().toString());
            GarbageCollectionRepoStats stat = new GarbageCollectionRepoStats();
            stat.setRepositoryId(id);
            if (id != null && id.equals(repoId)) {
                stat.setLocal(true);
            }

            if (references.containsKey(id)) {
                DataRecord refRec = references.get(id);
                stat.setEndTime(refRec.getLastModified());
                stat.setLength(refRec.getLength());

                if (markers.containsKey(id)) {
                    stat.setStartTime(markers.get(id).getLastModified());
                }

                LineNumberReader reader = null;
                try {
                    reader = new LineNumberReader(new InputStreamReader(refRec.getStream()));
                    while (reader.readLine() != null) {
                    }
                    stat.setNumLines(reader.getLineNumber());
                } finally {
                    Closeables.close(reader, true);
                }
            }
            stats.add(stat);
        }
    }
    return stats;
}

From source file:net.rptools.lib.io.PackedFile.java

/**
 * Returns a POJO by reading the contents of the zip archive path specified and converting the XML via the
 * associated XStream object. (Because the XML is character data, this routine calls
 * {@link #getFileAsReader(String)} to handle character encoding.)
 * <p>/*  w  w  w  .j  a v a  2s.c o  m*/
 * <b>TODO:</b> add {@link ModelVersionManager} support
 * 
 * @param path
 *            zip file archive path entry
 * @return Object created by translating the XML
 * @throws IOException
 */
public Object getFileObject(String path) throws IOException {
    // This next line really should be routed thru the version manager...
    // Update:  a new XStreamConverter was created for the Asset object that
    // never marshalls the image data, but *does* unmarshall it.  This allows
    // older pre-1.3.b64 campaigns to be loaded but only the newer format
    // (with a separate image file) works on output.
    LineNumberReader r = getFileAsReader(path);
    Object o = null;
    try {
        xstream.ignoreUnknownElements(); // Jamz: Should we use this? This will ignore new classes/fields added.      
        o = xstream.fromXML(r);
    } catch (InstantiationError ie) {
        log.error("Found at line number " + r.getLineNumber());
        log.error("Cannot convert XML to Object", ie);
        throw ie;
    } finally {
        IOUtils.closeQuietly(r);
    }
    return o;
}

From source file:org.latticesoft.util.common.FileUtil.java

/**
 * Read lines from an inputstream.// w ww .ja v  a2  s. c om
 * @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:org.apache.isis.objectstore.nosql.db.file.server.FileServer.java

private void recover(final File file) {
    LineNumberReader reader = null;
    try {/*from   w  w w  . ja va 2  s .co m*/
        reader = new LineNumberReader(new InputStreamReader(new FileInputStream(file), Util.ENCODING));

        while (true) {
            final String line = reader.readLine();
            if (line == null) {
                break;
            }
            if (!line.startsWith("#transaction started")) {
                throw new NoSqlStoreException(
                        "No transaction start found: " + line + " (" + reader.getLineNumber() + ")");
            }
            readTransaction(reader);
        }
    } catch (final IOException e) {
        throw new NoSqlStoreException(e);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException e) {
                throw new NoSqlStoreException(e);
            }
        }
    }
}

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/*from  w ww. j a  va  2  s. 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;
}