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:com.sds.acube.jstor.XNDiscXNApi.java

/**
 * XNDisc XNApi ?  ?// ww w.j  av a 2 s .com
 */
private static void readVersionFromFile() {
    XNDiscXNApi_PublishingVersion = "<unknown>";
    XNDiscXNApi_PublishingDate = "<unknown>";
    InputStreamReader isr = null;
    LineNumberReader lnr = null;
    try {
        isr = new InputStreamReader(XNDiscXNApi.class.getResourceAsStream("/com/sds/acube/jstor/version.txt"));
        if (isr != null) {
            lnr = new LineNumberReader(isr);
            String line = null;
            do {
                line = lnr.readLine();
                if (line != null) {
                    if (line.startsWith("Publishing-Version=")) {
                        XNDiscXNApi_PublishingVersion = line
                                .substring("Publishing-Version=".length(), line.length()).trim();
                    } else if (line.startsWith("Publishing-Date=")) {
                        XNDiscXNApi_PublishingDate = line.substring("Publishing-Date=".length(), line.length())
                                .trim();
                    }
                }
            } while (line != null);
            lnr.close();
        }
    } catch (IOException ioe) {
        XNDiscXNApi_PublishingVersion = "<unknown>";
        XNDiscXNApi_PublishingDate = "<unknown>";
    } finally {
        try {
            if (lnr != null) {
                lnr.close();
            }
            if (isr != null) {
                isr.close();
            }
        } catch (IOException ioe) {
        }
    }
}

From source file:org.jboss.as.test.integration.domain.suites.ResponseStreamTestCase.java

private void readLogStream(InputStream stream, boolean forServer, boolean forMaster) throws IOException {

    LineNumberReader reader = new LineNumberReader(new InputStreamReader(stream, StandardCharsets.UTF_8));

    String expected = LogStreamExtension.getLogMessage(logMessageContent);
    boolean readRegisteredServer = false;
    boolean readRegisteredSlave = false;
    boolean readExpected = false;
    String read;/*w  ww  . jav a 2  s.c  o  m*/
    while ((read = reader.readLine()) != null) {
        readRegisteredServer = readRegisteredServer || read.contains("WFLYHC0020");
        readRegisteredSlave = readRegisteredSlave || read.contains("WFLYHC0019");
        readExpected = readExpected || read.contains(expected);
    }

    if (forServer) {
        Assert.assertFalse(readRegisteredServer);
    } else if (forMaster) {
        Assert.assertTrue(readRegisteredSlave);
    } else {
        Assert.assertFalse(readRegisteredSlave);
        Assert.assertTrue(readRegisteredServer);
    }
    Assert.assertTrue(readExpected);

    reader.close();

}

From source file:net.rptools.lib.io.PackedFile.java

/**
 * Returns an InputStreamReader that corresponds to the zip file path specified. This method should be called only
 * for character-based file contents such as the <b>CONTENT_FILE</b> and <b>PROPERTY_FILE</b>. For binary data, such
 * as images (assets and thumbnails) use {@link #getFileAsInputStream(String)} instead.
 * //from ww  w. j  a  va2 s .c  o  m
 * @param path
 *            zip file archive path entry
 * @return Reader representing the data stream
 * @throws IOException
 */
public LineNumberReader getFileAsReader(String path) throws IOException {
    File explodedFile = getExplodedFile(path);
    if ((!file.exists() && !tmpFile.exists() && !explodedFile.exists()) || removedFileSet.contains(path))
        throw new FileNotFoundException(path);
    if (explodedFile.exists())
        return new LineNumberReader(FileUtil.getFileAsReader(explodedFile));

    ZipEntry entry = new ZipEntry(path);
    ZipFile zipFile = getZipFile();
    InputStream in = null;
    try {
        in = new BufferedInputStream(zipFile.getInputStream(entry));
        if (log.isDebugEnabled()) {
            String type;
            type = FileUtil.getContentType(in);
            if (type == null)
                type = FileUtil.getContentType(explodedFile);
            log.debug("FileUtil.getContentType() returned " + (type != null ? type : "(null)"));
        }
        return new LineNumberReader(new InputStreamReader(in, "UTF-8"));
    } catch (IOException ex) {
        // Don't need to close 'in' since zipFile.close() will do so
        throw ex;
    }
}

