Example usage for java.io LineNumberReader readLine

List of usage examples for java.io LineNumberReader readLine

Introduction

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

Prototype

public String readLine() throws IOException 

Source Link

Document

Read a line of text.

Usage

From source file:org.kalypso.model.wspm.core.profil.sobek.parser.SobekLineParser.java

public SobekLineParser(final LineNumberReader reader) throws IOException, CoreException {
    final String line = reader.readLine();
    if (line == null)
        throw SobekParsing.throwError(format(Messages.getString("SobekLineParser_0"))); //$NON-NLS-1$

    m_tokenizer = new StrTokenizer(line, StrMatcher.spaceMatcher(), StrMatcher.singleQuoteMatcher());
    m_lineNumber = reader.getLineNumber();
}

From source file:com.acmeair.loader.FlightLoader.java

public void loadFlights() throws Exception {
    InputStream csvInputStream = FlightLoader.class.getResourceAsStream("/mileage.csv");

    LineNumberReader lnr = new LineNumberReader(new InputStreamReader(csvInputStream));
    String line1 = lnr.readLine();
    StringTokenizer st = new StringTokenizer(line1, ",");
    ArrayList<AirportCodeMapping> airports = new ArrayList<AirportCodeMapping>();

    // read the first line which are airport names
    while (st.hasMoreTokens()) {
        AirportCodeMapping acm = new AirportCodeMapping();
        acm.setAirportName(st.nextToken());
        airports.add(acm);/*from   w  ww.  ja  v  a 2 s .c o m*/
    }
    // read the second line which contains matching airport codes for the first line
    String line2 = lnr.readLine();
    st = new StringTokenizer(line2, ",");
    int ii = 0;
    while (st.hasMoreTokens()) {
        String airportCode = st.nextToken();
        airports.get(ii).setAirportCode(airportCode);
        ii++;
    }
    // read the other lines which are of format:
    // airport name, aiport code, distance from this airport to whatever airport is in the column from lines one and two
    String line;
    int flightNumber = 0;
    while (true) {
        line = lnr.readLine();
        if (line == null || line.trim().equals("")) {
            break;
        }
        st = new StringTokenizer(line, ",");
        String airportName = st.nextToken();
        String airportCode = st.nextToken();
        if (!alreadyInCollection(airportCode, airports)) {
            AirportCodeMapping acm = new AirportCodeMapping();
            acm.setAirportName(airportName);
            acm.setAirportCode(airportCode);
            airports.add(acm);
        }
        int indexIntoTopLine = 0;
        while (st.hasMoreTokens()) {
            String milesString = st.nextToken();
            if (milesString.equals("NA")) {
                indexIntoTopLine++;
                continue;
            }
            int miles = Integer.parseInt(milesString);
            String toAirport = airports.get(indexIntoTopLine).getAirportCode();
            String flightId = "AA" + flightNumber;
            FlightSegment flightSeg = new FlightSegment(flightId, airportCode, toAirport, miles);
            flightService.storeFlightSegment(flightSeg);
            Date now = new Date();
            for (int daysFromNow = 0; daysFromNow < MAX_FLIGHTS_PER_SEGMENT; daysFromNow++) {
                Calendar c = Calendar.getInstance();
                c.setTime(now);
                c.set(Calendar.HOUR_OF_DAY, 0);
                c.set(Calendar.MINUTE, 0);
                c.set(Calendar.SECOND, 0);
                c.set(Calendar.MILLISECOND, 0);
                c.add(Calendar.DATE, daysFromNow);
                Date departureTime = c.getTime();
                Date arrivalTime = getArrivalTime(departureTime, miles);
                flightService.createNewFlight(flightId, departureTime, arrivalTime, new BigDecimal(500),
                        new BigDecimal(200), 10, 200, "B747");

            }
            flightNumber++;
            indexIntoTopLine++;
        }
    }

    for (int jj = 0; jj < airports.size(); jj++) {
        flightService.storeAirportMapping(airports.get(jj));
    }
    lnr.close();
}

From source file:com.bce.gis.io.zweidm.SmsParser.java

