Example usage for java.io LineNumberReader readLine

List of usage examples for java.io LineNumberReader readLine

Introduction

In this page you can find the example usage for java.io LineNumberReader readLine.

Prototype

public String readLine() throws IOException 

Source Link

Document

Read a line of text.

Usage

From source file:org.apache.lucene.search.SearchUtil.java

public void parse(File file) throws IOException, InterruptedException {
    FileInputStream fis = null;/* w  ww.  j a  v  a2 s .c  om*/
    try {
        fis = new FileInputStream(file);
        HTMLParser parser = new HTMLParser(fis);

        //         this.title=Entities.encode(parser.getTitle());
        StringBuilder sb = new StringBuilder();
        LineNumberReader reader = new LineNumberReader(parser.getReader());
        for (String l = reader.readLine(); l != null; l = reader.readLine()) {
            //            System.out.println(l);
            sb.append(l + " ");
        }
        this.contents = sb.toString();
        //         System.out.println("Parsed Contents: "+contents);
    } finally {
        if (fis != null)
            fis.close();
    }
}

From source file:org.apache.axis.security.simple.SimpleSecurityProvider.java

private synchronized void initialize(MessageContext msgContext) {
    if (initialized)
        return;/* ww w .j  a  v a 2 s.c  o m*/

    String configPath = msgContext.getStrProp(Constants.MC_CONFIGPATH);
    if (configPath == null) {
        configPath = "";
    } else {
        configPath += File.separator;
    }
    File userFile = new File(configPath + "users.lst");
    if (userFile.exists()) {
        users = new HashMap();

        try {

            FileReader fr = new FileReader(userFile);
            LineNumberReader lnr = new LineNumberReader(fr);
            String line = null;

            // parse lines into user and passwd tokens and add result to hash table
            while ((line = lnr.readLine()) != null) {
                StringTokenizer st = new StringTokenizer(line);
                if (st.hasMoreTokens()) {
                    String userID = st.nextToken();
                    String passwd = (st.hasMoreTokens()) ? st.nextToken() : "";

                    if (log.isDebugEnabled()) {
                        log.debug(Messages.getMessage("fromFile00", userID, passwd));
                    }

                    users.put(userID, passwd);
                }
            }

            lnr.close();

        } catch (Exception e) {
            log.error(Messages.getMessage("exception00"), e);
            return;
        }
    }
    initialized = true;
}

From source file:com.googlecode.jweb1t.IndexCreator.java

private void read(final File aFile) throws IOException {
    LineNumberReader reader = null;
    try {/*from  w w  w . j  a va  2s . c  o m*/
        reader = new LineNumberReader(new FileReader(aFile));
        String line = null;
        String ch = null;

        // first line
        if ((line = reader.readLine()) != null) {
            ch = line.substring(0, 2).trim();
        }

        String old = ch;

        // second line
        while ((line = reader.readLine()) != null) {
            ch = line.substring(0, 2).trim();

            if (!ch.equals(old)) {
                put(old, aFile);
                old = ch;
            }
        }

        put(old, aFile);
    } finally {
        IOUtils.closeQuietly(reader);
    }
}

From source file:com.gettextresourcebundle.GettextResourceBundle.java

/**
 * initialize the ResourceBundle from a PO file
 * /*  w ww  .  j a va2s. c  o  m*/
 * if
 * 
 * @param reader the reader to read the contents of the PO file from
 */