From source file:de.innovationgate.wgpublisher.WGPDeployer.java

public String preprocessCode(WGTMLModule mod, String code, int codeOffset) throws WGAPIException {

    // First pass. Process preprocessor tags
    try {//ww  w  .  j  av a 2 s  .co m
        PPTagsPreProcessor preProcessor = new PPTagsPreProcessor(_core, mod);
        code = WGUtils.strReplace(code, "{%", preProcessor, true);
    } catch (RuntimeException e) {
        LOG.error("Error preprocessing WebTML module " + mod.getDocumentKey(), e);
    }

    // Process <@ preprocessor if enabled
    if (mod.isPreprocess()) {
        try {
            //code = code.replaceAll("@@([\\w|\\$]+)", "<tml:item name=\"$1\"/>");
            PPPreProcessor pppreProcessor = new PPPreProcessor(_core, mod);
            code = WGUtils.strReplace(code, "@{", pppreProcessor, true);
        } catch (RuntimeException e) {
            LOG.error("Error preprocessing WebTML module " + mod.getDocumentKey(), e);
        }
    }

    // Second pass. Process WebTML tags
    LineNumberReader reader = new LineNumberReader(new StringReader(code));
    StringBuffer out = new StringBuffer();
    TMLTagsPreProcessor linePreProcessor = new TMLTagsPreProcessor();
    String line;
    boolean firstLine = true;
    try {
        while ((line = reader.readLine()) != null) {
            if (!firstLine) {
                out.append("\n");
            } else {
                firstLine = false;
            }
            linePreProcessor.setLineNumber(codeOffset + reader.getLineNumber());
            out.append(WGUtils.strReplace(line, "<tml:", linePreProcessor, true));
        }
        code = out.toString();
    } catch (IOException e) {
        LOG.error("Error adding line numbers to WebTML code", e);
    }

    // Third pass. Process WebTML close tags
    code = WGUtils.strReplace(code, "</tml:", new TMLCloseTagsPreProcessor(), true);

    return code;
}

From source file:org.apache.isis.objectstore.nosql.db.file.server.FileServer.java

private void recover(final File file) {
    LineNumberReader reader = null;
    try {/*w  w w .j  a  v  a2  s.  com*/
        reader = new LineNumberReader(new InputStreamReader(new FileInputStream(file), Util.ENCODING));

        while (true) {
            final String line = reader.readLine();
            if (line == null) {
                break;
            }
            if (!line.startsWith("#transaction started")) {
                throw new NoSqlStoreException(
                        "No transaction start found: " + line + " (" + reader.getLineNumber() + ")");
            }
            readTransaction(reader);
        }
    } catch (final IOException e) {
        throw new NoSqlStoreException(e);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException e) {
                throw new NoSqlStoreException(e);
            }
        }
    }
}

From source file:com.roche.sequencing.bioinformatics.common.utils.FileUtil.java