private void parse(final Reader reader) throws IOException {
    Assert.isNotNull(reader);//  w ww .j a  v a2s.c o  m

    final LineNumberReader lnReader = new LineNumberReader(reader);
    for (String line = lnReader.readLine(); line != null; line = lnReader.readLine()) {
        try {
            if (line.startsWith("ND")) //$NON-NLS-1$
                interpreteNodeLine(line, lnReader);
            else if (line.startsWith("E3T")) //$NON-NLS-1$
                interpreteE3TLine(line, lnReader);
            else if (line.startsWith("E4Q")) //$NON-NLS-1$
                interpreteE4QLine(line, lnReader);
        } catch (final NumberFormatException e) {
            addStatus(lnReader, IStatus.ERROR, Messages.getString("SmsParser_2"), e.getLocalizedMessage()); //$NON-NLS-1$
        }

        /* Abort after too many problems, */
        final int maxProblemCount = 100;
        if (m_stati.size() > maxProblemCount) {
            m_stati.add(IStatus.ERROR, Messages.getString("SmsParser_3")); //$NON-NLS-1$
            return;
        }
    }
}

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

public void readValues(final LineNumberReader reader, final int numValues) throws IOException {
    int valueCount = 0;

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

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

        if (StringUtils.isBlank(line))
            continue;

        final String[] values = StringUtils.split(line, null);
        for (final String item : values) {
            m_timeStep.step(m_currentStep);

            final Date valueDate = m_currentStep.getTime();

            final double value = NumberUtils.parseQuietDouble(item);

            m_data.put(valueDate, value);

            valueCount++;/*from w  w w.  jav  a 2 s.  com*/

            if (valueCount >= numValues)
                return;
        }
    }
}

From source file:org.kuali.test.proxyserver.MultiPartHandler.java

public MultiPartHandler(MultipartStream multipartStream) throws IOException {
    LineNumberReader lnr = null;
    try {/*  w w  w .  j a  v a 2s . co m*/
        lnr = new LineNumberReader(new StringReader(multipartStream.readHeaders()));
        String line;

        while ((line = lnr.readLine()) != null) {
            if (line.startsWith(Constants.CONTENT_DISPOSITION)) {
                for (String param : PARAMETER_NAMES) {
                    int pos = line.indexOf(param);
                    if (pos > -1) {
                        pos += (param.length() + 2);
                        int pos2 = line.indexOf("\"", pos);

                        if ((pos > -1) && (pos2 > -1) && (pos2 > pos)) {
                            parameters.put(param, line.substring(pos, pos2));
                        }
                    }
                }
            }

            if (line.startsWith(Constants.HTTP_RESPONSE_CONTENT_TYPE)) {
                int pos = line.indexOf(Constants.SEPARATOR_COLON);

                if (pos > -1) {
                    contentType = line.substring(pos + 1).trim();
                }
            }
        }

        ByteArrayOutputStream bos = new ByteArrayOutputStream(512);
        multipartStream.readBodyData(bos);
        bytes = bos.toByteArray();
    }

    finally {
        try {
            if (lnr != null) {
                lnr.close();
            }
        }

        catch (Exception ex) {
        }
        ;
    }
}

From source file:org.testng.spring.test.AbstractTransactionalDataSourceSpringContextTests.java

/**
 * Execute the given SQL script. Will be rolled back by default,
 * according to the fate of the current transaction.
 * @param sqlResourcePath Spring resource path for the SQL script.
 * Should normally be loaded by classpath. There should be one statement
 * per line. Any semicolons will be removed.
 * <b>Do not use this method to execute DDL if you expect rollback.</b>
 * @param continueOnError whether or not to continue without throwing
 * an exception in the event of an error
 * @throws DataAccessException if there is an error executing a statement
 * and continueOnError was false/*from  w  w w.  j a v  a 2 s  . co m*/
 */
