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:javarestart.Utils.java

private static String getText(final URL url) throws IOException {
    final URLConnection connection = url.openConnection();
    try (LineNumberReader in = new LineNumberReader(
            new InputStreamReader(connection.getInputStream(), Charset.forName("UTF-8")))) {

        final StringBuilder response = new StringBuilder();
        String inputLine;//  w  w w  .j  av a2  s  .com
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }

        return response.toString();
    }
}

From source file:org.nordapp.web.util.StateReader.java

/**
 * Reads the state file/*ww w  .  j  a v a 2 s  .co  m*/
 * 
 * @param dest The destination of the file
 * @return The list of valid states
 * @throws IOException
 */
public List<String> getState(String dest) throws IOException {

    //Get the resource
    ServiceReference<ResourceService> rsr = context.getServiceReference(ResourceService.class);
    if (rsr == null)
        throw new IOException("The resource service is not available (maybe down or a version conflict).");

    ResourceService rs = context.getService(rsr);
    if (rs == null)
        throw new IOException("The resource service is not available (maybe down or a version conflict).");

    Map<String, String> props = new HashMap<String, String>();
    List<String> list = new ArrayList<String>();

    InputStream in = rs.getResourceAsStream(ctrl.getMandatorID(), ctrl.getGroupID(), ctrl.getArtifactID(), dest,
            ResourceService.FILE_RESOURCE, props);

    //use an input stream that supports mark.
    LineNumberReader r = new LineNumberReader(new InputStreamReader(in));
    String line = r.readLine();
    while (line != null) {
        line = line.trim();
        //skip empty lines and comments
        if (!(line.equals("") || line.startsWith("#"))) {
            list.add(line);
        }
        line = r.readLine();
    }

    return list;
}

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

@Test
public void findStreamingFile() throws Exception {
    FileStreamStateHandler rwd = new FileStreamStateHandler();

    File testFilesDir = new File(samplesDir, "/multiple-logs/");
    File[] testFiles = testFilesDir.listFiles((FilenameFilter) new WildcardFileFilter("orders*")); // NON-NLS
    FileAccessState newFAS = new FileAccessState();

    int count = 0;
    File fileToSearchFor = null;//from  w w w.  j a  v  a2 s  . c  om
    int lineLastRead = 0;
    File fileWritten = null;
    for (File testFile : testFiles) {
        count++;
        FileReader in;
        LineNumberReader reader;

        Long fileCRC = rwd.getFileCrc(testFile);
        if (count == 2) {
            newFAS.currentFileCrc = fileCRC;
            fileToSearchFor = testFile;
        }

        in = new FileReader(testFile);
        reader = new LineNumberReader(in);
        reader.setLineNumber(0);
        String line = reader.readLine();
        int count2 = 0;
        while (line != null) {
            count2++;
            Checksum crcLine = new CRC32();
            final byte[] bytes4Line = line.getBytes();
            crcLine.update(bytes4Line, 0, bytes4Line.length);
            final long lineCRC = crcLine.getValue();
            final int lineNumber = reader.getLineNumber();
            System.out.println("for " + lineNumber + " line CRC is " + lineCRC); // NON-NLS
            if (count2 == 3) {
                newFAS.currentLineCrc = lineCRC;
                newFAS.currentLineNumber = lineNumber;
                newFAS.lastReadTime = System.currentTimeMillis();
                lineLastRead = lineNumber;
            }
            line = reader.readLine();
        }
        fileWritten = AbstractFileStreamStateHandler.writeState(newFAS, testFilesDir, "TestStream"); // NON-NLS
        Utils.close(reader);
    }

    final File findLastProcessed = rwd.findStreamingFile(newFAS, testFiles);
    assertEquals(fileToSearchFor, findLastProcessed);
    final int lineLastReadRecorded = rwd.checkLine(findLastProcessed, newFAS);
    assertEquals(lineLastRead, lineLastReadRecorded);
    fileWritten.delete();
}

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

/**
 * @param bRefFirst// w  w w  .j av a 2s. co m
 *          Where to apply the reference: if true, the start-point is applied to the first point of the profile, else
 *          to the point with the breite-coordinate zero.
 * @param srsName
 *          The coordinate system code.
 */