private void init(LineNumberReader reader) {
    if (reader != null) {
        String line = null;
        String key = null;
        String value = null;
        try {
            while ((line = reader.readLine()) != null) {
                if (line.startsWith("#")) {
                    LOG.trace(reader.getLineNumber() + ": Parsing PO file, comment skipped [" + line + "]");
                } else if (line.trim().length() == 0) {
                    LOG.trace(reader.getLineNumber() + ": Parsing PO file, whitespace line skipped");
                } else {
                    Matcher matcher = LINE_PATTERN.matcher(line);
                    if (matcher.matches()) {
                        String type = matcher.group(1);
                        String str = matcher.group(2);
                        if ("msgid".equals(type)) {
                            if (key != null && value != null) {
                                LOG.debug(
                                        "Parsing PO file, key,value pair found [" + key + " => " + value + "]");
                                resources.put(StringEscapeUtils.unescapeJava(key),
                                        StringEscapeUtils.unescapeJava(value));
                                key = null;
                                value = null;
                            }
                            key = str;
                            LOG.trace(reader.getLineNumber() + ": Parsing PO file, msgid found [" + key + "]");
                        } else if ("msgstr".equals(type)) {
                            value = str;
                            LOG.trace(
                                    reader.getLineNumber() + ": Parsing PO file, msgstr found [" + value + "]");
                        } else if (type == null || type.length() == 0) {
                            if (value == null) {
                                LOG.trace(reader.getLineNumber()
                                        + ": Parsing PO file, addition to msgid found [" + str + "]");
                                key += str;
                            } else {
                                LOG.trace(reader.getLineNumber()
                                        + ": Parsing PO file, addition to msgstr found [" + str + "]");
                                value += str;
                            }

                        }
                    } else {
                        LOG.error(reader.getLineNumber() + ": Parsing PO file, invalid syntax [" + line + "]");
                    }
                }

            }

            if (key != null && value != null) {
                LOG.debug("Parsing PO file, key,value pair found [" + key + " => " + value + "]");
                resources.put(StringEscapeUtils.unescapeJava(key), StringEscapeUtils.unescapeJava(value));
                key = null;
                value = null;
            }
        } catch (IOException e) {
            LOG.error("GettextResourceBundle could not be initialized", e);
        }

    } else {
        LOG.warn("GettextResourceBundle could not be initialized, input was null");
    }
    LOG.info("GettextResourceBundle initialization complete, " + resources.size() + " resources loaded");
}

From source file:com.acmeair.web.LoaderREST.java

public void loadFlights(int segments) throws Exception {
    System.out.println("Loading flight data...");
    InputStream csvInputStream = getClass().getResourceAsStream("/mileage.csv");
    LineNumberReader lnr = new LineNumberReader(new InputStreamReader(csvInputStream));
    String line1 = lnr.readLine();
    StringTokenizer st = new StringTokenizer(line1, ",");
    ArrayList<AirportCodeMapping> airports = new ArrayList<AirportCodeMapping>();

    // read the first line which are airport names
    while (st.hasMoreTokens()) {
        AirportCodeMapping acm = new AirportCodeMapping();
        acm.setAirportName(st.nextToken());
        airports.add(acm);//from   ww w . j a va  2s. c  o  m
    }
    // read the second line which contains matching airport codes for the
    // first line
    String line2 = lnr.readLine();
    st = new StringTokenizer(line2, ",");
    int ii = 0;
    while (st.hasMoreTokens()) {
        String airportCode = st.nextToken();
        airports.get(ii).setAirportCode(airportCode);
        ii++;
    }
    // read the other lines which are of format:
    // airport name, aiport code, distance from this airport to whatever
    // airport is in the column from lines one and two
    String line;
    int flightNumber = 0;
    while (true) {
        line = lnr.readLine();
        if (line == null || line.trim().equals("")) {
            break;
        }
        st = new StringTokenizer(line, ",");
        String airportName = st.nextToken();
        String airportCode = st.nextToken();
        if (!alreadyInCollection(airportCode, airports)) {
            AirportCodeMapping acm = new AirportCodeMapping();
            acm.setAirportName(airportName);
            acm.setAirportCode(airportCode);
            airports.add(acm);
        }
        int indexIntoTopLine = 0;
        while (st.hasMoreTokens()) {
            String milesString = st.nextToken();
            if (milesString.equals("NA")) {
                indexIntoTopLine++;
                continue;
            }
            int miles = Integer.parseInt(milesString);
            String toAirport = airports.get(indexIntoTopLine).getAirportCode();
            if (!flightService.getFlightByAirports(airportCode, toAirport).isEmpty()) {
                // already there
                continue;
            }
            String flightId = "AA" + flightNumber;
            FlightSegment flightSeg = new FlightSegment(flightId, airportCode, toAirport, miles);
            flightService.storeFlightSegment(flightSeg);
            Date now = new Date();
            for (int daysFromNow = 0; daysFromNow < segments; daysFromNow++) {
                Calendar c = Calendar.getInstance();
                c.setTime(now);
                c.set(Calendar.HOUR_OF_DAY, 0);
                c.set(Calendar.MINUTE, 0);
                c.set(Calendar.SECOND, 0);
                c.set(Calendar.MILLISECOND, 0);
                c.add(Calendar.DATE, daysFromNow);
                Date departureTime = c.getTime();
                Date arrivalTime = getArrivalTime(departureTime, miles);
                flightService.createNewFlight(flightId, departureTime, arrivalTime, new BigDecimal(500),
                        new BigDecimal(200), 10, 200, "B747");

            }
            flightNumber++;
            indexIntoTopLine++;
        }
    }

    for (int jj = 0; jj < airports.size(); jj++) {
        flightService.storeAirportMapping(airports.get(jj));
    }
    lnr.close();
    System.out.println("Done loading flight data.");
}

