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.apache.zookeeper.server.quorum.QuorumPeerMainTest.java

/**
 * Verify boot fails with a bad MetricsProvider
 *///from   w  w w  .  j av a  2s .com
@Test
public void testInvalidMetricsProvider() 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();

        String quorumCfgSection = "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_QP1 + "\n"
                + "metricsProvider.className=BadClass\n";

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

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

        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(".*BadClass.*");
    while ((line = r.readLine()) != null) {
        found = p.matcher(line).matches();
        if (found) {
            break;
        }
    }
    Assert.assertTrue("complains about metrics provider", found);
}

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

/**
 * Verify boot fails with a MetricsProvider with fails to start
 *//* w  w  w .  ja v a2  s.c om*/
@Test
public void testFaultyMetricsProviderOnStart() 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();

        String quorumCfgSection = "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_QP1 + "\n"
                + "metricsProvider.className="
                + BaseTestMetricsProvider.MetricsProviderWithErrorInStart.class.getName() + "\n";

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

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

        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(".*MetricsProviderLifeCycleException.*");
    while ((line = r.readLine()) != null) {
        found = p.matcher(line).matches();
        if (found) {
            break;
        }
    }
    Assert.assertTrue("complains about metrics provider MetricsProviderLifeCycleException", found);
}

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

/**
 * Verify boot fails with a MetricsProvider with fails to start
 *///from  w  w  w.j  a  v a 2  s.c o  m
@Test
public void testFaultyMetricsProviderOnConfigure() 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();

        String quorumCfgSection = "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_QP1 + "\n"
                + "metricsProvider.className="
                + BaseTestMetricsProvider.MetricsProviderWithErrorInConfigure.class.getName() + "\n";

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

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

        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(".*MetricsProviderLifeCycleException.*");
    while ((line = r.readLine()) != null) {
        found = p.matcher(line).matches();
        if (found) {
            break;
        }
    }
    Assert.assertTrue("complains about metrics provider MetricsProviderLifeCycleException", found);
}

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

/**
 * yzhang Comment method "updateGraphicalNodeBreaking".
 * /*from  w  ww  . j  a va2 s.c  om*/
 * @param breakpoint
 */
private void updateGraphicalNodeBreaking(IJavaBreakpoint breakpoint, boolean removed) {
    try {
        Integer breakLineNumber = (Integer) breakpoint.getMarker().getAttribute(IMarker.LINE_NUMBER);
        if (breakLineNumber == null || breakLineNumber == -1) {
            return;
        }
        IFile codeFile = this.getCodeProject().getFile(this.getSrcCodePath());
        if (!codeFile.exists()) {
            JDIDebugModel.removeJavaBreakpointListener(this);
            return;
        }
        LineNumberReader lineReader = new LineNumberReader(new InputStreamReader(codeFile.getContents()));
        String content = null;
        while (lineReader.getLineNumber() < breakLineNumber - 3) {
            content = lineReader.readLine();
            if (content == null) {
                return;
            }
        }
        int startIndex = content.indexOf("[") + 1; //$NON-NLS-1$
        int endIndex = content.indexOf(" main ] start"); //$NON-NLS-1$
        if (startIndex != -1 && endIndex != -1) {
            String nodeUniqueName = content.substring(startIndex, endIndex);
            List<? extends INode> breakpointNodes = CorePlugin.getContext().getBreakpointNodes(process);
            List<? extends INode> graphicalNodes = process.getGraphicalNodes();
            if (graphicalNodes == null) {
                return;
            }
            for (INode node : graphicalNodes) {
                if (node.getUniqueName().equals(nodeUniqueName) && removed && breakpointNodes.contains(node)) {
                    CorePlugin.getContext().removeBreakpoint(process, node);
                    if (node instanceof Node) {
                        final INode currentNode = node;
                        Display.getDefault().syncExec(new Runnable() {

                            @Override
                            public void run() {
                                ((Node) currentNode).removeStatus(Process.BREAKPOINT_STATUS);

                            }

                        });
                    }
                } else if (node.getUniqueName().equals(nodeUniqueName) && !removed
                        && !breakpointNodes.contains(node)) {
                    CorePlugin.getContext().addBreakpoint(process, node);
                    if (node instanceof Node) {
                        final INode currentNode = node;
                        Display.getDefault().syncExec(new Runnable() {

                            @Override
                            public void run() {
                                ((Node) currentNode).addStatus(Process.BREAKPOINT_STATUS);

                            }

                        });
                    }
                }
            }

        }

    } catch (CoreException e) {
        RuntimeExceptionHandler.process(e);
    } catch (IOException e) {
        RuntimeExceptionHandler.process(e);
    }
}

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

/**
 * Execute the sql file {@link #upgradeRoot}
 * <code>/post-upgrade/sql/misc.sql</code> against the database
 * /*from w  w w . ja v a  2 s  .  c  om*/
 * @param conn
 *            {@link Connection} to the database
 * @param stmt
 *            {@link Statement} to use to execute SQL
 */
