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:name.martingeisse.ecobuild.moduletool.output.OutputTool.java

@Override
public void execute(IModuleToolContext context) throws IOException {
    FileReader buildScriptReader;
    try {//from w  ww.ja  v a  2  s .c  o m
        buildScriptReader = new FileReader(new File(context.getModuleSourceFolder(), "build.txt"));
    } catch (FileNotFoundException e) {
        throw new UserMessageBuildException(
                "Output build script 'build.txt' not found for module " + context.getModuleSourceFolder());
    }
    LineNumberReader lineReader = new LineNumberReader(buildScriptReader);
    State state = new State();
    state.currentFolder = context.getMainBuildFolder();
    state.folderStack = new Stack<File>();
    while (true) {
        String line = lineReader.readLine();
        if (line == null) {
            break;
        }
        handleLine(context, state, line);
    }
    buildScriptReader.close();
}

From source file:net.sf.keystore_explorer.crypto.signing.JarSigner.java

private static String getManifestEntryAttrs(JarFile jar, String entryName) throws IOException {

    // Get full manifest content
    String manifestContent = getManifest(jar);

    LineNumberReader lnr = new LineNumberReader(new StringReader(manifestContent));

    try {//  w  ww. ja  v a 2 s. com
        StringBuilder sb = new StringBuilder();

        String line = null;

        // First entry name attribute to match
        String entryNameAttr = createAttributeText(NAME_ATTR, entryName);

        // Only match on first 70 characters (max line length)
        if (entryNameAttr.length() > 70) {
            entryNameAttr = entryNameAttr.substring(0, 70);
        }

        // Keep reading and ignoring lines until entry is found - the end of the entry's attributes
        while ((line = lnr.readLine()) != null) {
            if (line.equals(entryNameAttr)) {
                // Found entry name attribute - append it
                sb.append(line);
                sb.append(CRLF);
                break;
            }
        }

        // Keep reading until a blank line is found - the end of the entry's
        // attributes
        while ((line = lnr.readLine()) != null) {
            if (line.trim().length() == 0) {
                break;
            }

            // Append another entry attribute line
            sb.append(line);
            sb.append(CRLF);
        }

        return sb.toString();
    } finally {
        IOUtils.closeQuietly(lnr);
    }
}

From source file:org.codehaus.mojo.taglist.FileAnalyser.java

/**
 * Scans a file to look for task tags.//from   w ww . ja v  a2s  . co  m
 * 
 * @param file the file to scan.
 */
public void scanFile(File file) {
    LineNumberReader reader = null;

    try {
        reader = new LineNumberReader(getReader(file));

        String currentLine = reader.readLine();
        while (currentLine != null) {
            int index = -1;
            Iterator iter = tagClasses.iterator();
            // look for a tag on this line
            while (iter.hasNext()) {
                TagClass tagClass = (TagClass) iter.next();
                index = tagClass.tagMatchContains(currentLine, locale);
                if (index != TagClass.NO_MATCH) {
                    // there's a tag on this line
                    String commentType = null;
                    commentType = extractCommentType(currentLine, index);

                    if (commentType == null) {
                        // this is not a valid comment tag: skip other tag classes and
                        // go to the next line
                        break;
                    }

                    int tagLength = tagClass.getLastTagMatchStringLength();
                    int commentStartIndex = reader.getLineNumber();
                    StringBuffer comment = new StringBuffer();

                    String firstLine = StringUtils.strip(currentLine.substring(index + tagLength));
                    firstLine = StringUtils.removeEnd(firstLine, "*/"); //MTAGLIST-35
                    if (firstLine.length() == 0 || ":".equals(firstLine)) {
                        // this is not a valid comment tag: nothing is written there
                        if (emptyCommentsOn) {
                            comment.append("--");
                            comment.append(noCommentString);
                            comment.append("--");
                        } else {
                            continue;
                        }
                    } else {
                        // this tag has a comment
                        if (firstLine.charAt(0) == ':') {
                            comment.append(firstLine.substring(1).trim());
                        } else {
                            comment.append(firstLine);
                        }

                        if (multipleLineCommentsOn) {
                            // Mark the current position, set the read forward limit to
                            // a large number that should not be met.
                            reader.mark(MAX_COMMENT_CHARACTERS);

                            // next line
                            String futureLine = reader.readLine();

                            // we're looking for multiple line comments
                            while (futureLine != null && futureLine.trim().startsWith(commentType)
                                    && futureLine.indexOf(tagClass.getLastTagMatchString()) < 0) {
                                String currentComment = futureLine
                                        .substring(futureLine.indexOf(commentType) + commentType.length())
                                        .trim();
                                if (currentComment.startsWith("@") || "".equals(currentComment)
                                        || "/".equals(currentComment)) {
                                    // the comment is finished
                                    break;
                                }
                                // try to look if the next line is not a new tag
                                boolean newTagFound = false;
                                Iterator moreTCiter = tagClasses.iterator();
                                while (moreTCiter.hasNext()) {
                                    TagClass tc = (TagClass) moreTCiter.next();
                                    if (tc.tagMatchStartsWith(currentComment, locale)) {
                                        newTagFound = true;
                                        break;
                                    }
                                }
                                if (newTagFound) {
                                    // this is a new comment: stop here the current comment
                                    break;
                                }
                                // nothing was found: this means the comment is going on this line
                                comment.append(" ");
                                comment.append(currentComment);
                                futureLine = reader.readLine();
                            }

                            // Reset the reader to the marked position before the multi
                            // line check was performed.
                            reader.reset();
                        }
                    }
                    TagReport tagReport = tagClass.getTagReport();
                    FileReport fileReport = tagReport.getFileReport(file, encoding);
                    fileReport.addComment(comment.toString(), commentStartIndex);
                }
            }
            currentLine = reader.readLine();
        }
    } catch (IOException e) {
        log.error("Error while scanning the file " + file.getPath(), e);
    } finally {
        IOUtil.close(reader);
    }
}