public static void importDA50(final File da50File, final FeatureList profileFeatures, final boolean bRefFirst,
        final String srsName) throws CoreException {
    LineNumberReader da50reader = null;
    try {
        /* Read and parse d50 file */
        da50reader = new LineNumberReader(new FileReader(da50File));
        final DA50Entry[] entries = readDA50(da50reader, srsName);

        /* Index features by station */
        final Map<Double, DA50Entry> entryMap = new TreeMap<>(
                new DoubleComparator(Math.pow(10, -IProfileFeature.STATION_SCALE)));
        for (final DA50Entry entry : entries) {
            entryMap.put(entry.station, entry);
        }

        /* Apply d50 information to profiles */
        for (final Object o : profileFeatures) {
            final IProfileFeature profile = (IProfileFeature) o;
            final double station = profile.getStation();
            final DA50Entry d50Entry = entryMap.get(station);
            if (d50Entry != null) {
                final IProfile profil = profile.getProfile();
                applyD50Entry(profil, d50Entry, bRefFirst);
            }
        }
    } catch (final IOException e) {
        final IStatus status = StatusUtilities.statusFromThrowable(e,
                Messages.getString("org.kalypso.model.wspm.core.imports.DA50Importer.0")); //$NON-NLS-1$
        throw new CoreException(status);
    } finally {
        IOUtils.closeQuietly(da50reader);
    }

}

From source file:org.kawanfw.commons.util.FrameworkDebug.java

/**
 * Load the classes to debug from the file
 * /* w  w w .j ava2  s .  co  m*/
 * @throws IOException
 */
private static void load() {
    if (!CLASSES_TO_DEBUG.isEmpty()) {
        return;
    }

    File kawansoftDir = new File(FrameworkFileUtil.getUserHomeDotKawansoftDir());
    kawansoftDir.mkdirs();

    String file = kawansoftDir + File.separator + KAWANSOFT_DEBUG_INI;

    // Nothing to load if file not set
    if (!new File(file).exists()) {
        CLASSES_TO_DEBUG.add("empty");
        return;
    }

    LineNumberReader lineNumberReader = null;

    try {
        lineNumberReader = new LineNumberReader(new FileReader(file));

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

            if (line.startsWith("//") || line.startsWith("#") || line.isEmpty()) {
                continue;
            }

            CLASSES_TO_DEBUG.add(line);
        }
    } catch (FileNotFoundException e) {
        throw new IllegalArgumentException("Wrapped IOException. Impossible to load debug file: " + file, e);
    } catch (IOException e) {
        throw new IllegalArgumentException("Wrapped IOException. Error reading debug file: " + file, e);
    } finally {
        IOUtils.closeQuietly(lineNumberReader);
    }
}

From source file:org.beangle.ems.system.web.action.FileAction.java

public String download() throws IOException {
    String path = get("path");
    FileMimeType fileMimeType = new FileMimeType(mimeTypeProvider);
    if (Strings.isNotBlank(path)) {
        File file = new File(path);
        if (!file.isFile()) {
            return null;
        }/*from   w ww  . j  av  a2 s  .com*/
        boolean download = getBool("download");
        if (!download && fileMimeType.isTextType(file)) {
            List<String> lines = CollectUtils.newArrayList();
            LineNumberReader reader = new LineNumberReader(new FileReader(file));
            String line = reader.readLine();
            while (null != line) {
                lines.add(line);
                line = reader.readLine();
            }
            put("lines", lines);
            put("file", file);
            reader.close();
            return forward("content");
        } else {
            streamDownloader.download(getRequest(), getResponse(), file);
        }
    }
    return null;
}

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   www. j a  va2s  .  co m
        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.diffkit.db.DKDBInsertTableLoader.java

/**
 * @return true if the load succeeded/*  ww w  .  ja  v  a 2 s. c  o m*/
 * @throws IOException
 */