private void runMiscSql(Connection conn, Statement stmt) {
    LineNumberReader lnr = null;

    logHeader2("Executing miscellaneous post-upgrade sql");
    File miscSqlFile = new File(postUpgradeDirectory + File.separator + MISC_SQL_PATH);
    try {
        lnr = new LineNumberReader(new FileReader(miscSqlFile));

        String sql = null;

        while ((sql = lnr.readLine()) != null) {
            if (StringUtils.isNotBlank(sql)) {
                try {
                    if (sql.trim().endsWith(";")) {
                        int pos = sql.lastIndexOf(";");
                        sql = sql.substring(0, pos);
                    }

                    if (isDDL(sql)) {
                        stmt.execute(sql);
                    } else {
                        stmt.executeUpdate(sql);
                    }
                    LOGGER.info(sql);
                } catch (SQLException ex) {
                    LOGGER.error("sql execution failed: " + sql, ex);
                }
            }
        }
    } catch (Exception ex) {
        LOGGER.error(ex);
    } finally {
        try {
            if (lnr != null) {
                lnr.close();
            }
        } catch (Exception ex) {
            LOGGER.error(ex);
        }
        ;
    }
    postUpgradeFilesProcessed.add(miscSqlFile);
}

From source file:org.yccheok.jstock.gui.Utils.java

/**
 * Returns number of lines in a file./*w ww. ja  va2s.c  om*/
 * 
 * @param file The file
 * @return number of lines in a file
 */
public static int numOfLines(File file, boolean skipMetadata) {
    int line = 0;
    int metaLineNumber = 0;

    LineNumberReader lnr = null;
    try {
        lnr = new LineNumberReader(new FileReader(file));

        if (skipMetadata) {
            String nextLine = lnr.readLine();
            // Metadata handling.
            while (nextLine != null) {
                String[] tokens = nextLine.split("=", 2);
                if (tokens.length == 2) {
                    String key = tokens[0].trim();
                    if (key.length() > 0) {
                        // Is OK for value to be empty.
                        metaLineNumber++;
                        nextLine = lnr.readLine();
                    } else {
                        break;
                    }
                } else {
                    break;
                }
            }
        }

        lnr.skip(Long.MAX_VALUE);
        line = lnr.getLineNumber();
    } catch (IOException ex) {
        log.error(null, ex);
    } finally {
        org.yccheok.jstock.file.Utils.close(lnr);
    }

    return line - metaLineNumber;
}

From source file:org.opencms.setup.CmsSetupBean.java

/**
 * Saves the properties to a file.<p>
 * /*  w ww.  j  ava2 s.  c o m*/
 * @param properties the properties to be saved
 * @param source the source file to get the keys from
 * @param target the target file to save the properties to
 * @param forceWrite the keys of the properties which should always be written, even if they don't exist in the configuration file 
 */
private void save(CmsParameterConfiguration properties, String source, String target, Set<String> forceWrite) {

    try {
        Set<String> alreadyWritten = new HashSet<String>();

        LineNumberReader lnr = new LineNumberReader(new FileReader(new File(m_configRfsPath + source)));

        FileWriter fw = new FileWriter(new File(m_configRfsPath + target));

        while (true) {
            String line = lnr.readLine();
            if (line == null) {
                break;
            }
            line = line.trim();

            if ("".equals(line)) {
                // output empty line
                fw.write("\n");
            } else if (line.startsWith("#")) {
                // output comment
                fw.write(line);
                fw.write("\n");
            } else {

                int index = line.indexOf('=');
                int index1 = line.indexOf("\\=");
                if ((line.indexOf('=') > -1) && (index1 != (index - 1))) {

                    String key = line.substring(0, line.indexOf('=')).trim();
                    if (alreadyWritten.contains(key)) {
                        continue;
                    }
                    // write key
                    fw.write((key + "="));
                    try {
                        Object obj = properties.getObject(key);
                        if (obj != null) {
                            String valueToWrite = getPropertyValueToWrite(obj);
                            fw.write(valueToWrite);
                        }

                    } catch (NullPointerException e) {
                        // no value found - do nothing 
                    }
                    // add trailing line feed
                    fw.write("\n");

                    // remember that this properties is already written (multi values)
                    alreadyWritten.add(key);
                }
            }
        }
        if (forceWrite != null) {
            for (String forced : forceWrite) {
                if (!alreadyWritten.contains(forced) && properties.containsKey(forced)) {
                    fw.write("\n\n");
                    fw.write(forced + "=");
                    try {
                        Object obj = properties.getObject(forced);

                        if (obj != null) {
                            String valueToWrite = getPropertyValueToWrite(obj);
                            fw.write(valueToWrite);
                        }
                    } catch (NullPointerException e) {
                        // no value found - do nothing
                    }
                    fw.write("\n");

                }
            }
        }

        lnr.close();
        fw.close();
    } catch (Exception e) {
        m_errors.add("Could not save properties to " + target + " \n");
        m_errors.add(e.toString() + "\n");
    }
}

From source file:lineage2.gameserver.Config.java

/**
 * Method abuseLoad./*  w  w w.ja v a2 s. c  o  m*/
 */
public static void abuseLoad() {
    List<Pattern> tmp = new ArrayList<Pattern>();
    LineNumberReader lnr = null;
    try {
        String line;
        lnr = new LineNumberReader(new InputStreamReader(new FileInputStream(ANUSEWORDS_CONFIG_FILE), "UTF-8"));
        while ((line = lnr.readLine()) != null) {
            StringTokenizer st = new StringTokenizer(line, "\n\r");
            if (st.hasMoreTokens()) {
                tmp.add(Pattern.compile(".*" + st.nextToken() + ".*",
                        Pattern.DOTALL | Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE));
            }
        }
        ABUSEWORD_LIST = tmp.toArray(new Pattern[tmp.size()]);
        tmp.clear();
        _log.info("Abuse: Loaded " + ABUSEWORD_LIST.length + " abuse words.");
    } catch (IOException e1) {
        _log.warn("Error reading abuse: " + e1);
    } finally {
        try {
            if (lnr != null) {
                lnr.close();
            }
        } catch (Exception e2) {
        }
    }
}