public static FileComparisonResults compareTextFiles(File fileOne, File fileTwo, boolean ignoreEndOfLine,
        boolean ignoreCommentLines, boolean caseInsensitiveComparison, int[] linesInFileOneToIgnore,
        int[] linesInFileTwoToIgnore) throws IOException {
    List<Integer> fileOnesLinesThatDiffer = new ArrayList<Integer>();
    List<Integer> fileTwosLinesThatDiffer = new ArrayList<Integer>();

    boolean endOfLinesMatch = true;

    boolean fileOneHasAdditionalLines = false;
    boolean fileTwoHasAdditionalLines = false;

    if (fileOne.length() > 0 && fileTwo.length() > 0) {

        if (fileOne.length() > 4096 && fileTwo.length() > 4096) {
            if (!isTextFile(fileOne)) {
                throw new IllegalStateException(
                        "The provided file[" + fileOne.getAbsolutePath() + "] is not a text file.");
            }/*from w  ww .  j  ava  2s.  co  m*/

            if (!isTextFile(fileTwo)) {
                throw new IllegalStateException(
                        "The provided file[" + fileTwo.getAbsolutePath() + "] is not a text file.");
            }
        }

        String firstFileEOL = getFirstLineEndOfLineSymbolsAsString(fileOne);
        String secondFileEOL = getFirstLineEndOfLineSymbolsAsString(fileTwo);
        if (firstFileEOL == null && secondFileEOL == null) {
            endOfLinesMatch = true;
        } else if (firstFileEOL != null && secondFileEOL != null) {
            endOfLinesMatch = firstFileEOL.equals(secondFileEOL);
        } else {
            // one is null and one is not null
            endOfLinesMatch = false;
        }

        Set<Integer> fileOneLinesToIgnoreSet = new HashSet<Integer>();
        if (linesInFileOneToIgnore != null) {
            for (int i : linesInFileOneToIgnore) {
                fileOneLinesToIgnoreSet.add(i);
            }
        }

        Set<Integer> fileTwoLinesToIgnoreSet = new HashSet<Integer>();
        if (linesInFileTwoToIgnore != null) {
            for (int i : linesInFileTwoToIgnore) {
                fileTwoLinesToIgnoreSet.add(i);
            }
        }

        try (LineNumberReader reader1 = new LineNumberReader(new FileReader(fileOne))) {
            try (LineNumberReader reader2 = new LineNumberReader(new FileReader(fileTwo))) {
                String file1Line = reader1.readLine();
                String file2Line = reader2.readLine();

                while (file1Line != null || file2Line != null) {
                    while (file1Line != null && fileOneLinesToIgnoreSet.contains(reader1.getLineNumber())) {
                        file1Line = reader1.readLine();
                    }

                    while (file2Line != null && fileTwoLinesToIgnoreSet.contains(reader2.getLineNumber())) {
                        file2Line = reader2.readLine();
                    }

                    if (ignoreCommentLines) {
                        while (file1Line != null && file1Line.startsWith("#")) {
                            file1Line = reader1.readLine();
                        }

                        while (file2Line != null && file2Line.startsWith("#")) {
                            file2Line = reader2.readLine();
                        }
                    }

                    boolean areEqual = true;

                    if (file1Line == null && file2Line == null) {
                        areEqual = true;
                    } else if ((file1Line == null && file2Line != null)
                            || ((file1Line != null) && (file2Line == null))) {
                        areEqual = false;
                    } else if (caseInsensitiveComparison) {
                        areEqual = file1Line.equalsIgnoreCase(file2Line);
                    } else {
                        areEqual = file1Line.equals(file2Line);
                    }

                    if (!areEqual) {
                        fileOnesLinesThatDiffer.add(reader1.getLineNumber());
                        fileTwosLinesThatDiffer.add(reader2.getLineNumber());
                    }

                    file1Line = reader1.readLine();
                    file2Line = reader2.readLine();
                }

                fileOneHasAdditionalLines = file1Line != null;
                fileTwoHasAdditionalLines = file2Line != null;
            }
        }
    }

    boolean filesAreEqual = fileOnesLinesThatDiffer.size() == 0 && !fileOneHasAdditionalLines
            && !fileTwoHasAdditionalLines;
    if (filesAreEqual) {
        filesAreEqual = ignoreEndOfLine || (!ignoreEndOfLine && endOfLinesMatch);
    }

    FileComparisonResults result = new FileComparisonResults(filesAreEqual, endOfLinesMatch,
            fileOneHasAdditionalLines, fileTwoHasAdditionalLines,
            ArraysUtil.convertToIntArray(fileOnesLinesThatDiffer),
            ArraysUtil.convertToIntArray(fileTwosLinesThatDiffer));
    return result;
}

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

/**
 * Verify handling of bad quorum address
 *//*from  www .  java 2 s  .com*/
