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:de.bps.course.nodes.vc.provider.wimba.WimbaClassroomProvider.java

private WimbaResponse getResponseDocument(String rawResponse) {
    StringReader input = new StringReader(rawResponse);
    LineNumberReader reader = new LineNumberReader(input);

    WimbaResponse response = new WimbaResponse();
    String line;/*from w w w.  jav  a2 s.  co m*/
    Map<String, String> record = new HashMap<String, String>();
    try {
        // start with status code in first line
        line = reader.readLine();
        response.setStatus(getStatusCode(line));
        // read the records following
        while ((line = reader.readLine()) != null) {
            if (line.equals(DELIM)) {
                // end of record
                response.addRecord(record);
                record = new HashMap<String, String>();
            } else {
                // regular part of a record
                String[] elem = line.split("=", 2);
                record.put(elem[0], elem[1]);
            }
        }
    } catch (IOException e) {
        logError("The Wimba Classroom response could not parsed. Raw response: " + rawResponse, e);
    }

    return response;
}

From source file:org.latticesoft.util.common.FileUtil.java

/**
 * Read lines from an inputstream./*from  www. j  a  v a2  s  . c om*/
 * @param is the InputStream
 * @param close if set to true, after reading the input stream would be closed.
 * @param start the line of the file to read from. Line starts from 0. 
 * If count is 1, 1 line would be skipped.
 * @param end the line of the file to stop reading. The end line is included.
 * @return an collection of the lines read
 */
public static List readLinesFromStream(InputStream is, boolean close, int start, int end) {
    if (is == null) {
        return null;
    }
    ArrayList a = new ArrayList();
    Reader r = null;
    LineNumberReader lr = null;
    try {
        r = new InputStreamReader(is);
        lr = new LineNumberReader(r);
        String line = null;
        do {
            line = lr.readLine();
            int currLine = lr.getLineNumber();
            if (start > 0 && end > 0 && currLine >= start && currLine <= end) {
                if (line != null) {
                    a.add(line);
                }
            }
            if (start == START_OF_FILE && end == END_OF_FILE) {
                if (line != null) {
                    a.add(line);
                }
            }
            if (end > 0 && currLine > end) {
                break;
            }
        } while (line != null);
    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error(e);
        }
    } finally {
        if (close) {
            try {
                lr.close();
            } catch (Exception e) {
            }
            try {
                r.close();
            } catch (Exception e) {
            }
        }
        lr = null;
        r = null;
    }
    return a;
}

From source file:com.castis.sysComp.PoisConverterSysComp.java

public void parseCategoryFile(File file, String sub) throws Exception {
    String line = "";
    FileInputStream in = null;//from   w  ww  .j a  v a2 s .c  o  m
    Reader isReader = null;
    LineNumberReader bufReader = null;

    try {
        String encodingCharset = FILE_CHARSET;

        in = new FileInputStream(file);
        isReader = new InputStreamReader(in, encodingCharset);
        bufReader = new LineNumberReader(isReader);

        boolean first = true;
        while ((line = bufReader.readLine()) != null) {
            if (first == true) {
                first = false;
                continue;
            }

            //Depth, Menu ID, Menu Name, Hidden, Menu Type.
            String result[] = line.split(",");

            String depth = result[0];
            String menuId = result[1];
            String menuName = result[2];
            String hidden = result[3];
            String menuType = result[5];

            if (depth == null || depth.equals("")) {
                throw new DataParsingException("data parsing error(depth)");
            }
            if (menuId == null || menuId.equals("")) {
                throw new DataParsingException("data parsing error(Menu ID)");
            }
            if (menuName == null || menuName.equals("")) {
                throw new DataParsingException("data parsing error(Menu Name)");
            }
            if (hidden == null || hidden.equals("")) {
                throw new DataParsingException("data parsing error(Hidden)");
            }
            if (menuType == null || menuType.equals("")) {
                throw new DataParsingException("data parsing error(Menu Type)");
            }

        }
    } catch (Exception e) {
        String errorMsg = e.getMessage();
        log.error(errorMsg, e);
        throw new DataParsingException(errorMsg, e); //throw(e);

    } finally {
        if (in != null)
            in.close();
        if (isReader != null)
            isReader.close();
        if (bufReader != null)
            bufReader.close();
    }

    String fileName = file.getName();
    int index = fileName.indexOf("-");
    if (index != -1) {
        fileName = fileName.substring(index + 1, fileName.length());
    }

    index = fileName.indexOf("_");

    String targetDir = resultDir;
    if (index != -1) {
        String directory = fileName.substring(0, index);
        targetDir += "/" + sub + "/" + directory;
    }

    try {
        File resultTargetDir = new File(CiFileUtil.getReplaceFullPath(targetDir));
        if (!resultTargetDir.isDirectory()) {
            CiFileUtil.createDirectory(targetDir);
        }

        CiFileUtil.renameFile(file, targetDir, fileName);

    } catch (Exception e) {
        log.error(e.getMessage());
    }

}

