Example usage for java.io LineNumberReader ready

List of usage examples for java.io LineNumberReader ready

Introduction

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

Prototype

public boolean ready() throws IOException 

Source Link

Document

Tells whether this stream is ready to be read.

Usage

From source file:org.kalypso.model.hydrology.internal.postprocessing.BlockTimeSeries.java

private Entry<String, Integer> searchBlockHeader(final LineNumberReader reader)
        throws NumberFormatException, IOException {
    while (reader.ready()) {
        final String line = reader.readLine();
        if (line == null)
            break;

        if (line.startsWith("#")) //$NON-NLS-1$
            continue;

        final Matcher m = PATTERN_BLOCK_HEADER.matcher(line);
        if (m.matches()) {
            final String key = m.group(1);
            final int valuesCount = Integer.parseInt(m.group(3));

            // HACK: create singleton map in order to create entry
            return Collections.singletonMap(key, valuesCount).entrySet().iterator().next();
        }/*from  w  ww  .j  av a 2  s . co  m*/
    }

    return null;
}

From source file:org.kalypso.model.hydrology.internal.postprocessing.LzsToGml.java

private void readLzsFile(final FileReader fileReader, final Catchment catchment, final Feature lzCatchmentFE)
        throws Exception {
    final LineNumberReader reader = new LineNumberReader(fileReader);

    final IFeatureType lzCatchmentFT = GMLSchemaUtilities
            .getFeatureTypeQuiet(new QName(NaModelConstants.NS_INIVALUES, "Catchment")); //$NON-NLS-1$
    final IRelationType lzinitHydMemberRT = (IRelationType) lzCatchmentFT
            .getProperty(NaModelConstants.INI_CATCHMENT_LINK_HYD_PROP);

    final String iniDate = m_dateFormat.format(m_initialDate);
    int maxHydros = 0;
    int counterHydros = 0;
    // TODO: why compare the datum? IT would be more robust to just read all data that is in the lsz file, and append
    // it to the features!

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

        final String cleanLine = line.trim().replaceAll("\\s+", " "); //$NON-NLS-1$ //$NON-NLS-2$
        switch (status) {
        case SEARCH_HEADER:
            final Matcher matcherBODF = PATTERN_HEADER_BODF.matcher(cleanLine);
            if (cleanLine.endsWith("snow") && cleanLine.startsWith(iniDate)) //$NON-NLS-1$
                status = CatchmentStatus.READ_SNOW;
            else if (cleanLine.endsWith("gwsp") && cleanLine.startsWith(iniDate)) //$NON-NLS-1$
                status = CatchmentStatus.READ_GWSP;
            else if (matcherBODF.matches() && cleanLine.startsWith(iniDate)) {
                status = CatchmentStatus.READ_BODF;
                maxHydros = Integer.parseInt(matcherBODF.group(2));
            }//from ww w.  j ava  2s . c  om
            break;

        case READ_BODF: {
            final Feature lzHydFE = m_lzWorkspace.createFeature(lzCatchmentFE, lzinitHydMemberRT,
                    lzinitHydMemberRT.getTargetFeatureType());
            m_lzWorkspace.addFeatureAsComposition(lzCatchmentFE, lzinitHydMemberRT, 0, lzHydFE);
            final String[] strings = cleanLine.split(" "); //$NON-NLS-1$
            final int pos = Integer.parseInt(strings[0]) - 1;
            final String hydroID = m_hydroHash.getHydroFeatureId(catchment, pos);
            lzHydFE.setProperty(new QName(NaModelConstants.NS_INIVALUES, "featureId"), hydroID); //$NON-NLS-1$
            final Double interception = Double.valueOf(strings[1]);
            final List<Double> bofs = new ArrayList<>();
            for (int i = 2; i < strings.length; i++) {
                final Double bf = Double.valueOf(strings[i]);
                bofs.add(bf);
            }
            lzHydFE.setProperty(new QName(NaModelConstants.NS_INIVALUES, "bi"), interception); //$NON-NLS-1$
            lzHydFE.setProperty(new QName(NaModelConstants.NS_INIVALUES, "bofs"), bofs); //$NON-NLS-1$
            counterHydros++;
            if (counterHydros >= maxHydros) {
                status = CatchmentStatus.SEARCH_HEADER;
                counterHydros = 0;
            }
        }
            break;

        case READ_GWSP: {
            final String[] strings = cleanLine.split(" "); //$NON-NLS-1$
            final Double hgws = Double.valueOf(strings[1]);// hoehe gw
            final Double qb = Double.valueOf(strings[2]);// basisabfluss
            lzCatchmentFE.setProperty(new QName(NaModelConstants.NS_INIVALUES, "hgws"), hgws); //$NON-NLS-1$
            lzCatchmentFE.setProperty(new QName(NaModelConstants.NS_INIVALUES, "qb"), qb); //$NON-NLS-1$
            status = CatchmentStatus.SEARCH_HEADER;
        }
            break;

        case READ_SNOW:
            final String[] strings = cleanLine.split(" "); //$NON-NLS-1$
            final Double h = Double.valueOf(strings[1]);// hoehe schnee
            final Double ws = Double.valueOf(strings[2]);// wassergehalt
            lzCatchmentFE.setProperty(new QName(NaModelConstants.NS_INIVALUES, "h"), h); //$NON-NLS-1$
            lzCatchmentFE.setProperty(new QName(NaModelConstants.NS_INIVALUES, "ws"), ws); //$NON-NLS-1$
            status = CatchmentStatus.SEARCH_HEADER;
            break;
        }
    } // TODO: if we reach this line without any read data, something is wrong!
}