public boolean load(DKDBTable table_, File csvFile_) throws IOException, SQLException {
    _log.debug("table_->{}", table_);
    _log.debug("csvFile_->{}", csvFile_);
    DKValidate.notNull(table_, csvFile_);
    if (!csvFile_.canRead())
        throw new IOException(String.format("can't read csvFile_->%s", csvFile_));
    if (!_database.tableExists(table_))
        throw new IOException(String.format("table_->%s does not exist in database->", table_, _database));
    Connection connection = _database.getConnection();
    _log.debug("connection->{}", connection);
    if (connection == null)
        throw new SQLException(String.format("can't get connection from database->", _database));

    connection.setAutoCommit(true);
    this.setDateFormat(connection);
    LineNumberReader reader = new LineNumberReader(new BufferedReader(new FileReader(csvFile_)));
    String[] tableColumnNames = table_.getColumnNames();
    DKDBTypeInfo[] typeInfos = _database.getColumnConcreteTypeInfos(table_);
    if (_debugEnabled) {
        _log.debug("tableColumnNames->{}", Arrays.toString(tableColumnNames));
        _log.debug("typeInfos->{}", Arrays.toString(typeInfos));
    }
    String line = null;
    List<String> updateStatements = new ArrayList<String>(LOAD_BATCH_SIZE);
    // assume first line is header, use column names to drive the line parse
    line = StringUtils.trimToNull(reader.readLine());
    String[] headerColumnNames = line.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
    int[] loadIndices = DKArrayUtil.getIndicesOfIntersection(headerColumnNames, tableColumnNames);
    if (_debugEnabled) {
        _log.debug("headerColumnNames->{}", Arrays.toString(headerColumnNames));
        _log.debug("loadIndices->{}", Arrays.toString(loadIndices));
    }
    for (long i = 1; (line = StringUtils.trimToNull(reader.readLine())) != null; i++) {
        String[] values = line.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
        if (_debugEnabled) {
            _log.debug("line: " + line);
            _log.debug("values: " + Arrays.toString(values));
        }
        DKStringUtil.unquote(values, Quote.DOUBLE);
        values = DKArrayUtil.retainElementsAtIndices(values, loadIndices);
        if (_debugEnabled) {
            _log.debug("values: " + Arrays.toString(values));
        }
        if (!(values.length == tableColumnNames.length))
            throw new RuntimeException(
                    String.format("number of values->%s does not match number of columns->%s", values.length,
                            tableColumnNames.length));
        String insertStatementString = _database.generateInsertDML(values, typeInfos, tableColumnNames,
                table_.getSchema(), table_.getTableName());
        updateStatements.add(insertStatementString);
        _log.debug("insertStatementString: " + insertStatementString);
        if (i % LOAD_BATCH_SIZE == 0) {
            DKSqlUtil.executeBatchUpdate(updateStatements, connection);
            _log.debug("inserted " + i + " rows");
            updateStatements.clear();
        }
    }
    long updates = DKSqlUtil.executeBatchUpdate(updateStatements, connection);
    DKSqlUtil.close(connection);
    _log.debug("updates: " + updates);
    reader.close();
    return true;
}

From source file:net.sf.ginp.tags.GetFolderInfo.java

/**
 *  Called when a Start tag is processed.
 *
 *@return                   Description of the Return Value
 *@exception  JspException  Description of the Exception
 */// w ww .j a  v  a  2  s.  c om
public final int doStartTag() throws JspException {
    String title = "";
    String description = "";
    String date = "";
    String time = "";

    try {
        model = ModelUtil.getModel((HttpServletRequest) pageContext.getRequest());
    } catch (Exception e) {
        throw new JspException(e);
    }

    try {
        File fl = new File(
                model.getCollection().getRoot() + model.getCollection().getPath() + "ginpfolder.xml");

        if (fl.exists()) {
            FileReader fr = new FileReader(fl);
            LineNumberReader lr = new LineNumberReader(fr);
            StringBuffer sb = new StringBuffer();
            String temp;

            while ((temp = lr.readLine()) != null) {
                sb.append(temp + "\n");
            }

            // Date
            date = StringTool.getXMLTagContent("date", sb.toString());

            if (date != null) {
                pageContext.setAttribute("date", date);
            } else {
                pageContext.setAttribute("date", "");
            }

            // Time
            time = StringTool.getXMLTagContent("time", sb.toString());

            if (time != null) {
                pageContext.setAttribute("time", time);
            } else {
                pageContext.setAttribute("time", "");
            }

            // Title
            temp = StringTool.getXMLTagContent("title", sb.toString());
            title = StringTool.getXMLTagContent(model.getLocale().getLanguage(), temp);

            if (title != null) {
                pageContext.setAttribute("title", title);
            } else {
                pageContext.setAttribute("title", "");
            }

            // description
            temp = StringTool.getXMLTagContent("description", sb.toString());
            description = StringTool.getXMLTagContent(model.getLocale().getLanguage(), temp);

            if (description != null) {
                pageContext.setAttribute("description", description);
            } else {
                pageContext.setAttribute("description", "");
            }

            pageContext.setAttribute("path", model.getCollection().getPath());
            pageContext.setAttribute("colid", "" + model.getCurrCollectionId());
            pageContext.setAttribute("langcode", "" + model.getLocale().getLanguage());

            return EVAL_BODY_AGAIN;
        } else {
            return SKIP_BODY;
        }
    } catch (Exception ex) {
        return SKIP_BODY;
    }
}

From source file:org.freeeed.services.Util.java

public static int countLines(String filename) throws IOException {
    int cnt;//ww  w.  j a va2 s.co  m
    try (LineNumberReader reader = new LineNumberReader(new FileReader(filename))) {
        String lineRead = "";
        while ((lineRead = reader.readLine()) != null) {
        }
        cnt = reader.getLineNumber();
    }
    return cnt;
}