@Test
public void testBadPeerAddressInQuorum() throws Exception {
    ClientBase.setupTestEnv();

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

    try {
        final int CLIENT_PORT_QP1 = PortAssignment.unique();
        final int CLIENT_PORT_QP2 = PortAssignment.unique();

        String quorumCfgSection = "server.1=127.0.0.1:" + PortAssignment.unique() + ":"
                + PortAssignment.unique() + ";" + CLIENT_PORT_QP1 + "\nserver.2=fee.fii.foo.fum:"
                + PortAssignment.unique() + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP2;

        MainThread q1 = new MainThread(1, CLIENT_PORT_QP1, quorumCfgSection);
        q1.start();

        boolean isup = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1, 30000);

        Assert.assertFalse("Server never came up", isup);

        q1.shutdown();

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

    } finally {
        qlogger.removeAppender(appender);
    }

    LineNumberReader r = new LineNumberReader(new StringReader(os.toString()));
    String line;
    boolean found = false;
    Pattern p = Pattern.compile(".*Cannot open channel to .* at election address .*");
    while ((line = r.readLine()) != null) {
        found = p.matcher(line).matches();
        if (found) {
            break;
        }
    }
    Assert.assertTrue("complains about host", found);
}

From source file:org.opencms.synchronize.CmsSynchronize.java

/**
 * Reads the synchronization list from the last sync process form the file
 * system and stores the information in a HashMap. <p>
 * //  ww  w.j a  v a2s .c o  m
 * Filenames are stored as keys, CmsSynchronizeList objects as values.
 * @return HashMap with synchronization information of the last sync process
 * @throws CmsException if something goes wrong
 */
private HashMap readSyncList() throws CmsException {

    HashMap syncList = new HashMap();

    // the sync list file in the server fs
    File syncListFile;
    syncListFile = new File(m_destinationPathInRfs, SYNCLIST_FILENAME);
    // try to read the sync list file if it is there
    if (syncListFile.exists()) {
        // prepare the streams to write the data
        FileReader fIn = null;
        LineNumberReader lIn = null;
        try {
            fIn = new FileReader(syncListFile);
            lIn = new LineNumberReader(fIn);
            // read one line from the file
            String line = lIn.readLine();
            while (line != null) {
                line = lIn.readLine();
                // extract the data and create a CmsSychroizedList object
                //  from it
                if (line != null) {
                    StringTokenizer tok = new StringTokenizer(line, ":");
                    String resName = tok.nextToken();
                    String tranResName = tok.nextToken();
                    long modifiedVfs = new Long(tok.nextToken()).longValue();
                    long modifiedFs = new Long(tok.nextToken()).longValue();
                    CmsSynchronizeList sync = new CmsSynchronizeList(resName, tranResName, modifiedVfs,
                            modifiedFs);
                    syncList.put(translate(resName), sync);
                }
            }
        } catch (IOException e) {
            throw new CmsSynchronizeException(Messages.get().container(Messages.ERR_READ_SYNC_LIST_0), e);
        } finally {
            // close all streams that were used
            try {
                if (lIn != null) {
                    lIn.close();
                }
                if (fIn != null) {
                    fIn.close();
                }
            } catch (IOException e) {
                // ignore
            }
        }
    }

    return syncList;
}

From source file:org.opennms.netmgt.ackd.readers.HypericAckProcessor.java

/**
 * <p>parseHypericAlerts</p>
 *
 * @param reader a {@link java.io.Reader} object.
 * @return a {@link java.util.List} object.
 * @throws javax.xml.bind.JAXBException if any.
 * @throws javax.xml.stream.XMLStreamException if any.
 *//*from   w ww. j  a  v a2  s.  c  om*/