From source file:org.kalypso.model.hydrology.internal.postprocessing.LzsToGml.java

private double readLzgFile(final FileReader fileReader) throws NumberFormatException, IOException {
    final LineNumberReader reader = new LineNumberReader(fileReader);

    ChannelStatus status = ChannelStatus.SEARCH_HEADER;

    final String iniDate = m_dateFormat.format(m_initialDate);

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

        final String cleanLine = line.trim().replaceAll("\\s+", " "); //$NON-NLS-1$ //$NON-NLS-2$
        switch (status) {
        case SEARCH_HEADER:
            if (cleanLine.endsWith("qgs") && cleanLine.startsWith(iniDate)) //$NON-NLS-1$
                // 19960521 00 h 1 qgs
                // 1 0.000
                status = ChannelStatus.READ_QGS;
            break;

        case READ_QGS: // Gesamtabfluss
            final String[] strings = cleanLine.split(" "); //$NON-NLS-1$
            return Double.valueOf(strings[1]);
        }/*from  w  ww.j av  a 2  s .c  om*/
    }

    return Double.NaN;
}

From source file:org.kalypso.model.wspm.core.imports.DA50Importer.java

/**
 * @param srsName//from w  w w .  j a  v  a2  s  .  c om
 *          The coordinate system code.
 */
private static DA50Entry[] readDA50(final LineNumberReader lnr, final String srsName)
        throws IOException, CoreException {
    final List<DA50Entry> result = new ArrayList<>();

    final MultiStatus logStatus = new MultiStatus(KalypsoModelWspmCorePlugin.getID(), 0,
            Messages.getString("org.kalypso.model.wspm.core.imports.DA50Importer.2"), null); //$NON-NLS-1$

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

        try {

            if (line.length() < 60 || !line.startsWith("50")) //$NON-NLS-1$
            {
                continue;
            }

            // Station auslesen und mit 0en auffllen, sonst klappt das umrechnen in m nicht immer
            // CString help_str = str.Mid( 9,9 );
            // help_str.TrimRight();
            // help_str = help_str + CString( '0', 9 - help_str.GetLength() );
            final String stationString = line.substring(9, 18).trim();
            final StringBuffer stationBuf = new StringBuffer(stationString);
            for (int i = stationString.length() - 9; i < 0; i++) {
                stationBuf.append('0');
            }

            // int temp = 0;
            // sscanf( help_str, "%d", &temp );
            // double station = (double)temp / 1000000;
            final double station = Double.parseDouble(stationBuf.toString()) / 1000000;

            // logstream << "Geokoordinaten gefunden fr Station: " << station << std::endl;

            // logstream << "Querprofil mit gleicher Station gefunden" << std::endl;

            // double rw_start, rw_end,hw_start,hw_end;
            // __int64 rh_wert;

            // help_str=str.Mid(21-1,10);

            final String rwStartString = line.substring(20, 30);
            final String hwStartString = line.substring(30, 40);
            final String rwEndString = line.substring(40, 50);
            final String hwEndString = line.substring(50, 60);

            final double rwStart = Double.parseDouble(rwStartString) / 1000.0;
            final double hwStart = Double.parseDouble(hwStartString) / 1000.0;
            final double rwEnd = Double.parseDouble(rwEndString) / 1000.0;
            final double hwEnd = Double.parseDouble(hwEndString) / 1000.0;

            final GM_Point start = WspmGeometryUtilities.pointFromRwHw(rwStart, hwStart, Double.NaN, srsName,
                    null);
            final GM_Point end = WspmGeometryUtilities.pointFromRwHw(rwEnd, hwEnd, Double.NaN, srsName, null);

            result.add(new DA50Entry(station, start, end));
        } catch (final Exception e) {
            final IStatus status = StatusUtilities.statusFromThrowable(e, Messages
                    .getString("org.kalypso.model.wspm.core.imports.DA50Importer.4", lnr.getLineNumber())); //$NON-NLS-1$
            logStatus.add(status);
        }
    }

    if (!logStatus.isOK())
        throw new CoreException(logStatus);

    return result.toArray(new DA50Entry[result.size()]);
}