From source file:com.datatorrent.stram.StramLocalClusterTest.java

/**
 * Verify test configuration launches and stops after input terminates.
 * Test validates expected output end to end.
 *
 * @throws Exception/*from   www. j a v  a2 s  . c  o  m*/
 */
@Test
public void testLocalClusterInitShutdown() throws Exception {
    TestGeneratorInputOperator genNode = dag.addOperator("genNode", TestGeneratorInputOperator.class);
    genNode.setMaxTuples(2);

    GenericTestOperator node1 = dag.addOperator("node1", GenericTestOperator.class);
    node1.setEmitFormat("%s >> node1");

    File outFile = new File(
            "./target/" + StramLocalClusterTest.class.getName() + "-testLocalClusterInitShutdown.out");
    outFile.delete();

    TestOutputOperator outNode = dag.addOperator("outNode", TestOutputOperator.class);
    outNode.pathSpec = outFile.toURI().toString();

    dag.addStream("fromGenNode", genNode.outport, node1.inport1);

    dag.addStream("fromNode1", node1.outport1, outNode.inport);

    dag.getAttributes().put(LogicalPlan.CONTAINERS_MAX_COUNT, 2);

    StramLocalCluster localCluster = new StramLocalCluster(dag);
    localCluster.setHeartbeatMonitoringEnabled(false);
    localCluster.run();

    Assert.assertTrue(outFile + " exists", outFile.exists());
    LineNumberReader lnr = new LineNumberReader(new FileReader(outFile));
    String line;
    while ((line = lnr.readLine()) != null) {
        Assert.assertTrue("line match " + line, line.matches("" + lnr.getLineNumber() + " >> node1"));
    }
    Assert.assertEquals("number lines", 2, lnr.getLineNumber());
    lnr.close();
}

From source file:mitm.common.postfix.PostfixLogParser.java

public int getRawLogCount(Reader log) throws IOException {
    LineNumberReader lineReader = new LineNumberReader(log);

    int count = 0;

    String line;//w w  w . ja  v  a  2 s  .co m

    while ((line = lineReader.readLine()) != null) {
        line = StringUtils.trimToNull(line);

        if (line == null) {
            continue;
        }

        if (searchPattern != null) {
            Matcher matcher = searchPattern.matcher(line);

            if (matcher.find()) {
                count++;
            }
        } else {
            count++;
        }
    }

    return count;
}

From source file:org.apache.hadoop.yarn.server.nodemanager.TestLinuxContainerExecutorWithMocks.java

private List<String> readMockParams() throws IOException {
    LinkedList<String> ret = new LinkedList<String>();
    LineNumberReader reader = new LineNumberReader(new FileReader(mockParamFile));
    String line;/*  w  ww .j  a  va 2s.  co m*/
    while ((line = reader.readLine()) != null) {
        ret.add(line);
    }
    reader.close();
    return ret;
}

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  www .j  av a  2  s.  com

    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:pl.otros.logview.importer.UtilLoggingXmlLogImporter.java

@Override
public void importLogs(InputStream in, LogDataCollector collector, ParsingContext parsingContext) {

    StringBuffer sb = new StringBuffer();
    try {/*  w w w . j  a  v  a  2  s . c  o  m*/
        LineNumberReader bin = new LineNumberReader(new InputStreamReader(in, ENCODING));
        String line = null;

        while ((line = bin.readLine()) != null) {
            sb.append(line).append("\n");
            if (bin.getLineNumber() % 30 == 0) {
                decodeEvents(sb.toString(), collector, parsingContext);
                sb.setLength(0);
            }
        }

    } catch (UnsupportedEncodingException e) {
        LOGGER.severe("Cant load codepage " + e.getMessage());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        decodeEvents(sb.toString(), collector, parsingContext);
    }

}

From source file:mitm.common.postfix.PostfixLogParser.java

