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.gcaldaemon.core.sendmail.SendMail.java

private final void sendPlainText(String email, String content, GmailEntry entry) throws Exception {

    // Mail properties
    HashSet to = new HashSet();
    HashSet cc = new HashSet();
    HashSet bcc = new HashSet();
    String subject = "Mail from " + username;
    QuickWriter body = new QuickWriter(content.length());
    if (email != null) {
        to.add(email);//from  w  ww .j a  va  2s  . c  o m
    }

    // Parse text
    LineNumberReader reader = new LineNumberReader(new StringReader(content));
    boolean readingBody = false;
    String line, upper;
    for (;;) {
        line = reader.readLine();
        if (line == null) {
            break;
        }
        if (readingBody) {
            body.write(line);
            body.write(CRLF);
            continue;
        }
        if (line.trim().length() == 0) {
            continue;
        }
        upper = line.toUpperCase();
        if (upper.startsWith("ENCODING")) {
            continue;
        }
        if (upper.startsWith("SUBJECT")) {
            subject = getParameter(line);
            continue;
        }
        if (upper.startsWith("TO")) {
            addParameters(to, line);
            continue;
        }
        if (upper.startsWith("CC")) {
            addParameters(cc, line);
            continue;
        }
        if (upper.startsWith("BCC")) {
            addParameters(bcc, line);
            continue;
        }
        readingBody = true;
        body.write(line);
        body.write(CRLF);
    }

    // Submit mail
    String toList = "";
    String ccList = "";
    String bccList = "";

    Iterator i = to.iterator();
    while (i.hasNext()) {
        toList += (String) i.next() + ",";
    }
    i = cc.iterator();
    while (i.hasNext()) {
        ccList += (String) i.next() + ",";
    }
    i = bcc.iterator();
    while (i.hasNext()) {
        bccList += (String) i.next() + ",";
    }
    if (toList.length() == 0) {
        toList = username;
    }

    String msg = body.toString();
    boolean isHTML = msg.indexOf("/>") != -1 || msg.indexOf("</") != -1;
    if (isHTML) {
        msg = cropBody(msg);
    }
    if (isHTML) {
        log.debug("Sending HTML mail...");
    } else {
        log.debug("Sending plain-text mail...");
    }
    entry.send(toList, ccList, bccList, subject, msg, isHTML);
    log.debug("Mail submission finished.");
}

From source file:org.beangle.struts2.action.EntityDrivenAction.java

/**
 * //from   w w  w.j a  v  a2  s  .c om
 * 
 * @param upload
 * @param clazz
 * @return
 */
protected EntityImporter buildEntityImporter(String upload, Class<?> clazz) {
    try {
        File file = get(upload, File.class);
        if (null == file) {
            logger.error("cannot get upload file {}.", upload);
            return null;
        }
        String fileName = get(upload + "FileName");
        InputStream is = new FileInputStream(file);
        if (fileName.endsWith(".xls")) {
            EntityImporter importer = (clazz == null) ? new DefaultEntityImporter()
                    : new DefaultEntityImporter(clazz);
            importer.setReader(new ExcelItemReader(is, 1));
            put("importer", importer);
            return importer;
        } else {
            LineNumberReader reader = new LineNumberReader(new InputStreamReader(is));
            if (null == reader.readLine()) {
                reader.close();
                return null;
            }
            reader.reset();
            EntityImporter importer = (clazz == null) ? new DefaultEntityImporter()
                    : new DefaultEntityImporter(clazz);
            importer.setReader(new CsvItemReader(reader));
            return importer;
        }
    } catch (MyException e) {
        logger.error("saveAndForwad failure", e);
        return null;
    } catch (Exception e) {
        logger.error("error", e);
        return null;
    }
}

From source file:com.smartgwt.extensions.fileuploader.server.TestServiceImpl.java

/**
 * This files a test file that contains a response for all CRUD operations. See example
 * profile.xq.xml file.//from w  w w . j  a va2 s . c o m
 * @param out
 * @param context
 * @param model
 * @param xq
 * @param op
 * @throws Exception
 */