From source file:net.sourceforge.pmd.lang.java.rule.strings.AvoidDuplicateLiteralsRule.java

@Override
public Object visit(ASTCompilationUnit node, Object data) {
    literals.clear();//from w  w w. j  a  v  a  2s.  co m

    if (getProperty(EXCEPTION_LIST_DESCRIPTOR) != null) {
        ExceptionParser p = new ExceptionParser(getProperty(SEPARATOR_DESCRIPTOR));
        exceptions = p.parse(getProperty(EXCEPTION_LIST_DESCRIPTOR));
    } else if (getProperty(EXCEPTION_FILE_DESCRIPTOR) != null) {
        exceptions = new HashSet<String>();
        LineNumberReader reader = null;
        try {
            reader = getLineReader();
            String line;
            while ((line = reader.readLine()) != null) {
                exceptions.add(line);
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            IOUtils.closeQuietly(reader);
        }
    }

    minLength = 2 + getProperty(MINIMUM_LENGTH_DESCRIPTOR);

    super.visit(node, data);

    processResults(data);

    return data;
}

From source file:org.kalypso.model.wspm.tuhh.schema.simulation.BuildingPolygonReader.java

public void read(final File buildingFile) throws IOException {
    LineNumberReader reader = null;
    try {/*  ww  w. ja  v a 2 s  .c o  m*/
        reader = new LineNumberReader(new FileReader(buildingFile));

        /* Ingore first line */
        if (reader.ready())
            reader.readLine();

        while (reader.ready()) {
            final String line = reader.readLine();
            if (line == null)
                break;

            try {
                readBuildingLine(line.trim(), buildingFile);
            } catch (final NumberFormatException nfe) {
                /* A good line but bad content. Give user a hint that something might be wrong. */
                m_log.log(false,
                        Messages.getString(
                                "org.kalypso.model.wspm.tuhh.schema.simulation.PolynomeProcessor.25"), //$NON-NLS-1$
                        buildingFile.getName(), reader.getLineNumber(), nfe.getLocalizedMessage());
            } catch (final Throwable e) {
                // should never happen
                m_log.log(e,
                        Messages.getString(
                                "org.kalypso.model.wspm.tuhh.schema.simulation.PolynomeProcessor.25"), //$NON-NLS-1$
                        buildingFile.getName(), reader.getLineNumber(), e.getLocalizedMessage());
            }

        }
        reader.close();
    } finally {
        IOUtils.closeQuietly(reader);
    }
}

From source file:com.feilong.tools.ant.plugin.jpa.ParseJPATest.java

/**
 * Aa.// ww w  . jav a 2  s. c o m
 *
 * @param longTextFile
 *            the long text file
 * @return the list< column>
 * @throws FileNotFoundException
 *             the file not found exception
 * @throws IOException
 *             the IO exception
 */
private List<Column> aa(String longTextFile) throws FileNotFoundException, IOException {
    Reader reader = new FileReader(longTextFile);
    LineNumberReader lineNumberReader = new LineNumberReader(reader);

    String line = null;

    List<Column> columnlist = new ArrayList<Column>();

    while ((line = lineNumberReader.readLine()) != null) {
        int lineNumber = lineNumberReader.getLineNumber();
        //         if (log.isDebugEnabled()){
        //            log.debug("the param lineNumber:{}", lineNumber);
        //         }

        String[] split = line.split("\t");

        Column column = new Column();

        column.setTableName(split[0]);
        column.setColumnName(split[1]);
        //column.setLength(columnName);
        column.setType(split[2]);
        columnlist.add(column);
    }

    lineNumberReader.close();

    return columnlist;

}

From source file:org.gsoft.admin.ScriptRunner.java

/**
 * Runs an SQL script (read in using the Reader parameter) using the
 * connection passed in//  www.  j  a  va2 s  .  co  m
 * 
 * @param conn
 *            - the connection to use for the script
 * @param reader
 *            - the source of the script
 * @throws SQLException
 *             if any SQL errors occur
 * @throws IOException
 *             if there is an error reading from the Reader
 */
private void runScript(Connection conn, Reader reader) throws IOException, SQLException {
    StringBuffer command = null;
    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("--")) {
                println(trimmedLine);
            } else if (trimmedLine.length() < 1 || trimmedLine.startsWith("//")) {
                // Do nothing
            } else if (trimmedLine.length() < 1 || trimmedLine.startsWith("--")) {
                // Do nothing
            } else if (!fullLineDelimiter && trimmedLine.endsWith(getDelimiter())
                    || fullLineDelimiter && trimmedLine.equals(getDelimiter())) {
                command.append(line.substring(0, line.lastIndexOf(getDelimiter())));
                command.append(" ");
                Statement statement = conn.createStatement();

                println(command);

                boolean hasResults = false;
                if (stopOnError) {
                    hasResults = statement.execute(command.toString());
                } else {
                    try {
                        statement.execute(command.toString());
                    } catch (SQLException e) {
                        e.fillInStackTrace();
                        printlnError("Error executing: " + command);
                        printlnError(e);
                    }
                }

                if (autoCommit && !conn.getAutoCommit()) {
                    conn.commit();
                }

                ResultSet rs = statement.getResultSet();
                if (hasResults && rs != null) {
                    ResultSetMetaData md = rs.getMetaData();
                    int cols = md.getColumnCount();
                    for (int i = 0; i < cols; i++) {
                        String name = md.getColumnLabel(i);
                        print(name + "\t");
                    }
                    println("");
                    while (rs.next()) {
                        for (int i = 0; i < cols; i++) {
                            String value = rs.getString(i);
                            print(value + "\t");
                        }
                        println("");
                    }
                }

                command = null;
                try {
                    statement.close();
                } catch (Exception e) {
                    // Ignore to workaround a bug in Jakarta DBCP
                }
                Thread.yield();
            } else {
                command.append(line);
                command.append(" ");
            }
        }
        if (!autoCommit) {
            conn.commit();
        }
    } catch (SQLException e) {
        e.fillInStackTrace();
        printlnError("Error executing: " + command);
        printlnError(e);
        throw e;
    } catch (IOException e) {
        e.fillInStackTrace();
        printlnError("Error executing: " + command);
        printlnError(e);
        throw e;
    } finally {
        conn.rollback();
        flush();
    }
}

From source file:ru.jkff.antro.ReportReader.java

public Report readReport(String filename) throws IOException {
    // function getProfileData() {
    // return (// ww w  . ja  v  a  2s.  c  o  m
    //   JSONObject (read until {} [] braces are balanced)
    // )
    // }
    // function getTrace() {
    // return (
    //   JSONObject (read until {} [] braces are balanced)
    // )
    // }
    try {
        LineNumberReader r = new LineNumberReader(
                new BufferedReader(new FileReader(filename), REPORT_FILE_BUFFER_SIZE));
        StringBuilder sb = new StringBuilder();
        String line;
        while (null != (line = r.readLine())) {
            sb.append(line);
        }

        JSONArray data = new JSONArray(sb.toString());

        JSONArray profileData = data.getJSONArray(0);
        JSONObject traceData = data.getJSONObject(1);

        return new Report(toTrace(traceData), toAnnotatedFiles(profileData));
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
}