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:org.apache.pdfbox.util.TestTextStripper.java

/**
 * Validate text extraction on a single file.
 *
 * @param inFile The PDF file to validate
 * @param outDir The directory to store the output in
 * @param bLogResult Whether to log the extracted text
 * @param bSort Whether or not the extracted text is sorted
 * @throws Exception when there is an exception
 *///from w  w w  . j a v  a2  s.c om
public void doTestFile(File inFile, File outDir, boolean bLogResult, boolean bSort) throws Exception {
    if (bSort) {
        log.info("Preparing to parse " + inFile.getName() + " for sorted test");
    } else {
        log.info("Preparing to parse " + inFile.getName() + " for standard test");
    }

    if (!outDir.exists()) {
        if (!outDir.mkdirs()) {
            throw (new Exception("Error creating " + outDir.getAbsolutePath() + " directory"));
        }
    }

    PDDocument document = PDDocument.load(inFile);
    try {

        File outFile = null;
        File expectedFile = null;

        if (bSort) {
            outFile = new File(outDir, inFile.getName() + "-sorted.txt");
            expectedFile = new File(inFile.getParentFile(), inFile.getName() + "-sorted.txt");
        } else {
            outFile = new File(outDir, inFile.getName() + ".txt");
            expectedFile = new File(inFile.getParentFile(), inFile.getName() + ".txt");
        }

        OutputStream os = new FileOutputStream(outFile);
        try {
            os.write(0xFF);
            os.write(0xFE);

            Writer writer = new OutputStreamWriter(os, encoding);
            try {
                //Allows for sorted tests 
                stripper.setSortByPosition(bSort);
                stripper.writeText(document, writer);
            } finally {
                // close the written file before reading it again
                writer.close();
            }
        } finally {
            os.close();
        }

        if (bLogResult) {
            log.info("Text for " + inFile.getName() + ":");
            log.info(stripper.getText(document));
        }

        if (!expectedFile.exists()) {
            this.bFail = true;
            log.error("FAILURE: Input verification file: " + expectedFile.getAbsolutePath() + " did not exist");
            return;
        }

        LineNumberReader expectedReader = new LineNumberReader(
                new InputStreamReader(new FileInputStream(expectedFile), encoding));
        LineNumberReader actualReader = new LineNumberReader(
                new InputStreamReader(new FileInputStream(outFile), encoding));

        while (true) {
            String expectedLine = expectedReader.readLine();
            while (expectedLine != null && expectedLine.trim().length() == 0) {
                expectedLine = expectedReader.readLine();
            }
            String actualLine = actualReader.readLine();
            while (actualLine != null && actualLine.trim().length() == 0) {
                actualLine = actualReader.readLine();
            }
            if (!stringsEqual(expectedLine, actualLine)) {
                this.bFail = true;
                log.error("FAILURE: Line mismatch for file " + inFile.getName() + " ( sort = " + bSort + ")"
                        + " at expected line: " + expectedReader.getLineNumber() + " at actual line: "
                        + actualReader.getLineNumber());
                log.error("  expected line was: \"" + expectedLine + "\"");
                log.error("  actual line was:   \"" + actualLine + "\"" + "\n");

                //lets report all lines, even though this might produce some verbose logging
                //break;
            }

            if (expectedLine == null || actualLine == null) {
                break;
            }
        }
    } finally {
        document.close();
    }
}

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

