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:hobby.wei.c.phone.Network.java

public static String DNS(int n, boolean format) {
    String dns = null;//from  w w  w  .j a  va 2  s  .  c o m
    Process process = null;
    LineNumberReader reader = null;
    try {
        final String CMD = "getprop net.dns" + (n <= 1 ? 1 : 2);

        process = Runtime.getRuntime().exec(CMD);
        reader = new LineNumberReader(new InputStreamReader(process.getInputStream()));

        String line = null;
        while ((line = reader.readLine()) != null) {
            dns = line.trim();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (reader != null)
                reader.close();
            if (process != null)
                process.destroy(); //??
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return format ? (dns != null ? dns.replace('.', '_') : dns) : dns;
}

From source file:com.l2jfree.gameserver.geodata.pathfinding.geonodes.GeoPathFinding.java

private GeoPathFinding() {
    LineNumberReader lnr = null;/*from   w ww. j  a  v  a2  s .c o  m*/
    try {
        _log.info("PathFinding Engine: - Loading Path Nodes...");
        File Data = new File("./data/pathnode/pn_index.txt");
        if (!Data.exists())
            return;

        lnr = new LineNumberReader(new BufferedReader(new FileReader(Data)));
    } catch (Exception e) {
        throw new Error("Failed to Load pn_index File.", e);
    }
    String line;
    try {
        while ((line = lnr.readLine()) != null) {
            if (line.trim().length() == 0)
                continue;
            StringTokenizer st = new StringTokenizer(line, "_");
            byte rx = Byte.parseByte(st.nextToken());
            byte ry = Byte.parseByte(st.nextToken());
            LoadPathNodeFile(rx, ry);
        }
    } catch (Exception e) {
        throw new Error("Failed to Read pn_index File.", e);
    } finally {
        try {
            lnr.close();
        } catch (Exception e) {
        }
    }
}

From source file:org.apache.jackrabbit.oak.plugins.blob.MarkSweepGarbageCollector.java

/**
 * Returns the stats related to GC for all repos
 * //from  w  w  w  . j a  v a  2 s .c  om
 * @return a list of GarbageCollectionRepoStats objects
 * @throws Exception
 */
@Override
public List<GarbageCollectionRepoStats> getStats() throws Exception {
    List<GarbageCollectionRepoStats> stats = newArrayList();
    if (SharedDataStoreUtils.isShared(blobStore)) {
        // Get all the references available
        List<DataRecord> refFiles = ((SharedDataStore) blobStore)
                .getAllMetadataRecords(SharedStoreRecordType.REFERENCES.getType());
        Map<String, DataRecord> references = Maps.uniqueIndex(refFiles, new Function<DataRecord, String>() {
            @Override
            public String apply(DataRecord input) {
                return SharedStoreRecordType.REFERENCES.getIdFromName(input.getIdentifier().toString());
            }
        });

        // Get all the markers available
        List<DataRecord> markerFiles = ((SharedDataStore) blobStore)
                .getAllMetadataRecords(SharedStoreRecordType.MARKED_START_MARKER.getType());
        Map<String, DataRecord> markers = Maps.uniqueIndex(markerFiles, new Function<DataRecord, String>() {
            @Override
            public String apply(DataRecord input) {
                return SharedStoreRecordType.MARKED_START_MARKER
                        .getIdFromName(input.getIdentifier().toString());
            }
        });

        // Get all the repositories registered
        List<DataRecord> repoFiles = ((SharedDataStore) blobStore)
                .getAllMetadataRecords(SharedStoreRecordType.REPOSITORY.getType());

        for (DataRecord repoRec : repoFiles) {
            String id = SharedStoreRecordType.REFERENCES.getIdFromName(repoRec.getIdentifier().toString());
            GarbageCollectionRepoStats stat = new GarbageCollectionRepoStats();
            stat.setRepositoryId(id);
            if (id != null && id.equals(repoId)) {
                stat.setLocal(true);
            }

            if (references.containsKey(id)) {
                DataRecord refRec = references.get(id);
                stat.setEndTime(refRec.getLastModified());
                stat.setLength(refRec.getLength());

                if (markers.containsKey(id)) {
                    stat.setStartTime(markers.get(id).getLastModified());
                }

                LineNumberReader reader = null;
                try {
                    reader = new LineNumberReader(new InputStreamReader(refRec.getStream()));
                    while (reader.readLine() != null) {
                    }
                    stat.setNumLines(reader.getLineNumber());
                } finally {
                    Closeables.close(reader, true);
                }
            }
            stats.add(stat);
        }
    }
    return stats;
}

From source file:org.grails.web.errors.GrailsWrappedRuntimeException.java

/**
 * @param servletContext The ServletContext instance
 * @param t The exception that was thrown
 *///from  ww w  .j  ava 2s .  c  o m
public GrailsWrappedRuntimeException(ServletContext servletContext, Throwable t) {
    super(t.getMessage(), t);
    this.cause = t;
    Throwable cause = t;

    FastStringPrintWriter pw = FastStringPrintWriter.newInstance();
    cause.printStackTrace(pw);
    stackTrace = pw.toString();

    while (cause.getCause() != cause) {
        if (cause.getCause() == null) {
            break;
        }
        cause = cause.getCause();
    }

    stackTraceLines = stackTrace.split("\\n");

    if (cause instanceof MultipleCompilationErrorsException) {
        MultipleCompilationErrorsException mcee = (MultipleCompilationErrorsException) cause;
        Object message = mcee.getErrorCollector().getErrors().iterator().next();
        if (message instanceof SyntaxErrorMessage) {
            SyntaxErrorMessage sem = (SyntaxErrorMessage) message;
            lineNumber = sem.getCause().getLine();
            className = sem.getCause().getSourceLocator();
            sem.write(pw);
        }
    } else {
        Matcher m1 = PARSE_DETAILS_STEP1.matcher(stackTrace);
        Matcher m2 = PARSE_DETAILS_STEP2.matcher(stackTrace);
        Matcher gsp = PARSE_GSP_DETAILS_STEP1.matcher(stackTrace);
        try {
            if (gsp.find()) {
                className = gsp.group(2);
                lineNumber = Integer.parseInt(gsp.group(3));
                gspFile = URL_PREFIX + "views/" + gsp.group(1) + '/' + className;
            } else {
                if (m1.find()) {
                    do {
                        className = m1.group(1);
                        lineNumber = Integer.parseInt(m1.group(2));
                    } while (m1.find());
                } else {
                    while (m2.find()) {
                        className = m2.group(1);
                        lineNumber = Integer.parseInt(m2.group(2));
                    }
                }
            }
        } catch (NumberFormatException nfex) {
            // ignore
        }
    }

    LineNumberReader reader = null;
    try {
        checkIfSourceCodeAware(t);
        checkIfSourceCodeAware(cause);

        if (getLineNumber() > -1) {
            String fileLocation;
            String url = null;

            if (fileName != null) {
                fileLocation = fileName;
            } else {
                String urlPrefix = "";
                if (gspFile == null) {
                    fileName = className.replace('.', '/') + ".groovy";

                    GrailsApplication application = WebApplicationContextUtils
                            .getRequiredWebApplicationContext(servletContext)
                            .getBean(GrailsApplication.APPLICATION_ID, GrailsApplication.class);
                    // @todo Refactor this to get the urlPrefix from the ArtefactHandler
                    if (application.isArtefactOfType(ControllerArtefactHandler.TYPE, className)) {
                        urlPrefix += "/controllers/";
                    } else if (application.isArtefactOfType(TagLibArtefactHandler.TYPE, className)) {
                        urlPrefix += "/taglib/";
                    } else if (application.isArtefactOfType(ServiceArtefactHandler.TYPE, className)) {
                        urlPrefix += "/services/";
                    }
                    url = URL_PREFIX + urlPrefix + fileName;
                } else {
                    url = gspFile;
                    GrailsApplicationAttributes attrs = null;
                    try {
                        attrs = grailsApplicationAttributesConstructor.newInstance(servletContext);
                    } catch (Exception e) {
                        ReflectionUtils.rethrowRuntimeException(e);
                    }
                    ResourceAwareTemplateEngine engine = attrs.getPagesTemplateEngine();
                    lineNumber = engine.mapStackLineNumber(url, lineNumber);
                }
                fileLocation = "grails-app" + urlPrefix + fileName;
            }

            InputStream in = null;
            if (!GrailsStringUtils.isBlank(url)) {
                in = servletContext.getResourceAsStream(url);
                LOG.debug("Attempting to display code snippet found in url " + url);
            }
            if (in == null) {
                Resource r = null;
                try {
                    r = resolver.getResource(fileLocation);
                    in = r.getInputStream();
                } catch (Throwable e) {
                    r = resolver.getResource("file:" + fileLocation);
                    if (r.exists()) {
                        try {
                            in = r.getInputStream();
                        } catch (IOException e1) {
                            // ignore
                        }
                    }
                }
            }

            if (in != null) {
                reader = new LineNumberReader(new InputStreamReader(in, "UTF-8"));
                String currentLine = reader.readLine();
                StringBuilder buf = new StringBuilder();
                while (currentLine != null) {
                    int currentLineNumber = reader.getLineNumber();
                    if ((lineNumber > 0 && currentLineNumber == lineNumber - 1)
                            || (currentLineNumber == lineNumber)) {
                        buf.append(currentLineNumber).append(": ").append(currentLine).append("\n");
                    } else if (currentLineNumber == lineNumber + 1) {
                        buf.append(currentLineNumber).append(": ").append(currentLine);
                        break;
                    }
                    currentLine = reader.readLine();
                }
                codeSnippet = buf.toString().split("\n");
            }
        }
    } catch (IOException e) {
        LOG.warn("[GrailsWrappedRuntimeException] I/O error reading line diagnostics: " + e.getMessage(), e);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
}

From source file:org.kalypso.model.wspm.tuhh.core.wspwin.prf.PrfWriter.java

private void writeComment() {
    final String comment = m_profil.getComment();
    final DataBlockHeader dbh = PrfHeaders.createHeader(IWspmPointProperties.POINT_PROPERTY_COMMENT); //$NON-NLS-1$
    final TextDataBlock db = new TextDataBlock(dbh);

    final StringReader stringReader = new StringReader(comment);
    final LineNumberReader lineNumberReader = new LineNumberReader(stringReader);

    try {//from w  w w  .j  a va2 s . c  o  m
        for (String line = lineNumberReader.readLine(); line != null; line = lineNumberReader.readLine()) {
            db.addLine("CC " + line); //$NON-NLS-1$
        }
        if (db.getCoordCount() > 0) {
            db.setThirdLine("0  0  0  0  0  0  0  " + Integer.toString(db.getCoordCount()) + " " //$NON-NLS-1$//$NON-NLS-2$
                    + IWspWinConstants.SPEZIALPROFIL_COMMENT);
            m_dbWriter.addDataBlock(db);
        }
    } catch (final IOException e) {
        KalypsoCommonsPlugin.getDefault().getLog().log(new Status(IStatus.WARNING, KalypsoCommonsPlugin.getID(),
                0, Messages.getString("org.kalypso.model.wspm.tuhh.core.wspwin.prf.PrfSink.8"), e)); //$NON-NLS-1$
    }
}

From source file:com.autentia.tnt.bill.migration.BillToBillPaymentMigration.java

/**
 * executes an script received by parameter
 * @param script the script to be launched
 *//*from w w  w  .ja  v a  2s.  co  m*/
private static void executeScript(String script) throws Exception {
    Connection con = null;
    Statement stmt = null;
    LineNumberReader file = null;
    String delimiter = ";";

    try {
        log.debug("LOADING DATABASE SCRIPT" + script);

        // connect to database
        Class.forName(DATABASE_DRIVER);
        con = DriverManager.getConnection(DATABASE_CONNECTION, DATABASE_USER, DATABASE_PASS); //NOSONAR
        con.setAutoCommit(false); // DATABASE_PASS es nula
        stmt = con.createStatement();

        // load file
        InputStream sqlScript = Thread.currentThread().getContextClassLoader().getResourceAsStream(script);
        if (sqlScript == null) {
            throw new FileNotFoundException(script);
        }
        file = new LineNumberReader(new InputStreamReader(new BufferedInputStream(sqlScript), "UTF-8"));

        // Add batched SQL sentences to statement
        StringBuilder sentence = new StringBuilder();
        String line;
        while ((line = file.readLine()) != null) {
            line = line.trim();
            if (!line.startsWith("--")) {
                // Interpret "DELIMITER" sentences
                if (line.trim().toUpperCase(Locale.ENGLISH).startsWith("DELIMITER")) {
                    delimiter = line.trim().substring("DELIMITER".length()).trim();
                } else {
                    // Add line to sentence
                    if (line.endsWith(delimiter)) {
                        // Remove delimiter
                        String lastLine = line.substring(0, line.length() - delimiter.length());

                        // Append line to sentence
                        sentence.append(lastLine);

                        // Execute sentence
                        log.debug(" " + sentence.toString());
                        stmt.addBatch(sentence.toString());

                        // Prepare new sentence
                        sentence = new StringBuilder();
                    } else {
                        // Append line to sentence
                        sentence.append(line);

                        // Append separator for next line
                        sentence.append(" ");
                    }
                }
            }
        }

        // Execute batch
        log.debug("upgradeDatabase - executing batch of commands");
        stmt.executeBatch();

        // Commit transaction
        log.debug("upgradeDatabase - commiting changes to database");
        con.commit();

        // Report end of migration
        log.debug("END LOADING DATABASE SCRIPT");

    } catch (Exception e) {
        log.error("FAILED: WILL BE ROLLED BACK: ", e);
        if (con != null) {
            con.rollback();
        }

    } finally {
        cierraFichero(file);
        liberaConexion(con, stmt, null);
    }
}

From source file:net.sf.keystore_explorer.crypto.csr.pkcs10.Pkcs10Util.java

/**
 * Load a PKCS #10 CSR from the specified stream. The encoding of the CSR
 * may be PEM or DER./*from w w  w .  j a va2 s  .  c  om*/
 *
 * @param is
 *            Stream to load CSR from
 * @return The CSR
 * @throws IOException
 *             An I/O error occurred
 */
public static PKCS10CertificationRequest loadCsr(InputStream is) throws IOException {
    byte[] streamContents = ReadUtil.readFully(is);

    byte[] csrBytes = null;
    LineNumberReader lnr = null;

    // Assume file is PEM until we find out otherwise
    try {
        lnr = new LineNumberReader(new InputStreamReader(new ByteArrayInputStream(streamContents)));

        String line = lnr.readLine();
        StringBuffer sbPem = new StringBuffer();

        if ((line != null) && ((line.equals(BEGIN_CSR_FORM_1) || line.equals(BEGIN_CSR_FORM_2)))) {
            while ((line = lnr.readLine()) != null) {
                if (line.equals(END_CSR_FORM_1) || line.equals(END_CSR_FORM_2)) {
                    csrBytes = Base64.decode(sbPem.toString());
                    break;
                }

                sbPem.append(line);
            }
        }
    } finally {
        IOUtils.closeQuietly(lnr);
    }

    // Not PEM - must be DER encoded
    if (csrBytes == null) {
        csrBytes = streamContents;
    }

    PKCS10CertificationRequest csr = new PKCS10CertificationRequest(csrBytes);

    return csr;
}

From source file:com.sds.acube.ndisc.xnapi.XNApiUtils.java

private static void readVersionFromFile() {
    XNApi_PublishingVersion = "<unknown>";
    XNApi_PublishingDate = "<unknown>";
    InputStreamReader isr = null;
    LineNumberReader lnr = null;/* w w w .ja  v a  2  s  . c o m*/
    try {
        isr = new InputStreamReader(
                XNApiUtils.class.getResourceAsStream("/com/sds/acube/ndisc/xnapi/version.txt"));
        if (isr != null) {
            lnr = new LineNumberReader(isr);
            String line = null;
            do {
                line = lnr.readLine();
                if (line != null) {
                    if (line.startsWith("Publishing-Version=")) {
                        XNApi_PublishingVersion = line.substring("Publishing-Version=".length(), line.length())
                                .trim();
                    } else if (line.startsWith("Publishing-Date=")) {
                        XNApi_PublishingDate = line.substring("Publishing-Date=".length(), line.length())
                                .trim();
                    }
                }
            } while (line != null);
            lnr.close();
        }
    } catch (IOException ioe) {
        XNApi_PublishingVersion = "<unknown>";
        XNApi_PublishingDate = "<unknown>";
    } finally {
        try {
            if (lnr != null) {
                lnr.close();
            }
            if (isr != null) {
                isr.close();
            }
        } catch (IOException ioe) {
        }
    }
}

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
 *//*w  w  w .  j a v a2s .c o m*/
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.fbk.cit.hlt.dirha.Annotator.java

public List<Answer> classify(File fin) throws IOException {
    List<Answer> list = new ArrayList<>();
    LineNumberReader lr = new LineNumberReader(new FileReader(fin));
    String line = null;//from www  .ja  v  a  2 s  .com
    int count = 0;
    String sentence_id = null;

    while ((line = lr.readLine()) != null) {
        try {
            if (line.length() == 0)
                continue;

            try {
                Double.parseDouble(line);
                sentence_id = line;
            } catch (NumberFormatException ex) {
                logger.debug(count + "\t" + line);
                String sid;
                if (sentence_id == null)
                    sid = Integer.toString(count++);
                else {
                    sid = sentence_id;
                    sentence_id = null;
                }
                list.add(classify(line, sid));
            }

        } catch (Exception e) {
            logger.error(e);
        }
    }
    return list;
}