From source file:com.bigdata.rdf.sail.webapp.AbstractTestNanoSparqlClient.java

/**
 * Read the contents of a file./*from  www  . j a va 2 s . c o  m*/
 * 
 * @param file
 *            The file.
 * @return It's contents.
 */
protected static String readFromFile(final File file) throws IOException {

    final LineNumberReader r = new LineNumberReader(new FileReader(file));

    try {

        final StringBuilder sb = new StringBuilder();

        String s;
        while ((s = r.readLine()) != null) {

            if (r.getLineNumber() > 1)
                sb.append("\n");

            sb.append(s);

        }

        return sb.toString();

    } finally {

        r.close();

    }

}

From source file:rega.genotype.ui.forms.StartForm.java

private boolean capSequences(String fastaContent) {
    LineNumberReader r = new LineNumberReader(new StringReader(fastaContent));

    try {/*  w  w  w  . java 2 s .co m*/
        while (true) {
            Sequence s = SequenceAlignment.readFastaFileSequence(r, SequenceAlignment.SEQUENCE_DNA, true);
            if (s == null)
                break;

            if (s.isNameCapped())
                return true;
        }
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } catch (FileFormatException e) {
        return false;
    }

    return false;
}

From source file:org.apache.zookeeper.server.quorum.QuorumPeerMainTest.java

/**
 * Verify handling of inconsistent peer type
 *///w w w .  j av  a 2  s .c o m
@Test
public void testInconsistentPeerType() throws Exception {
    ClientBase.setupTestEnv();

    // setup the logger to capture all logs
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    WriterAppender appender = getConsoleAppender(os, Level.INFO);
    Logger qlogger = Logger.getLogger("org.apache.zookeeper.server.quorum");
    qlogger.addAppender(appender);

    // test the most likely situation only: server is stated as observer in
    // servers list, but there's no "peerType=observer" token in config
    try {
        final int CLIENT_PORT_QP1 = PortAssignment.unique();
        final int CLIENT_PORT_QP2 = PortAssignment.unique();
        final int CLIENT_PORT_QP3 = PortAssignment.unique();

        String quorumCfgSection = "server.1=127.0.0.1:" + PortAssignment.unique() + ":"
                + PortAssignment.unique() + ";" + CLIENT_PORT_QP1 + "\nserver.2=127.0.0.1:"
                + PortAssignment.unique() + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP2
                + "\nserver.3=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique()
                + ":observer" + ";" + CLIENT_PORT_QP3;

        MainThread q1 = new MainThread(1, CLIENT_PORT_QP1, quorumCfgSection);
        MainThread q2 = new MainThread(2, CLIENT_PORT_QP2, quorumCfgSection);
        MainThread q3 = new MainThread(3, CLIENT_PORT_QP3, quorumCfgSection);
        q1.start();
        q2.start();
        q3.start();

        Assert.assertTrue("waiting for server 1 being up",
                ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1, CONNECTION_TIMEOUT));
        Assert.assertTrue("waiting for server 2 being up",
                ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP2, CONNECTION_TIMEOUT));
        Assert.assertTrue("waiting for server 3 being up",
                ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP3, CONNECTION_TIMEOUT));

        q1.shutdown();
        q2.shutdown();
        q3.shutdown();

        Assert.assertTrue("waiting for server 1 down",
                ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP1, ClientBase.CONNECTION_TIMEOUT));
        Assert.assertTrue("waiting for server 2 down",
                ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP2, ClientBase.CONNECTION_TIMEOUT));
        Assert.assertTrue("waiting for server 3 down",
                ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP3, ClientBase.CONNECTION_TIMEOUT));

    } finally {
        qlogger.removeAppender(appender);
    }

    LineNumberReader r = new LineNumberReader(new StringReader(os.toString()));
    String line;
    boolean warningPresent = false;
    boolean defaultedToObserver = false;
    Pattern pWarn = Pattern.compile(".*Peer type from servers list.* doesn't match peerType.*");
    Pattern pObserve = Pattern.compile(".*OBSERVING.*");
    while ((line = r.readLine()) != null) {
        if (pWarn.matcher(line).matches()) {
            warningPresent = true;
        }
        if (pObserve.matcher(line).matches()) {
            defaultedToObserver = true;
        }
        if (warningPresent && defaultedToObserver) {
            break;
        }
    }
    Assert.assertTrue("Should warn about inconsistent peer type", warningPresent && defaultedToObserver);
}

From source file:org.kawanfw.sql.jdbc.StatementHttp.java

/**
 * Says if the file contains a ResultSet or if the file contains an
 * UpdateCount. if file contains an UpdateCount ==> first line is numeric
 * /*from   ww  w.j  a v a  2  s. c  o m*/
 * @param file
 *            the received file from the server
 * @return true if the file is a result set
 */