/**
 * Scans a file to look for task tags.//from  w  w  w .  j a va  2 s  .c o 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:net.ontopia.topicmaps.db2tm.CSVImport.java

public void importCSV(InputStream csvfile) throws Exception {
    // Execute statements
    try {//  w  w w. j a  v  a 2s .  c o m
        System.out.println("TABLE: " + table);

        if (cleartable) {
            String delsql = "delete from " + table;
            log.debug("DELETE: {}", delsql);
            Statement delstm = conn.createStatement();
            delstm.executeUpdate(delsql);
            //! conn.commit();
        }

        // get hold of column metadata
        List<String> colnames = new ArrayList<String>();
        List<Integer> coltypes_ = new ArrayList<Integer>();
        ResultSet rs = conn.getMetaData().getColumns(null, null, table, null);
        try {
            while (rs.next()) {
                String colname = rs.getString(4);
                int coltype = rs.getInt(5);
                colnames.add(colname);
                coltypes_.add(new Integer(coltype));
            }
        } finally {
            rs.close();
        }
        int[] coltypes = new int[coltypes_.size()];
        for (int i = 0; i < coltypes.length; i++) {
            coltypes[i] = coltypes_.get(i).intValue();
        }

        String[] qmarks = new String[coltypes.length];
        for (int i = 0; i < qmarks.length; i++) {
            qmarks[i] = "?";
        }

        String sql = "insert into " + table + " (" + StringUtils.join(colnames, ", ") + ") values ("
                + StringUtils.join(qmarks, ", ") + ")";
        log.debug("INSERT: {}", sql);
        PreparedStatement stm = conn.prepareStatement(sql);

        LineNumberReader reader = new LineNumberReader(new InputStreamReader(csvfile));
        CSVReader csvreader = new CSVReader(reader, separator, quoteCharacter);

        // Ignore first X lines
        for (int i = 0; i < ignorelines; i++) {
            String[] tuple = csvreader.readNext();
            if (tuple == null)
                break;
        }

        // HACK: override date+datetime formats
        JDBCUtils.df_date = new SimpleDateFormat("dd.MM.yyyy");
        JDBCUtils.df_datetime = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");

        // Process input
        log.debug("[{}]", StringUtils.join(colnames, ", "));
        String[] tuple = null;
        try {
            while ((tuple = csvreader.readNext()) != null) {
                for (int i = 0; i < tuple.length; i++) {
                    System.out.println("V:" + (i + 1) + " " + colnames.get(i) + ":" + coltypes[i] + " "
                            + tuple[i].length() + "'" + tuple[i] + "'");
                    JDBCUtils.setObject(stm, i + 1, tuple[i], coltypes[i]);
                }
                stm.execute();
            }
        } catch (Exception e) {
            throw new OntopiaRuntimeException(
                    "Cannot read line " + reader.getLineNumber() + ": " + Arrays.asList(tuple), e);
        }
        conn.commit();

    } catch (Exception e) {
        //conn.rollback();
        throw e;
    }
}

From source file:org.apache.pdfbox.text.TestTextStripper.java

/**
 * Validate text extraction on a single file.
 *
 * @param inFile The PDF file to validate
 * @param outDir The directory to store the output in
 * @param bLogResult Whether to log the extracted text
 * @param bSort Whether or not the extracted text is sorted
 * @throws Exception when there is an exception
 *///  www. j av  a2s  .com