private void getResponse(PrintWriter out, String context, String model, String xq, String op) throws Exception {
    String path = "src/test/webapp/WEB-INF/models/" + model + "/" + xq + ".xml";
    System.out.println("getting datafile " + path);
    LineNumberReader in = null;
    File f = new File(path);
    if (!f.exists()) {
        System.out.println("File not found:" + path);
        out.println("<response>");
        out.println("  <status>1</status");
        out.println("</response>");
        return;
    }
    try {
        String start = "<" + op + ">";
        String end = "</" + op + ">";
        in = new LineNumberReader(new FileReader(f));
        String line = null;
        boolean inOp = false;
        while ((line = in.readLine()) != null) {
            if (line.indexOf(start) > 0)
                inOp = true;
            else if (line.indexOf(end) > 0)
                inOp = false;
            else if (inOp)
                out.println(line);
            //System.out.println(line);
        }
    } catch (FileNotFoundException fnf) {
        throw new Exception(fnf);
    } finally {
        if (in != null)
            try {
                in.close();
            } catch (Exception e) {
            }
        ;
    }
}

From source file:org.onecmdb.core.utils.transform.csv.CSVDataSource.java

private String handleEndOfLine(LineNumberReader lin, String line) throws IOException {
    if (this.textDelimiter == null || this.textDelimiter.length() == 0) {
        return (line);
    }/*from  w w w.j  a va  2  s . com*/
    int count = 0;
    for (char c : line.toCharArray()) {
        if (c == this.textDelimiter.charAt(0)) {
            count++;
        }
    }
    // If we have a even number of textDel then we are fine.
    if ((count % 2) == 0) {
        return (line);
    }

    // Else read next line.
    String nextLine = lin.readLine();
    if (nextLine == null) {
        return (line);
    }
    line = line + nextLine;

    return (handleEndOfLine(lin, line));
}

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

private FileContent readElementData(final String header, final LineNumberReader reader) throws IOException {
    final StringBuffer content = new StringBuffer();
    String line;//w  w  w  .  j av a2  s.c o m
    while ((line = reader.readLine()) != null) {
        if (line.length() == 0) {
            break;
        }
        content.append(line);
        content.append('\n');
    }

    final char command = header.charAt(0);
    final String[] split = header.substring(1).split(" ");
    final String type = split[0];
    final String id = split[1];
    final String version = split[2];
    return new FileContent(command, id, null, version, type, content.toString());
}

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  .java2 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;
    }
}

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