protected void executeSqlScript(String sqlResourcePath, boolean continueOnError) throws DataAccessException {
    if (logger.isInfoEnabled()) {
        logger.info("Executing SQL script '" + sqlResourcePath + "'");
    }

    long startTime = System.currentTimeMillis();
    List statements = new LinkedList();
    Resource res = getApplicationContext().getResource(sqlResourcePath);
    try {
        LineNumberReader lnr = new LineNumberReader(new InputStreamReader(res.getInputStream()));
        String currentStatement = lnr.readLine();
        while (currentStatement != null) {
            currentStatement = StringUtils.replace(currentStatement, ";", "");
            statements.add(currentStatement);
            currentStatement = lnr.readLine();
        }

        for (Iterator itr = statements.iterator(); itr.hasNext();) {
            String statement = (String) itr.next();
            try {
                int rowsAffected = this.jdbcTemplate.update(statement);
                if (logger.isDebugEnabled()) {
                    logger.debug(rowsAffected + " rows affected by SQL: " + statement);
                }
            } catch (DataAccessException ex) {
                if (continueOnError) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("SQL: " + statement + " failed", ex);
                    }
                } else {
                    throw ex;
                }
            }
        }
        long elapsedTime = System.currentTimeMillis() - startTime;
        logger.info("Done executing SQL script '" + sqlResourcePath + "' in " + elapsedTime + " ms");
    } catch (IOException ex) {
        throw new DataAccessResourceFailureException("Failed to open SQL script '" + sqlResourcePath + "'", ex);
    }
}

From source file:com.puppycrawl.tools.checkstyle.checks.header.AbstractHeaderCheck.java

/**
 * Load header to check against from a Reader into readerLines.
 * @param headerReader delivers the header to check against
 * @throws IOException if//from   w  ww. j a v a 2  s.co  m
 */
private void loadHeader(final Reader headerReader) throws IOException {
    final LineNumberReader lnr = new LineNumberReader(headerReader);
    readerLines.clear();
    while (true) {
        final String line = lnr.readLine();
        if (line == null) {
            break;
        }
        readerLines.add(line);
    }
    postProcessHeaderLines();
}

From source file:com.penguineering.cleanuri.sites.reichelt.ReicheltExtractor.java

@Override
public Map<Metakey, String> extractMetadata(URI uri) throws ExtractorException {
    if (uri == null)
        throw new NullPointerException("URI argument must not be null!");

    URL url;//  w  ww.  ja  v  a2  s. c o m
    try {
        url = uri.toURL();
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("The provided URI is not a URL!");
    }

    Map<Metakey, String> meta = new HashMap<Metakey, String>();

    try {
        final URLConnection con = url.openConnection();

        LineNumberReader reader = null;
        try {
            reader = new LineNumberReader(new InputStreamReader(con.getInputStream()));

            String line;
            while ((line = reader.readLine()) != null) {
                if (!line.contains("<h2>"))
                    continue;

                // h2
                int h2_idx = line.indexOf("h2");
                // Doppelpunkte
                int col_idx = line.indexOf("<span> :: <span");
                final String art_id = line.substring(h2_idx + 3, col_idx);
                meta.put(Metakey.ID, html2oUTF8(art_id).trim());

                int span_idx = line.indexOf("</span>");
                final String art_name = line.substring(col_idx + 32, span_idx);
                meta.put(Metakey.NAME, html2oUTF8(art_name).trim());

                break;
            }

            return meta;
        } finally {
            if (reader != null)
                reader.close();
        }
    } catch (IOException e) {
        throw new ExtractorException("I/O exception during extraction: " + e.getMessage(), e, uri);
    }

}

From source file:com.liferay.portal.scripting.internal.ScriptingImpl.java

protected String getErrorMessage(String script, Exception e) {
    StringBundler sb = new StringBundler();

    sb.append(e.getMessage());/*www. ja  v  a 2 s  .c o m*/
    sb.append(StringPool.NEW_LINE);

    try {
        LineNumberReader lineNumberReader = new LineNumberReader(new UnsyncStringReader(script));

        while (true) {
            String line = lineNumberReader.readLine();

            if (line == null) {
                break;
            }

            sb.append("Line ");
            sb.append(lineNumberReader.getLineNumber());
            sb.append(": ");
            sb.append(line);
            sb.append(StringPool.NEW_LINE);
        }
    } catch (IOException ioe) {
        sb.setIndex(0);

        sb.append(e.getMessage());
        sb.append(StringPool.NEW_LINE);
        sb.append(script);
    }

    return sb.toString();
}

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

private void initialize(final File baseDir) throws NumberFormatException, IOException {
    indexMap = new HashMap<Integer, FileMap>();
    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  ww. j a v  a 2  s  .c  o  m*/
        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();
    }

}