public void doTestFile(File inFile, File outDir, boolean bLogResult, boolean bSort) throws Exception {
    if (bSort) {
        log.info("Preparing to parse " + inFile.getName() + " for sorted test");
    } else {
        log.info("Preparing to parse " + inFile.getName() + " for standard test");
    }

    if (!outDir.exists()) {
        if (!outDir.mkdirs()) {
            throw (new Exception("Error creating " + outDir.getAbsolutePath() + " directory"));
        }
    }

    //System.out.println("  " + inFile + (bSort ? " (sorted)" : ""));
    PDDocument document = PDDocument.load(inFile);
    try {
        File outFile;
        File diffFile;
        File expectedFile;

        if (bSort) {
            outFile = new File(outDir, inFile.getName() + "-sorted.txt");
            diffFile = new File(outDir, inFile.getName() + "-sorted-diff.txt");
            expectedFile = new File(inFile.getParentFile(), inFile.getName() + "-sorted.txt");
        } else {
            outFile = new File(outDir, inFile.getName() + ".txt");
            diffFile = new File(outDir, inFile.getName() + "-diff.txt");
            expectedFile = new File(inFile.getParentFile(), inFile.getName() + ".txt");
        }

        // delete possible leftover
        diffFile.delete();

        OutputStream os = new FileOutputStream(outFile);
        try {
            os.write(0xEF);
            os.write(0xBB);
            os.write(0xBF);

            Writer writer = new BufferedWriter(new OutputStreamWriter(os, ENCODING));
            try {
                //Allows for sorted tests 
                stripper.setSortByPosition(bSort);
                stripper.writeText(document, writer);
            } finally {
                // close the written file before reading it again
                writer.close();
            }
        } finally {
            os.close();
        }

        if (bLogResult) {
            log.info("Text for " + inFile.getName() + ":");
            log.info(stripper.getText(document));
        }

        if (!expectedFile.exists()) {
            this.bFail = true;
            log.error("FAILURE: Input verification file: " + expectedFile.getAbsolutePath() + " did not exist");
            return;
        }

        boolean localFail = false;

        LineNumberReader expectedReader = new LineNumberReader(
                new InputStreamReader(new FileInputStream(expectedFile), ENCODING));
        LineNumberReader actualReader = new LineNumberReader(
                new InputStreamReader(new FileInputStream(outFile), ENCODING));

        while (true) {
            String expectedLine = expectedReader.readLine();
            while (expectedLine != null && expectedLine.trim().length() == 0) {
                expectedLine = expectedReader.readLine();
            }
            String actualLine = actualReader.readLine();
            while (actualLine != null && actualLine.trim().length() == 0) {
                actualLine = actualReader.readLine();
            }
            if (!stringsEqual(expectedLine, actualLine)) {
                this.bFail = true;
                localFail = true;
                log.error("FAILURE: Line mismatch for file " + inFile.getName() + " (sort = " + bSort + ")"
                        + " at expected line: " + expectedReader.getLineNumber() + " at actual line: "
                        + actualReader.getLineNumber() + "\nexpected line was: \"" + expectedLine + "\""
                        + "\nactual line was:   \"" + actualLine + "\"" + "\n");

                //lets report all lines, even though this might produce some verbose logging
                //break;
            }

            if (expectedLine == null || actualLine == null) {
                break;
            }
        }
        expectedReader.close();
        actualReader.close();
        if (!localFail) {
            outFile.delete();
        } else {
            // https://code.google.com/p/java-diff-utils/wiki/SampleUsage
            List<String> original = fileToLines(expectedFile);
            List<String> revised = fileToLines(outFile);

            // Compute diff. Get the Patch object. Patch is the container for computed deltas.
            Patch patch = DiffUtils.diff(original, revised);

            PrintStream diffPS = new PrintStream(diffFile, ENCODING);
            for (Object delta : patch.getDeltas()) {
                if (delta instanceof ChangeDelta) {
                    ChangeDelta cdelta = (ChangeDelta) delta;
                    diffPS.println("Org: " + cdelta.getOriginal());
                    diffPS.println("New: " + cdelta.getRevised());
                    diffPS.println();
                } else if (delta instanceof DeleteDelta) {
                    DeleteDelta ddelta = (DeleteDelta) delta;
                    diffPS.println("Org: " + ddelta.getOriginal());
                    diffPS.println("New: " + ddelta.getRevised());
                    diffPS.println();
                } else if (delta instanceof InsertDelta) {
                    InsertDelta idelta = (InsertDelta) delta;
                    diffPS.println("Org: " + idelta.getOriginal());
                    diffPS.println("New: " + idelta.getRevised());
                    diffPS.println();
                } else {
                    diffPS.println(delta);
                }
            }
            diffPS.close();
        }
    } finally {
        document.close();
    }
}

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  ww .j a  v a 2  s.  c o  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;
}

From source file:org.agnitas.beans.impl.MailingImpl.java

@Override
public DynamicTag findNextDynTag(String aTemplate, ApplicationContext con) throws Exception {
    int valueTagStartPos;
    int oldPos;//w w  w  . j  a  va2s.  c o m
    DynamicTag aDynTag = null;
    TagDetails aStartTag = null;
    TagDetails aEndTag = null;
    TagDetails aValueTag = null;

    aStartTag = getOneTag(aTemplate, "agnDYN", searchPos, con);
    if (aStartTag == null)
        return null;

    aStartTag.analyzeParameters();
    aStartTag.findTagParameters();

    searchPos = aStartTag.getEndPos();

    aDynTag = (DynamicTag) con.getBean("DynamicTag");
    aDynTag.setCompanyID(companyID);
    aDynTag.setMailingID(id);
    aDynTag.setComplex(aStartTag.isComplex());
    aDynTag.setDynName(aStartTag.getName());
    int group = 0;

    Map<String, String> params = aStartTag.getTagParameters();

    if (params != null) {
        String gname = (String) params.get("group");

        if (gname != null) {
            DynamicTagDao dao = (DynamicTagDao) con.getBean("DynamicTagDao");
            group = dao.getIdForName(this.id, gname);
        }
    }
    aDynTag.setGroup(group);

    if (aStartTag.isComplex()) {
        oldPos = searchPos;
        do {
            aEndTag = getOneTag(aTemplate, "/agnDYN", searchPos, con);
            if (aEndTag == null) {
                LineNumberReader aReader = new LineNumberReader(new StringReader(aTemplate));
                aReader.skip(searchPos);
                throw new Exception("NoEndTag$" + aReader.getLineNumber() + "$" + aStartTag.getName());
            }
            searchPos = aEndTag.getEndPos();
            aEndTag.analyzeParameters();
        } while (aStartTag.getName().compareTo(aEndTag.getName()) != 0);
        String valueArea = aTemplate.substring(aStartTag.getEndPos(), aEndTag.getStartPos());
        valueTagStartPos = 0;
        do {
            aValueTag = getOneTag(valueArea, "agnDVALUE", valueTagStartPos, con);
            if (aValueTag == null) {
                LineNumberReader aReader = new LineNumberReader(new StringReader(aTemplate));
                aReader.skip(searchPos);
                throw new Exception("NoValueTag$" + aReader.getLineNumber() + "$" + aStartTag.getName());
            }
            valueTagStartPos = aValueTag.getEndPos();
            aValueTag.analyzeParameters();
        } while (aStartTag.getName().compareTo(aValueTag.getName()) != 0);
        searchPos = oldPos;
        aDynTag.setStartTagStart(aStartTag.getStartPos());
        aDynTag.setStartTagEnd(aStartTag.getEndPos());
        aDynTag.setValueTagStart(aStartTag.getEndPos() + aValueTag.getStartPos());
        aDynTag.setValueTagEnd(aStartTag.getEndPos() + aValueTag.getEndPos());
        aDynTag.setEndTagStart(aEndTag.getStartPos());
        aDynTag.setEndTagEnd(aEndTag.getEndPos());
    } else {
        aDynTag.setStartTagStart(aStartTag.getStartPos());
        aDynTag.setStartTagEnd(aStartTag.getEndPos());
    }

    return aDynTag;
}