protected boolean isFileResultSet(File file) throws SQLException {

    LineNumberReader lineNumberReader = null;

    try {
        lineNumberReader = new LineNumberReader(new FileReader(file));
        String line = lineNumberReader.readLine();

        line = line.trim();

        if (line.startsWith("getUpdateCount=")) {

            String updateCountStr = StringUtils.substringAfter(line, "getUpdateCount=");

            try {
                updateCount = Integer.parseInt(updateCountStr);
            } catch (NumberFormatException e) {
                throw new SQLException(Tag.PRODUCT_PRODUCT_FAIL + e.getMessage(),
                        new IOException(e.getMessage(), e));
            }

            return false;
        } else if (line.startsWith(CallableParms.NO_RESULT_SET)) {
            return false;
        } else {
            return true;
        }
    } catch (IOException e) {
        JdbcHttpTransferUtil.wrapExceptionAsSQLException(e);
    } finally {
        IOUtils.closeQuietly(lineNumberReader);
    }

    return false;

}

From source file:rega.genotype.ui.forms.StartForm.java

private CharSequence verifyFasta(String fastaContent) {
    int sequenceCount = 0;

    LineNumberReader r = new LineNumberReader(new StringReader(fastaContent));

    try {//  w w  w.  j  a  v  a2 s  . c o m
        while (true) {
            if (SequenceAlignment.readFastaFileSequence(r, SequenceAlignment.SEQUENCE_DNA, true) == null)
                break;
            ++sequenceCount;
        }

        if (sequenceCount == 0) {
            return tr("startForm.noSequence");
        } else if (sequenceCount > Settings.getInstance().getMaxAllowedSeqs()) {
            return tr("startForm.tooManySequences");
        }
    } catch (IOException e) {
        e.printStackTrace();
        return tr("startForm.ioError");
    } catch (FileFormatException e) {
        return e.getMessage();
    }

    return null;
}

From source file:com.netspective.commons.text.TextUtils.java

/**
 * Retrieve lines of text from an input stream
 *
 * @param is              The input stream to read
 * @param startLineNumber The starting line number
 * @param endLineNumber   The ending line number
 *
 * @return The text contained in line numbers startingLineNumber to endingLineNumber
 *//*from  w  w  w .  j a  v a2s  . co  m*/
public String getTextStreamLines(InputStream is, int startLineNumber, int endLineNumber) throws IOException {
    if (is == null)
        return null;

    if (startLineNumber <= 0 && endLineNumber <= 0)
        return null;

    Reader isReader = null;
    LineNumberReader reader = null;
    StringBuffer result = new StringBuffer();

    try {
        isReader = new InputStreamReader(is);
        reader = new LineNumberReader(isReader);

        String line = null;

        if (startLineNumber > 0 && endLineNumber <= 0) {
            while ((line = reader.readLine()) != null) {
                if (reader.getLineNumber() == startLineNumber)
                    return line;
            }

        } else {
            while ((line = reader.readLine()) != null) {
                int lineNumber = reader.getLineNumber();

                if (lineNumber < startLineNumber)
                    continue;

                if (lineNumber > endLineNumber)
                    break;

                result.append(line);
                result.append("\n");
            }
        }
    } finally {
        if (reader != null)
            reader.close();

        if (isReader != null)
            is.close();

        is.close();
    }

    return result.toString();
}

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

/**
 * get the data point interval of report data. Use dataPointCount / imgWidth as the interval. if interval is 1, it
 * means we will get all point from report. If interval is 2, it means we will get 1 point from every 2 data.
 *
 * @param testId   test id//from www .j  ava 2s  . c o  m
 * @param dataType data type
 * @param imgWidth image width
 * @return interval interval value
 */
public int getReportDataInterval(long testId, String dataType, int imgWidth) {
    int pointCount = Math.max(imgWidth, MAX_POINT_COUNT);
    File reportFolder = config.getHome().getPerfTestReportDirectory(String.valueOf(testId));
    int interval = 0;
    File targetFile = new File(reportFolder, dataType + DATA_FILE_EXTENSION);
    if (!targetFile.exists()) {
        LOGGER.warn("Report {} for test {} does not exist.", dataType, testId);
        return 0;
    }
    LineNumberReader lnr = null;

    FileInputStream in = null;
    InputStreamReader isr = null;
    try {
        in = new FileInputStream(targetFile);
        isr = new InputStreamReader(in);
        lnr = new LineNumberReader(isr);
        lnr.skip(targetFile.length());
        int lineNumber = lnr.getLineNumber() + 1;
        interval = Math.max(lineNumber / pointCount, 1);
    } catch (Exception e) {
        LOGGER.error("Failed to get report data for {}", dataType, e);
    } finally {
        IOUtils.closeQuietly(lnr);
        IOUtils.closeQuietly(isr);
        IOUtils.closeQuietly(in);
    }

    return interval;
}