From source file:org.kalypso.model.wspm.core.imports.ImportTrippleHelper.java

/**
 * Imports the profile trippel data and converts it into IProfils
 * /*w w w.j av a  2 s.c  o  m*/
 * @param trippleFile
 *          file with profile tripples
 */
public static IProfile[] importTrippelData(final File trippleFile, final String separator,
        final String profileType, final String crs) throws CoreException {
    final IProfilePointPropertyProvider provider = KalypsoModelWspmCoreExtensions
            .getPointPropertyProviders(profileType);

    final IComponent rechtswert = provider.getPointProperty(IWspmPointProperties.POINT_PROPERTY_RECHTSWERT);
    final IComponent hochwert = provider.getPointProperty(IWspmPointProperties.POINT_PROPERTY_HOCHWERT);

    if (trippleFile == null)
        return new IProfile[0];

    /* read profiles, show warnings */
    final List<IProfile> profiles = new ArrayList<>();
    IProfile currentProfile = null;

    /* file loading */
    LineNumberReader fileReader = null;

    try (InputStreamReader inputReader = new InputStreamReader(new FileInputStream(trippleFile))) {
        fileReader = new LineNumberReader(inputReader);

        /* File Header */
        fileReader.readLine();

        IProfileRecord lastPoint = null;
        while (fileReader.ready()) {
            final String line = fileReader.readLine();
            if (line == null) {
                break;
            }

            /* ignore empty lines */
            if (StringUtils.isBlank(line)) {
                continue;
            }

            /* trippel-format should be: station, x, y, z */
            final String[] tokens = StringUtils.split(line, separator);

            /* continue just if there are enough values in the trippel file */
            if (tokens.length != 4) {
                // FIXME: better error handling
                // inform the user that his profile has not enough values...
                final String message = Messages.getString(
                        "org.kalypso.model.wspm.core.imports.ImportTrippleHelper.0", //$NON-NLS-1$
                        fileReader.getLineNumber());
                final IStatus status = new Status(IStatus.ERROR, KalypsoModelWspmCorePlugin.getID(), message);
                throw new CoreException(status);
            }

            try {
                /* first value = profile station */
                final double station = NumberUtils.parseDouble(tokens[0]);
                final BigDecimal currentStation = ProfileUtil.stationToBigDecimal(station);

                final BigDecimal currentProfileStation = currentProfile == null ? null
                        : ProfileUtil.stationToBigDecimal(currentProfile.getStation());

                if (!ObjectUtils.equals(currentStation, currentProfileStation)) {
                    lastPoint = null;

                    currentProfile = ProfileFactory.createProfil(profileType, null);

                    currentProfile.setStation(station);
                    currentProfile.setName(
                            Messages.getString("org.kalypso.model.wspm.core.imports.ImportTrippleHelper.1")); //$NON-NLS-1$
                    currentProfile.setDescription(
                            Messages.getString("org.kalypso.model.wspm.core.imports.ImportTrippleHelper.2")); //$NON-NLS-1$
                    currentProfile.setSrsName(crs);

                    currentProfile.addPointProperty(rechtswert);
                    currentProfile.addPointProperty(hochwert);

                    profiles.add(currentProfile);
                }

                final IProfileRecord point = ImportTrippleHelper.createProfilePoint(currentProfile, tokens,
                        lastPoint);
                if (point != null) {
                    currentProfile.addPoint(point);
                }

                lastPoint = point;
            } catch (final NumberFormatException e) {
                e.printStackTrace();
                final String message = Messages.getString(
                        "org.kalypso.model.wspm.core.imports.ImportTrippleHelper.3", //$NON-NLS-1$
                        fileReader.getLineNumber());
                final IStatus status = new Status(IStatus.ERROR, KalypsoModelWspmCorePlugin.getID(), message,
                        e);
                throw new CoreException(status);
            }
        }

        fileReader.close();
    } catch (final IOException e) {
        e.printStackTrace();

        final int lineNumber = fileReader == null ? 0 : fileReader.getLineNumber();

        final String message = Messages.getString("org.kalypso.model.wspm.core.imports.ImportTrippleHelper.4", //$NON-NLS-1$
                lineNumber);
        final IStatus status = new Status(IStatus.ERROR, KalypsoModelWspmCorePlugin.getID(), message, e);
        throw new CoreException(status);
    }

    return profiles.toArray(new IProfile[profiles.size()]);
}

From source file:org.kalypso.model.wspm.ewawi.data.reader.AbstractEwawiReader.java

private void read(final LineNumberReader reader) throws IOException, ParseException {
    while (reader.ready()) {
        final String line = reader.readLine();
        readLine(line);/*from  w w  w .j ava2  s .co m*/
    }
}

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