From source file:massbank.BatchJobWorker.java

/**
 * Ytt@C???ieLXg`?j//from w  w  w .j  av a 2 s . c o  m
 * @param time NGXg 
 * @param resultFile t@C
 * @param textFile YtpeLXgt@C
 */
private void createTextFile(String time, File resultFile, File textFile) {
    NumberFormat nf = NumberFormat.getNumberInstance();
    LineNumberReader in = null;
    PrintWriter out = null;
    try {
        in = new LineNumberReader(new FileReader(resultFile));
        out = new PrintWriter(new BufferedWriter(new FileWriter(textFile)));

        // wb_?[?o
        String reqIonStr = "Both";
        try {
            if (Integer.parseInt(this.ion) > 0) {
                reqIonStr = "Positive";
            } else if (Integer.parseInt(this.ion) < 0) {
                reqIonStr = "Negative";
            }
        } catch (NumberFormatException nfe) {
            nfe.printStackTrace();
        }
        out.println("***** MassBank Batch Service Results *****");
        out.println();
        out.println("Request Date: " + time);
        out.println("# Instrument Type: " + this.inst);
        out.println("# Ion Mode: " + reqIonStr);
        out.println();
        out.println();

        // ?o
        String line;
        long queryCnt = 0;
        boolean readName = false;
        boolean readHit = false;
        boolean readNum = false;
        boolean isFinalLine = false;
        while ((line = in.readLine()) != null) {
            isFinalLine = false;
            if (in.getLineNumber() < 4) {
                continue;
            }
            if (!readName) {
                queryCnt++;
                out.println("### Query " + nf.format(queryCnt) + " ###");
                out.println("# Name: " + line.trim());
                readName = true;
            } else if (!readHit) {
                out.println("# Hit: " + nf.format(Integer.parseInt(line.trim())));
                out.println();
                readHit = true;
            } else if (!readNum) {
                out.println("Top " + line.trim() + " List");
                out.println("Accession\tTitle\tFormula\tIon\tScore\tHit");
                out.println();
                readNum = true;
            } else {
                if (!line.trim().equals("")) {
                    String[] data = formatLine(line);
                    StringBuilder sb = new StringBuilder();
                    sb.append(data[0]).append("\t").append(data[1]).append("\t").append(data[2]).append("\t")
                            .append(data[3]).append("\t").append(data[4]).append("\t").append(data[5]);
                    out.println(sb.toString());
                } else {
                    out.println();
                    out.println();
                    readName = false;
                    readHit = false;
                    readNum = false;
                    isFinalLine = true;
                }
            }
        }
        if (!isFinalLine) {
            out.println();
            out.println();
        }
        out.println("##### END #####");
        out.println();
        out.println("**********************************************************");
        out.println("*  MassBank.jp - High Resolution Mass Spectral Database  *");
        out.println("*    URL: http://www.massbank.jp/                        *");
        out.println("**********************************************************");
        out.println();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
        }
        if (out != null) {
            out.flush();
            out.close();
        }
    }
}

From source file:org.talend.designer.runprocess.java.JavaProcessor.java

/**
 * Find line numbers of the beginning of the code of process nodes.
 * //from  w ww  . j  a va2  s.  c  o m
 * @param file Code file where we are searching node's code.
 * @param nodes List of nodes searched.
 * @return Line numbers where code of nodes appears.
 * @throws CoreException Search failed.
 */