private GeoPathFinding() {
    LineNumberReader lnr = null;
    try {//w  ww  . j  a v  a  2  s.c o m
        _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.wildfly.core.test.standalone.mgmt.api.core.ResponseAttachmentTestCase.java

private void readLogStream(InputStream stream) throws IOException {
    LineNumberReader reader = new LineNumberReader(new InputStreamReader(stream, StandardCharsets.UTF_8));
    String read;/*from   ww w.j  a  va 2  s.c o  m*/
    String lastRead = null;
    boolean readMessage = false;
    String expected = LogStreamExtension.getLogMessage(logMessageContent);
    while ((read = reader.readLine()) != null) {
        readMessage = readMessage || read.contains(expected);
        lastRead = read;
    }

    Assert.assertTrue("Did not see " + expected + " -- last read was " + lastRead, readMessage);

}

From source file:org.diffkit.db.DKDBInsertTableLoader.java

/**
 * @return true if the load succeeded/*  w  w w .  jav a2  s  .  c om*/
 * @throws IOException
 */
public boolean load(DKDBTable table_, File csvFile_) throws IOException, SQLException {
    _log.debug("table_->{}", table_);
    _log.debug("csvFile_->{}", csvFile_);
    DKValidate.notNull(table_, csvFile_);
    if (!csvFile_.canRead())
        throw new IOException(String.format("can't read csvFile_->%s", csvFile_));
    if (!_database.tableExists(table_))
        throw new IOException(String.format("table_->%s does not exist in database->", table_, _database));
    Connection connection = _database.getConnection();
    _log.debug("connection->{}", connection);
    if (connection == null)
        throw new SQLException(String.format("can't get connection from database->", _database));

    connection.setAutoCommit(true);
    this.setDateFormat(connection);
    LineNumberReader reader = new LineNumberReader(new BufferedReader(new FileReader(csvFile_)));
    String[] tableColumnNames = table_.getColumnNames();
    DKDBTypeInfo[] typeInfos = _database.getColumnConcreteTypeInfos(table_);
    if (_debugEnabled) {
        _log.debug("tableColumnNames->{}", Arrays.toString(tableColumnNames));
        _log.debug("typeInfos->{}", Arrays.toString(typeInfos));
    }
    String line = null;
    List<String> updateStatements = new ArrayList<String>(LOAD_BATCH_SIZE);
    // assume first line is header, use column names to drive the line parse
    line = StringUtils.trimToNull(reader.readLine());
    String[] headerColumnNames = line.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
    int[] loadIndices = DKArrayUtil.getIndicesOfIntersection(headerColumnNames, tableColumnNames);
    if (_debugEnabled) {
        _log.debug("headerColumnNames->{}", Arrays.toString(headerColumnNames));
        _log.debug("loadIndices->{}", Arrays.toString(loadIndices));
    }
    for (long i = 1; (line = StringUtils.trimToNull(reader.readLine())) != null; i++) {
        String[] values = line.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
        if (_debugEnabled) {
            _log.debug("line: " + line);
            _log.debug("values: " + Arrays.toString(values));
        }
        DKStringUtil.unquote(values, Quote.DOUBLE);
        values = DKArrayUtil.retainElementsAtIndices(values, loadIndices);
        if (_debugEnabled) {
            _log.debug("values: " + Arrays.toString(values));
        }
        if (!(values.length == tableColumnNames.length))
            throw new RuntimeException(
                    String.format("number of values->%s does not match number of columns->%s", values.length,
                            tableColumnNames.length));
        String insertStatementString = _database.generateInsertDML(values, typeInfos, tableColumnNames,
                table_.getSchema(), table_.getTableName());
        updateStatements.add(insertStatementString);
        _log.debug("insertStatementString: " + insertStatementString);
        if (i % LOAD_BATCH_SIZE == 0) {
            DKSqlUtil.executeBatchUpdate(updateStatements, connection);
            _log.debug("inserted " + i + " rows");
            updateStatements.clear();
        }
    }
    long updates = DKSqlUtil.executeBatchUpdate(updateStatements, connection);
    DKSqlUtil.close(connection);
    _log.debug("updates: " + updates);
    reader.close();
    return true;
}

From source file:org.kalypso.kalypsomodel1d2d.sim.IterationInfo.java

@Override
public void readIterFile() throws IOException {
    m_itrFile.refresh();/* w  ww.  ja  v a  2 s . co m*/
    if (!m_itrFile.exists())
        return;

    /* Read file and write outputs */
    LineNumberReader lnr = null;
    try {
        // final InputStream inputStream = m_itrFile.getContent().getInputStream();
        final byte[] content = FileUtil.getContent(m_itrFile);
        // lnr = new LineNumberReader( new BufferedReader( new InputStreamReader( inputStream ) ) );
        lnr = new LineNumberReader(new StringReader(new String(content, Charset.defaultCharset())));
        while (lnr.ready()) {
            final String line = lnr.readLine();
            if (line == null)
                break;

            processLine(line, lnr.getLineNumber());
        }
    } catch (final FileNotFoundException e) {
        // FIXME: stati are never used; what happened here?!
        //      if( lnr == null )
        //        StatusUtilities.createStatus( IStatus.WARNING, ISimulation1D2DConstants.CODE_RMA10S, Messages.getString( "org.kalypso.kalypsomodel1d2d.sim.IterationInfo.1" ), e ); //$NON-NLS-1$
        //
        //      final String msg = Messages.getString( "org.kalypso.kalypsomodel1d2d.sim.IterationInfo.2", lnr.getLineNumber() ); //$NON-NLS-1$
        //      StatusUtilities.createStatus( IStatus.WARNING, ISimulation1D2DConstants.CODE_RMA10S, msg, e );
    } finally {
        IOUtils.closeQuietly(lnr);
    }
}