public List<String> getRawLogItems(Reader log, final int startIndex, final int maxItems) throws IOException {
    if (startIndex < 0) {
        throw new IllegalArgumentException("startIndex must be >= 0");
    }/*from  w ww .j av  a  2 s  . c o  m*/

    if (maxItems <= 0) {
        throw new IllegalArgumentException("maxItems must be > 0");
    }

    List<String> logLines = new LinkedList<String>();

    LineNumberReader lineReader = new LineNumberReader(log);

    int index = 0;

    String line;

    while ((line = lineReader.readLine()) != null) {
        line = StringUtils.trimToNull(line);

        if (line == null) {
            continue;
        }

        if (searchPattern == null) {
            if (index >= startIndex) {
                logLines.add(line);
            }

            index++;
        } else {
            /*
             * Search pattern is given. We *must* always check if there is a match
             * before doing anything else
             */
            Matcher matcher = searchPattern.matcher(line);

            if (matcher.find()) {
                if (index >= startIndex) {
                    logLines.add(line);
                }

                index++;
            }
        }

        if (logLines.size() > maxItems) {
            break;
        }
    }

    return logLines;
}

From source file:org.kalypso.ogc.sensor.adapter.NativeObservationDWD5minAdapter.java

@Override
protected List<NativeObservationDataSet> parse(final File source, final TimeZone timeZone,
        final boolean continueWithErrors, final IStatusCollector stati) throws IOException {
    final List<NativeObservationDataSet> datasets = new ArrayList<>();

    final SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd"); //$NON-NLS-1$
    sdf.setTimeZone(timeZone);/*w w w .  j a  v a2s. co  m*/

    final FileReader fileReader = new FileReader(source);
    final LineNumberReader reader = new LineNumberReader(fileReader);

    try {
        String lineIn = null;
        int valuesLine = 0;
        int step = SEARCH_BLOCK_HEADER;
        final StringBuffer buffer = new StringBuffer();
        long startDate = 0;

        while ((lineIn = reader.readLine()) != null) {
            if (!continueWithErrors && getErrorCount() > getMaxErrorCount())
                return datasets;

            switch (step) {
            case SEARCH_BLOCK_HEADER:
                final Matcher matcher = DWD_BLOCK_PATTERN.matcher(lineIn);
                if (matcher.matches()) {
                    // String DWDID = matcher.group( 1 );
                    final String startDateString = matcher.group(2);

                    final Matcher dateMatcher = DATE_PATTERN.matcher(startDateString);
                    if (dateMatcher.matches()) {
                        // System.out.println( "Startdatum Header:" + startDateString );
                        try {
                            final Date parseDate = sdf.parse(startDateString);
                            startDate = parseDate.getTime();
                        } catch (final ParseException e) {
                            e.printStackTrace();

                            stati.add(IStatus.WARNING,
                                    String.format(Messages.getString("NativeObservationDWD5minAdapter_0"), //$NON-NLS-1$
                                            reader.getLineNumber(), startDateString, DATE_PATTERN.toString()),
                                    e);
                            tickErrorCount();
                        }
                    } else {
                        stati.add(IStatus.INFO,
                                String.format(Messages.getString("NativeObservationDWD5minAdapter_0"), //$NON-NLS-1$
                                        reader.getLineNumber(), startDateString, DATE_PATTERN.toString()));
                    }
                } else {
                    stati.add(IStatus.WARNING,
                            String.format(Messages.getString("NativeObservationDWD5minAdapter_1"), //$NON-NLS-1$
                                    reader.getLineNumber(), lineIn));
                    tickErrorCount();
                }

                step++;
                break;

            case SEARCH_VALUES:
                valuesLine = valuesLine + 1;
                for (int i = 0; i < 16; i++) {
                    final String valueString = lineIn.substring(i * 5, 5 * (i + 1));
                    Double value = new Double(Double.parseDouble(valueString)) / 1000;
                    // TODO: Write status

                    String src = SOURCE_ID;

                    if (value > 99.997) {
                        value = 0.0;
                        src = SOURCE_ID_MISSING_VALUE;
                    }

                    // Datenfilter fr 0.0 - um Datenbank nicht mit unntigen Werten zu fllen (Zur Zeit nicht verwendet, da
                    // Rohdaten bentigt)
                    buffer.append(" "); // separator //$NON-NLS-1$
                    final Date valueDate = new Date(
                            startDate + i * m_timeStep + (valuesLine - 1) * 16 * m_timeStep);
                    buffer.append(valueDate.toString());

                    datasets.add(new NativeObservationDataSet(valueDate, value, toStatus(src), src));
                }
                if (valuesLine == 18) {
                    step = SEARCH_BLOCK_HEADER;
                    valuesLine = 0;
                }
                break;
            default:
                break;
            }
        }
    } finally {
        IOUtils.closeQuietly(reader);
    }

    return datasets;
}