private static int[] getLineNumbers(IFile file, String[] nodes) throws CoreException {
    List<Integer> lineNumbers = new ArrayList<Integer>();

    // List of code's lines searched in the file
    List<String> searchedLines = new ArrayList<String>();
    for (String node : nodes) {
        searchedLines.add(node);
    }

    LineNumberReader lineReader = new LineNumberReader(new InputStreamReader(file.getContents()));
    try {
        String line = lineReader.readLine();
        while (!searchedLines.isEmpty() && line != null) {
            boolean nodeFound = false;
            for (Iterator<String> i = searchedLines.iterator(); !nodeFound && i.hasNext();) {
                String nodeMain = i.next();
                if (line.indexOf(nodeMain) != -1) {
                    nodeFound = true;
                    i.remove();

                    // Search the first valid code line
                    boolean lineCodeFound = false;
                    line = lineReader.readLine();
                    while (line != null && !lineCodeFound) {
                        if (isCodeLine(line)) {
                            lineCodeFound = true;
                            lineNumbers.add(new Integer(lineReader.getLineNumber() + 1));
                        }
                        line = lineReader.readLine();
                    }
                }
            }
            line = lineReader.readLine();
        }
    } catch (IOException ioe) {
        IStatus status = new Status(IStatus.ERROR, "", IStatus.OK, "Source code read failure.", ioe); //$NON-NLS-1$ //$NON-NLS-2$
        throw new CoreException(status);
    }

    int[] res = new int[lineNumbers.size()];
    int pos = 0;
    for (Integer i : lineNumbers) {
        res[pos++] = i.intValue();
    }
    return res;
}

From source file:org.ngrinder.perftest.service.PerfTestService.java

private int getRecordInterval(int imageWidth, File dataFile) {
    int pointCount = Math.max(imageWidth, MAX_POINT_COUNT);
    FileInputStream in = null;/*from   www .  j  av a 2s  . c  o m*/
    InputStreamReader isr = null;
    LineNumberReader lnr = null;
    int interval = 0;
    try {
        in = new FileInputStream(dataFile);
        isr = new InputStreamReader(in);
        lnr = new LineNumberReader(isr);
        lnr.skip(dataFile.length());
        interval = Math.max((lnr.getLineNumber() + 1) / pointCount, 1);
    } catch (FileNotFoundException e) {
        LOGGER.error("data file not exist:{}", dataFile);
        LOGGER.error(e.getMessage(), e);
    } catch (IOException e) {
        LOGGER.error("Error while getting data file:{}", dataFile);
        LOGGER.error(e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(lnr);
        IOUtils.closeQuietly(isr);
        IOUtils.closeQuietly(in);
    }
    return interval;
}

From source file:org.ngrinder.perftest.service.PerfTestService.java

/**
 * Get the monitor data interval value. In the normal, the image width is 700, and if the data count is too big,
 * there will be too many points in the chart. So we will calculate the interval to get appropriate count of data to
 * display. For example, interval value "2" means, get one record for every "2" records.
 *
 * @param testId     test id/*from  w w  w.  j av  a  2  s. c o  m*/
 * @param targetIP   ip address of monitor target
 * @param imageWidth image with of the chart.
 * @return interval value.
 */
public int getMonitorGraphInterval(long testId, String targetIP, int imageWidth) {
    File monitorDataFile = new File(config.getHome().getPerfTestReportDirectory(String.valueOf(testId)),
            MONITOR_FILE_PREFIX + targetIP + ".data");

    int pointCount = Math.max(imageWidth, MAX_POINT_COUNT);
    FileInputStream in = null;
    InputStreamReader isr = null;
    LineNumberReader lnr = null;
    int interval = 0;
    try {
        in = new FileInputStream(monitorDataFile);
        isr = new InputStreamReader(in);
        lnr = new LineNumberReader(isr);
        lnr.skip(monitorDataFile.length());
        int lineNumber = lnr.getLineNumber() + 1;
        interval = Math.max(lineNumber / pointCount, 1);
    } catch (FileNotFoundException e) {
        LOGGER.info("Monitor data file does not exist at {}", monitorDataFile);
    } catch (IOException e) {
        LOGGER.info("Error while getting monitor:{} data file:{}", targetIP, monitorDataFile);
    } finally {
        IOUtils.closeQuietly(lnr);
        IOUtils.closeQuietly(isr);
        IOUtils.closeQuietly(in);
    }
    return interval;
}