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: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  ww  w .j  a v  a2s  .com
    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:com.netcrest.pado.tools.pado.PadoShell.java

public void runScript(File scriptFile) throws IOException {
    LineNumberReader reader = null;
    try {//www . j  a  va 2s .  c  o m
        reader = new LineNumberReader(new FileReader(scriptFile));
        String line = reader.readLine();
        String command;
        ArrayList<String> propertyCommandList = new ArrayList<String>();
        ArrayList<String> commandList = new ArrayList<String>();
        StringBuffer buffer = new StringBuffer();

        while (line != null) {
            command = line.trim();
            if (command.length() > 0 && command.startsWith("#") == false) {
                if (command.endsWith("\\")) {
                    buffer.append(command.substring(0, command.length() - 1));
                } else {
                    buffer.append(command);
                    StringTokenizer strToken = new StringTokenizer(command);
                    if (strToken.hasMoreTokens()) {
                        String commandName = strToken.nextToken();
                        // if (PROPERTIES_CMD_LIST.contains(commandName)) {
                        // propertyCommandList.add(buffer.toString().trim());
                        // }
                        /*
                         * else if (commandName != null && commandName
                         * .startsWith("historyPerSession")) { try { String
                         * value = command .substring("historyPerSession"
                         * .length() + 1);
                         * setMultiSessionPerUser(Boolean.valueOf(value)); }
                         * catch (Exception ex) { // do nothing } }
                         */
                        // else {
                        commandList.add(buffer.toString().trim());
                        // }
                    }
                    buffer = new StringBuffer();
                }
            }
            line = reader.readLine();
        }

        command = null;
        // Execute properties set commands
        // for (String propertyCommand : PROPERTIES_CMD_LIST) {
        // for (int i = 0; i < propertyCommandList.size(); i++) {
        // command = propertyCommandList.get(i);
        // StringTokenizer strToken = new StringTokenizer(command);
        // if (strToken.hasMoreTokens()) {
        // String commandName = strToken.nextToken();
        // if (commandName.equals(propertyCommand)) {
        // runCommand(command);
        // propertyCommandList.remove(i);
        // i--;
        // }
        // }
        // }
        // }
        // Execute commands
        for (int i = 0; i < commandList.size(); i++) {
            command = commandList.get(i);
            runCommand(command, false);
        }
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}

From source file:net.rptools.maptool.launcher.MapToolLauncher.java

/**
 * Reads from a file named mt.cfg in the same directory to get the following
 * options. Each option is placed on a single line followed by an equal sign
 * ('=') and then the appropriate value. The default values are coded below.
 * /* ww w . j  av  a  2s .  c om*/
 * All memory sizes are in megabytes.
 */
private boolean readCfgFile() {
    boolean rv = false;

    // Set the defaults in the map.  As lines are read from the config file, overwrite the
    // map entries with the new values.  When we're done, we can look at the map entries
    // in an appropriate order and ensure dependencies are handled correctly as well as
    // convert values to the proper data types.
    final Map<String, String> values = new HashMap<String, String>(10);
    values.put("MAXMEM", Integer.toString(maxMemVal)); //$NON-NLS-1$
    values.put("MINMEM", Integer.toString(minMemVal)); //$NON-NLS-1$
    values.put("STACKSIZE", Integer.toString(stackSizeVal)); //$NON-NLS-1$
    values.put("PROMPT", "true"); //$NON-NLS-1$ //$NON-NLS-2$

    final List<String> errors = new ArrayList<String>();
    if (cfgFile.isFile() && cfgFile.length() > 0) {
        rv = true; // Assume that something was found.

        LineNumberReader lnbr = null;
        try {
            lnbr = new LineNumberReader(new BufferedReader(new FileReader(cfgFile)));
            try {
                String line = lnbr.readLine();
                while (line != null) {
                    line = line.trim();
                    if (!line.startsWith("#") && !line.isEmpty()) { //$NON-NLS-1$
                        final String[] arg = line.split("=", 2); // Only apply first delimiter //$NON-NLS-1$
                        if (arg.length == 2) {
                            values.put(arg[0].toUpperCase().trim(), arg[1].trim());
                        } else {
                            errors.add(CopiedFromOtherJars.getText("msg.error.configBadFormat", cfgFile, //$NON-NLS-1$
                                    lnbr.getLineNumber(), line));
                        }
                    }
                    line = lnbr.readLine();
                }
            } catch (final IOException ex) {
                logMsg(Level.SEVERE, "Error reading configuration file: {0}", "msg.error.configIOError", //$NON-NLS-1$
                        cfgFile); //$NON-NLS-2$
            }
        } catch (final FileNotFoundException ex) {
            // This shouldn't happen since we specifically used cfgFile.isFIle(), above, and that can't be true
            // unless the file actually exists.
            logMsg(Level.SEVERE, "Configuration file {0} not found.", "msg.error.configFileNotFound", cfgFile); //$NON-NLS-1$ $NON-NLS-2$
        } finally {
            try {
                lnbr.close();
            } catch (final IOException ex) {
                logMsg(Level.SEVERE, "Error closing configuration file {0}.", "msg.error.configClosing", //$NON-NLS-1$
                        cfgFile); //$NON-NLS-2$
            }
        }
    } else {
        logMsg(Level.INFO, "Configuration file not found; using built-in defaults", "msg.error.configNotFound", //$NON-NLS-1$
                cfgFile); //$NON-NLS-2$
    }
    // Build a list of all XML files in the same directory as the launcher.  This list of
    // filenames will be used to validate the LOGGING parameter from the configuration file.
    File logging = new File(currentDir, "logging"); //$NON-NLS-1$
    if (!logging.isDirectory()) {
        logging = currentDir;
    }
    logConfigs = buildLoggingFileList(logging);

    // Now process the records just read in (or the defaults).  Errors are accumulated into 'errors'.
    parseCfgValues(values, errors);
    if (!errors.isEmpty()) {
        errors.add(0, CopiedFromOtherJars.getText("msg.info.configFeedback")); //$NON-NLS-1$
        CopiedFromOtherJars.showFeedback(ERROR_MESSAGE, errors.toArray());
    }
    // Keep track of the original values.  When we go to save the configuration file, we
    // only write to it if something has changed.
    originalSettings = values;

    // Update UI fields for these three values.
    assignMinMem();
    assignMaxMem();
    assignStackSize();

    updateStrings();
    return rv;
}

From source file:edu.stanford.muse.util.EmailUtils.java

private static Map<String, String> readDBpedia(double p, String typesFile) {
    if (dbpedia != null) {
        if (p == 1)
            return dbpedia;
        else//from  ww w .  ja v  a2  s.co  m
            return new org.apache.commons.collections4.map.CaseInsensitiveMap<>(sample(dbpedia, p));
    }
    if (typesFile == null)
        typesFile = Config.DBPEDIA_INSTANCE_FILE;
    //dbpedia = new LinkedHashMap<>();
    //we want to be able to access elements in the map in a case-sensitive manner, this is a way to do that.
    dbpedia = new org.apache.commons.collections4.map.CaseInsensitiveMap<>();
    int d = 0, numPersons = 0, lines = 0;
    try {
        InputStream is = Config.getResourceAsStream(typesFile);
        if (is == null) {
            log.warn("DBpedia file resource could not be read!!");
            return dbpedia;
        }

        //true argument for BZip2CompressorInputStream so as to load the whole file content into memory
        LineNumberReader lnr = new LineNumberReader(
                new InputStreamReader(new BZip2CompressorInputStream(is, true), "UTF-8"));
        while (true) {
            String line = lnr.readLine();
            if (line == null)
                break;
            if (lines++ % 1000000 == 0)
                log.info("Processed " + lines + " lines of approx. 3.02M in " + typesFile);

            if (line.contains("GivenName"))
                continue;

            String[] words = line.split("\\s+");
            String r = words[0];

            /**
             * The types file contains lines like this:
             * National_Bureau_of_Asian_Research Organisation|Agent
             * National_Bureau_of_Asian_Research__1 PersonFunction
             * National_Bureau_of_Asian_Research__2 PersonFunction
             * Which leads to classifying "National_Bureau_of_Asian_Research" as PersonFunction and not Org.
             */
            if (r.contains("__")) {
                d++;
                continue;
            }
            //if it still contains this, is a bad title.
            if (r.equals("") || r.contains("__")) {
                d++;
                continue;
            }
            String type = words[1];
            //Royalty names, though tagged person are very weird, contains roman characters and suffixes like of_Poland e.t.c.
            if (type.equals("PersonFunction") || type.equals("Royalty|Person|Agent"))
                continue;
            //in places there are things like: Shaikh_Ibrahim,_Iraq
            if (type.endsWith("Settlement|PopulatedPlace|Place"))
                r = r.replaceAll(",_.*", "");

            //its very dangerous to remove things inside brackets as that may lead to terms like
            //University_(Metrorail_Station) MetroStation|Place e.t.c.
            //so keep them, or just skip this entry all together
            //We are not considering single word tokens any way, so its OK to remove things inside the brackets
            //removing stuff in brackets may cause trouble when blind matching entities
            //r = r.replaceAll("_\\(.*?\\)", "");
            String title = r.replaceAll("_", " ");

            String badSuffix = "|Agent";
            if (type.endsWith(badSuffix) && type.length() > badSuffix.length())
                type = type.substring(0, type.length() - badSuffix.length());
            if (type.endsWith("|Person"))
                numPersons++;
            type = type.intern(); // type strings are repeated very often, so intern

            if (type.equals("Road|RouteOfTransportation|Infrastructure|ArchitecturalStructure|Place")) {
                //System.err.print("Cleaned: "+title);
                title = cleanDBPediaRoad(title);
                //System.err.println(" to "+title);
            }
            dbpedia.put(title, type);
        }
        lnr.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    log.info("Read " + dbpedia.size() + " names from DBpedia, " + numPersons + " people name. dropped: " + d);

    return new org.apache.commons.collections4.map.CaseInsensitiveMap<>(sample(dbpedia, p));
}

From source file:ua.utility.kfsdbupgrade.App.java

/**
 * Create the public synonyms specified in {@link #upgradeRoot}
 * <code>/post-upgrade/sql/kfs-public-synonyms.sql</code> that do not
 * already exist.//ww w  .  j a va2  s.com
 * 
 * @param conn
 *            {@link Connection} to a database
 * @param stmt
 *            {@link Statement} to use to execute SQL statements
 */
private void createPublicSynonyms(Connection conn, Statement stmt) {
    LineNumberReader lnr = null;

    logHeader2("creating KFS public synonyms that existed prior to upgrade where required ");

    File kfsPublicSynonymsSqlFile = new File(
            postUpgradeDirectory + File.separator + KFS_PUBLIC_SYNONYMS_SQL_PATH);
    try {
        lnr = new LineNumberReader(new FileReader(kfsPublicSynonymsSqlFile));

        String line = null;

        while ((line = lnr.readLine()) != null) {
            String synonymName = getSynonymName(line);

            if (!synonymExists(conn, stmt, synonymName)) {
                try {
                    // if there is a trailing semicolon, remove it
                    int pos = line.lastIndexOf(';');
                    if (pos == line.length() - 1) {
                        line = line.substring(0, line.length() - 1);
                    }
                    stmt.execute(line);
                } catch (SQLException ex) {
                    LOGGER.error("failed to create public synonym: " + line, ex);
                }
            }
        }
    } catch (Exception ex) {
        LOGGER.error(ex);
    } finally {
        try {
            if (lnr != null) {
                lnr.close();
            }
        } catch (Exception ex) {
            LOGGER.error(ex);
        }
        ;
    }
    postUpgradeFilesProcessed.add(kfsPublicSynonymsSqlFile);
}

From source file:net.rptools.maptool.launcher.MapToolLauncher.java

/**
 * Read the given XML file and look for specially formatted lines so that a
 * description of the files purpose and text to display in a tooltip are
 * retrieved. The current process involves looking for XML comments that
 * match the regex <code><b>^&lt;!--\s+(\w+):\s*(.*)\s+--&gt;$</b></code>
 * and pull out the two fields; the first field is the key and the second is
 * the value for storing the information in the returned object.
 * /*from   ww  w  .j  a  v a2s.c o  m*/
 * @param xml
 *            <code>File</code> object representing the file to read
 * @return a {@link LoggingConfig} object which stores information about the
 *         XML file
 */
private LoggingConfig readDescFromXmlFile(File xml) {
    final LoggingConfig config = new LoggingConfig(xml, new JCheckBox());
    LineNumberReader lnbr = null;
    final String REGEX = "^<!--\\s+(\\w+):\\s*(.*)\\s+-->$"; //$NON-NLS-1$
    final Pattern pattern = Pattern.compile(REGEX);
    try {
        int count = 0;
        lnbr = new LineNumberReader(new BufferedReader(new FileReader(xml)));
        String line = lnbr.readLine();
        config.addProperty("desc", xml.getName()); //$NON-NLS-1$
        config.addProperty("ttip", xml.getName()); //$NON-NLS-1$
        while (count < 2 && line != null) {
            line = line.trim();
            final Matcher m = pattern.matcher(line);
            if (m.matches()) {
                final String key = m.group(1);
                final String value = m.group(2);
                config.addProperty(key, value);
                count++;
            }
            line = lnbr.readLine();
        }
        if (count < 2) {
            JOptionPane.showMessageDialog(null,
                    CopiedFromOtherJars.getText("msg.error.loggingBadFormat", xml.getName()), //$NON-NLS-1$
                    CopiedFromOtherJars.getText("msg.title.loggingBadFormat", xml), //$NON-NLS-1$
                    ERROR_MESSAGE);
        }
    } catch (final FileNotFoundException e) {
    } catch (final IOException e) {
    } finally {
        CopiedFromOtherJars.closeQuietly(lnbr);
    }
    return config;
}

From source file:org.agnitas.util.AgnUtils.java

public static int getLineCountOfFile(File file) throws IOException {
    LineNumberReader lineNumberReader = null;
    try {/*from  w w w.j  a v a2s  .  co m*/
        lineNumberReader = new LineNumberReader(new InputStreamReader(new FileInputStream(file)));
        while (lineNumberReader.readLine() != null) {
        }

        return lineNumberReader.getLineNumber();
    } finally {
        IOUtils.closeQuietly(lineNumberReader);
    }
}

From source file:com.repeatability.pdf.PDFTextStripper.java

/**
 * This method parses the bidi file provided as inputstream.
 * /*  www .j a v  a  2  s . c  o  m*/
 * @param inputStream - The bidi file as inputstream
 * @throws IOException if any line could not be read by the LineNumberReader
 */
private static void parseBidiFile(InputStream inputStream) throws IOException {
    LineNumberReader rd = new LineNumberReader(new InputStreamReader(inputStream));

    do {
        String s = rd.readLine();
        if (s == null) {
            break;
        }

        int comment = s.indexOf('#'); // ignore comments
        if (comment != -1) {
            s = s.substring(0, comment);
        }

        if (s.length() < 2) {
            continue;
        }

        StringTokenizer st = new StringTokenizer(s, ";");
        int nFields = st.countTokens();
        Character[] fields = new Character[nFields];
        for (int i = 0; i < nFields; i++) {
            fields[i] = (char) Integer.parseInt(st.nextToken().trim(), 16);
        }

        if (fields.length == 2) {
            // initialize the MIRRORING_CHAR_MAP
            MIRRORING_CHAR_MAP.put(fields[0], fields[1]);
        }

    } while (true);
}

From source file:fitnesserefactor.FitnesseRefactor.java

public int CountLines(File filename) throws FileNotFoundException, IOException {
    LineNumberReader reader = new LineNumberReader(new FileReader(filename));
    int cnt = 0;//from w ww  .  ja  v  a  2s.co m
    String lineRead = "";
    while ((lineRead = reader.readLine()) != null) {
    }
    cnt = reader.getLineNumber();
    reader.close();
    return cnt;
}

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

/**
 * Test verifies that the server shouldn't be affected but runtime errors on stop()
 *///from w w w  .java 2 s  . c om
@Test
public void testFaultyMetricsProviderOnStop() throws Exception {
    ClientBase.setupTestEnv();
    BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.reset();

    // 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 quorumCfgSectionServer = "server.1=127.0.0.1:" + PortAssignment.unique() + ":"
                + PortAssignment.unique() + ";" + CLIENT_PORT_QP1 + "\n" + "server.2=127.0.0.1:"
                + PortAssignment.unique() + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP2 + "\n";

        // server 1 boots with a MetricsProvider
        String quorumCfgSectionServer1 = quorumCfgSectionServer + "metricsProvider.className="
                + BaseTestMetricsProvider.MetricsProviderWithErrorInStop.class.getName() + "\n";

        MainThread q1 = new MainThread(1, CLIENT_PORT_QP1, quorumCfgSectionServer1);
        MainThread q2 = new MainThread(2, CLIENT_PORT_QP2, quorumCfgSectionServer);
        q1.start();
        q2.start();

        boolean isup1 = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1, 30000);
        boolean isup2 = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP2, 30000);
        Assert.assertTrue("Server 1 never came up", isup1);
        Assert.assertTrue("Server 2 never came up", isup2);

        q1.shutdown();
        q2.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));
    } finally {
        qlogger.removeAppender(appender);
    }

    Assert.assertTrue("metrics provider lifecycle error",
            BaseTestMetricsProvider.MetricsProviderWithErrorInStop.stopCalled.get());

    LineNumberReader r = new LineNumberReader(new StringReader(os.toString()));
    String line;
    boolean found = false;
    Pattern p = Pattern.compile(".*Error while stopping metrics.*");
    while ((line = r.readLine()) != null) {
        found = p.matcher(line).matches();
        if (found) {
            break;
        }
    }
    Assert.assertTrue("complains about metrics provider", found);
}