public void read(final File buildingFile) throws IOException {
    LineNumberReader reader = null;
    try {//from w w  w .j a v a 2  s  . c  o  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.kalypso.model.wspm.tuhh.schema.simulation.PolynomeReader.java

public void read(final File polyFile) throws IOException {
    LineNumberReader reader = null;
    try {/*from w w w .j a  va2  s. c om*/
        reader = new LineNumberReader(new FileReader(polyFile));

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

            final String trimmedLine = line.trim().replaceAll(" \\(h\\)", "\\(h\\)"); //$NON-NLS-1$ //$NON-NLS-2$
            final String[] tokens = trimmedLine.split(" +"); //$NON-NLS-1$
            if (tokens.length < 8)
                continue;

            /* Determine if this is a good line: good lines are lines whos first token is a number */
            final BigDecimal station;
            try {
                station = new BigDecimal(tokens[0]);
            } catch (final NumberFormatException nfe) {
                /* Just ignore this line */
                continue;
            }

            try {
                final String description = tokens[1];
                // final String whatIsN = tokens[2];
                final char type = tokens[3].charAt(0);

                final int order = Integer.parseInt(tokens[4]);
                final double rangeMin = Double.parseDouble(tokens[5].replace('D', 'E'));
                final double rangeMax = Double.parseDouble(tokens[6].replace('D', 'E'));

                if (tokens.length < 7 + order + 1) {
                    /* 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.22"), //$NON-NLS-1$
                            polyFile.getName(), reader.getLineNumber());
                    continue;
                }

                final List<Double> coefficients = new ArrayList<>(order);
                for (int i = 7; i < 7 + order + 1; i++) {
                    final double coeff = Double.parseDouble(tokens[i].replace('D', 'E'));
                    coefficients.add(coeff);
                }

                final Double[] doubles = coefficients.toArray(new Double[coefficients.size()]);
                final double[] coeffDoubles = ArrayUtils.toPrimitive(doubles);

                final String domainId;
                final String rangeId = IWspmTuhhQIntervallConstants.DICT_PHENOMENON_WATERLEVEL;
                switch (type) {
                case 'Q':
                    domainId = IWspmTuhhQIntervallConstants.DICT_PHENOMENON_RUNOFF;
                    break;
                case 'A':
                    domainId = IWspmTuhhQIntervallConstants.DICT_PHENOMENON_AREA;
                    break;
                case 'a':
                    domainId = IWspmTuhhQIntervallConstants.DICT_PHENOMENON_ALPHA;
                    break;

                default:
                    m_log.log(false,
                            Messages.getString(
                                    "org.kalypso.model.wspm.tuhh.schema.simulation.PolynomeProcessor.23"), //$NON-NLS-1$
                            station);
                    continue;
                }

                /* find feature for station */
                final QIntervallResult qresult = m_intervalIndex.get(station);
                if (qresult == null)
                    m_log.log(false,
                            Messages.getString(
                                    "org.kalypso.model.wspm.tuhh.schema.simulation.PolynomeProcessor.24"), //$NON-NLS-1$
                            station, line);
                else {
                    /* create new polynome */
                    final IPolynomial1D poly1d = qresult.createPolynomial();

                    poly1d.setName(description);
                    poly1d.setDescription(description);
                    poly1d.setCoefficients(coeffDoubles);
                    poly1d.setRange(rangeMin, rangeMax);

                    poly1d.setDomainPhenomenon(domainId);
                    poly1d.setRangePhenomenon(rangeId);
                }
            } 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$
                        polyFile.getName(), reader.getLineNumber(), nfe.getLocalizedMessage());
            } catch (final Exception e) {
                // should never happen
                m_log.log(e,
                        Messages.getString(
                                "org.kalypso.model.wspm.tuhh.schema.simulation.PolynomeProcessor.25"), //$NON-NLS-1$
                        polyFile.getName(), reader.getLineNumber(), e.getLocalizedMessage());
            }
        }
        reader.close();
    } finally {
        IOUtils.closeQuietly(reader);
    }
}

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

public void read(final File inputFile) throws IOException {
    final String filename = inputFile.getName();

    LineNumberReader reader = null;
    try {//from w  w  w . j a  va  2  s .c o m
        reader = new LineNumberReader(new FileReader(inputFile));

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

            final int lineNumber = reader.getLineNumber();
            readLine(line, lineNumber, filename);
        }

        reader.close();

        m_qresult.setPointsObservation(m_observation);
    } finally {
        IOUtils.closeQuietly(reader);
    }
}

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

/**
 * Reads a .at file from an InpuStream into a WQTableSet.
 *
 * @throws IOException/*from  www . j av a2  s .  co  m*/
 * @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);
}