public static List<HypericAlertStatus> parseHypericAlerts(Reader reader)
        throws JAXBException, XMLStreamException {
    List<HypericAlertStatus> retval = new ArrayList<HypericAlertStatus>();

    // Instantiate a JAXB context to parse the alert status
    JAXBContext context = JAXBContext
            .newInstance(new Class[] { HypericAlertStatuses.class, HypericAlertStatus.class });
    XMLInputFactory xmlif = XMLInputFactory.newInstance();
    XMLEventReader xmler = xmlif.createXMLEventReader(reader);
    EventFilter filter = new EventFilter() {
        @Override
        public boolean accept(XMLEvent event) {
            return event.isStartElement();
        }
    };
    XMLEventReader xmlfer = xmlif.createFilteredReader(xmler, filter);
    // Read up until the beginning of the root element
    StartElement startElement = (StartElement) xmlfer.nextEvent();
    // Fetch the root element name for {@link HypericAlertStatus} objects
    String rootElementName = context.createJAXBIntrospector().getElementName(new HypericAlertStatuses())
            .getLocalPart();
    if (rootElementName.equals(startElement.getName().getLocalPart())) {
        Unmarshaller unmarshaller = context.createUnmarshaller();
        // Use StAX to pull parse the incoming alert statuses
        while (xmlfer.peek() != null) {
            Object object = unmarshaller.unmarshal(xmler);
            if (object instanceof HypericAlertStatus) {
                HypericAlertStatus alertStatus = (HypericAlertStatus) object;
                retval.add(alertStatus);
            }
        }
    } else {
        // Try to pull in the HTTP response to give the user a better idea of what went wrong
        StringBuffer errorContent = new StringBuffer();
        LineNumberReader lineReader = new LineNumberReader(reader);
        try {
            String line;
            while (true) {
                line = lineReader.readLine();
                if (line == null) {
                    break;
                } else {
                    errorContent.append(line.trim());
                }
            }
        } catch (IOException e) {
            errorContent.append("Exception while trying to print out message content: " + e.getMessage());
        }

        // Throw an exception and include the erroneous HTTP response in the exception text
        throw new JAXBException("Found wrong root element in Hyperic XML document, expected: \""
                + rootElementName + "\", found \"" + startElement.getName().getLocalPart() + "\"\n"
                + errorContent.toString());
    }
    return retval;
}

From source file:architecture.common.spring.jdbc.core.ExtendedJdbcTemplate.java

protected Object runScript(Connection conn, boolean stopOnError, Reader reader)
        throws SQLException, IOException {

    StringBuffer command = null;/*from w w  w . j  a  va  2  s  .  c  o m*/
    List<Object> list = new ArrayList<Object>();
    try {
        LineNumberReader lineReader = new LineNumberReader(reader);
        String line = null;
        while ((line = lineReader.readLine()) != null) {
            if (command == null) {
                command = new StringBuffer();
            }
            String trimmedLine = line.trim();
            if (trimmedLine.startsWith("--")) {
                if (logger.isDebugEnabled())
                    logger.debug(trimmedLine);
            } else if (trimmedLine.length() < 1 || trimmedLine.startsWith("//")) {
                // Do nothing
            } else if (trimmedLine.length() < 1 || trimmedLine.startsWith("--")) {
                // Do nothing
            } else if (trimmedLine.endsWith(";")) {
                command.append(line.substring(0, line.lastIndexOf(";")));
                command.append(" ");

                Statement statement = conn.createStatement();
                if (logger.isDebugEnabled()) {
                    logger.debug("Executing SQL script command [" + command + "]");
                }

                boolean hasResults = false;
                if (stopOnError) {
                    hasResults = statement.execute(command.toString());
                } else {
                    try {
                        statement.execute(command.toString());
                    } catch (SQLException e) {
                        if (logger.isDebugEnabled())
                            logger.error("Error executing: " + command, e);
                        throw e;
                    }
                }
                ResultSet rs = statement.getResultSet();
                if (hasResults && rs != null) {
                    RowMapperResultSetExtractor<Map<String, Object>> rse = new RowMapperResultSetExtractor<Map<String, Object>>(
                            getColumnMapRowMapper());
                    List<Map<String, Object>> rows = rse.extractData(rs);
                    list.add(rows);
                }
                command = null;
            } else {
                command.append(line);
                command.append(" ");
            }
        }

        return list;
    } catch (SQLException e) {
        logger.error("Error executing: " + command, e);
        throw e;
    } catch (IOException e) {
        logger.error("Error executing: " + command, e);
        throw e;
    }
}