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.kawanfw.sql.jdbc.StatementHttp.java

/**
 * Says if the file contains a ResultSet or if the file contains an
 * UpdateCount. if file contains an UpdateCount ==> first line is numeric
 * //from  w  ww  .  j av  a  2  s  . c o m
 * @param file
 *            the received file from the server
 * @return true if the file is a result set
 */
protected boolean isFileResultSet(File file) throws SQLException {

    LineNumberReader lineNumberReader = null;

    try {
        lineNumberReader = new LineNumberReader(new FileReader(file));
        String line = lineNumberReader.readLine();

        line = line.trim();

        if (line.startsWith("getUpdateCount=")) {

            String updateCountStr = StringUtils.substringAfter(line, "getUpdateCount=");

            try {
                updateCount = Integer.parseInt(updateCountStr);
            } catch (NumberFormatException e) {
                throw new SQLException(Tag.PRODUCT_PRODUCT_FAIL + e.getMessage(),
                        new IOException(e.getMessage(), e));
            }

            return false;
        } else if (line.startsWith(CallableParms.NO_RESULT_SET)) {
            return false;
        } else {
            return true;
        }
    } catch (IOException e) {
        JdbcHttpTransferUtil.wrapExceptionAsSQLException(e);
    } finally {
        IOUtils.closeQuietly(lineNumberReader);
    }

    return false;

}

From source file:com.autentia.tnt.manager.data.MigrationManager.java

/**
 * @return the original database version
 * @throws com.autentia.tnt.manager.data.exception.DataException
 *//*from   w ww .j  a  v a 2  s .c o m*/
public Version upgradeDatabase() throws DataException {
    Version ret = null;
    Version db = null;
    Version code = Version.getApplicationVersion();
    Session ses = HibernateUtil.getSessionFactory().openSession();
    Connection con = ses.connection();
    Statement stmt = null;
    LineNumberReader file = null;
    String delimiter = ";";

    try {
        db = Version.getDatabaseVersion();
        ret = db.clone();
        log.info("upgradeDatabase - >>>> STARTING MIGRATION FROM " + db + " TO " + code + " <<<<");

        // Disable auto-commit (just in case...)
        log.info("upgradeDatabase - disabling auto commit");
        con.setAutoCommit(false);

        // Create statement
        stmt = con.createStatement();

        // While necessary, upgrade database
        while (db.compareTo(code, Version.MINOR) < 0) {
            log.info("upgradeDatabase - " + db);

            // Compose script name and open it
            String script = SCRIPT_PREFIX + db.toString(Version.MINOR) + SCRIPT_SUFFIX;
            log.info("upgradeDatabase - loading script " + script);
            InputStream sqlScript = Thread.currentThread().getContextClassLoader().getResourceAsStream(script);
            if (sqlScript == null) {
                throw FileNotFoundException(script);
            }
            file = new LineNumberReader(new InputStreamReader(new BufferedInputStream(sqlScript), "UTF-8"));
            int _c;

            // 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.info(" " + 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.info("upgradeDatabase - executing batch of commands");
            stmt.executeBatch();

            // Re-read database version
            Version old = db;
            db = Version.getDatabaseVersion(con);
            if (old.equals(db)) {
                throw new DataException("Script was applied but did not upgrade database: " + script);
            }
            log.info("upgradeDatabase - database upgraded to version " + db);
        }

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

        // Report end of migration
        log.info("upgradeDatabase - >>>> MIGRATION SUCCESSFULLY FINISHED <<<<");
    } catch (Exception e) {
        log.error("upgradeDatabase - >>>> MIGRATION FAILED: WILL BE ROLLED BACK <<<<", e);
        try {
            con.rollback();
        } catch (SQLException e2) {
            log.error("upgradeDatabase - Error al realizar el rollback");
        }
        throw new DataException("Script was applied but did not upgrade database: ", e);
    } finally {
        if (file != null) {
            try {
                file.close();
            } catch (IOException e2) {
                log.error("upgradeDatabase - Error al cerrar el fichero de script ", e2);
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e2) {
                log.error("upgradeDatabase - Error al cerrar el statement");
            }
        }
        ses.close();
    }

    return ret;
}

From source file:com.castis.sysComp.PoisConverterSysComp.java

public void parseCategoryFile(File file, String sub) throws Exception {
    String line = "";
    FileInputStream in = null;//from   ww  w  .ja v a2 s  .c  o  m
    Reader isReader = null;
    LineNumberReader bufReader = null;

    try {
        String encodingCharset = FILE_CHARSET;

        in = new FileInputStream(file);
        isReader = new InputStreamReader(in, encodingCharset);
        bufReader = new LineNumberReader(isReader);

        boolean first = true;
        while ((line = bufReader.readLine()) != null) {
            if (first == true) {
                first = false;
                continue;
            }

            //Depth, Menu ID, Menu Name, Hidden, Menu Type.
            String result[] = line.split(",");

            String depth = result[0];
            String menuId = result[1];
            String menuName = result[2];
            String hidden = result[3];
            String menuType = result[5];

            if (depth == null || depth.equals("")) {
                throw new DataParsingException("data parsing error(depth)");
            }
            if (menuId == null || menuId.equals("")) {
                throw new DataParsingException("data parsing error(Menu ID)");
            }
            if (menuName == null || menuName.equals("")) {
                throw new DataParsingException("data parsing error(Menu Name)");
            }
            if (hidden == null || hidden.equals("")) {
                throw new DataParsingException("data parsing error(Hidden)");
            }
            if (menuType == null || menuType.equals("")) {
                throw new DataParsingException("data parsing error(Menu Type)");
            }

        }
    } catch (Exception e) {
        String errorMsg = e.getMessage();
        log.error(errorMsg, e);
        throw new DataParsingException(errorMsg, e); //throw(e);

    } finally {
        if (in != null)
            in.close();
        if (isReader != null)
            isReader.close();
        if (bufReader != null)
            bufReader.close();
    }

    String fileName = file.getName();
    int index = fileName.indexOf("-");
    if (index != -1) {
        fileName = fileName.substring(index + 1, fileName.length());
    }

    index = fileName.indexOf("_");

    String targetDir = resultDir;
    if (index != -1) {
        String directory = fileName.substring(0, index);
        targetDir += "/" + sub + "/" + directory;
    }

    try {
        File resultTargetDir = new File(CiFileUtil.getReplaceFullPath(targetDir));
        if (!resultTargetDir.isDirectory()) {
            CiFileUtil.createDirectory(targetDir);
        }

        CiFileUtil.renameFile(file, targetDir, fileName);

    } catch (Exception e) {
        log.error(e.getMessage());
    }

}

From source file:massbank.BatchJobWorker.java

/**
 * Ytt@C???ieLXg`?j//from w w  w.  j av  a  2s  .c  om
 * @param time NGXg 
 * @param resultFile t@C
 * @param textFile YtpeLXgt@C
 */
private void createTextFile(String time, File resultFile, File textFile) {
    NumberFormat nf = NumberFormat.getNumberInstance();
    LineNumberReader in = null;
    PrintWriter out = null;
    try {
        in = new LineNumberReader(new FileReader(resultFile));
        out = new PrintWriter(new BufferedWriter(new FileWriter(textFile)));

        // wb_?[?o
        String reqIonStr = "Both";
        try {
            if (Integer.parseInt(this.ion) > 0) {
                reqIonStr = "Positive";
            } else if (Integer.parseInt(this.ion) < 0) {
                reqIonStr = "Negative";
            }
        } catch (NumberFormatException nfe) {
            nfe.printStackTrace();
        }
        out.println("***** MassBank Batch Service Results *****");
        out.println();
        out.println("Request Date: " + time);
        out.println("# Instrument Type: " + this.inst);
        out.println("# Ion Mode: " + reqIonStr);
        out.println();
        out.println();

        // ?o
        String line;
        long queryCnt = 0;
        boolean readName = false;
        boolean readHit = false;
        boolean readNum = false;
        boolean isFinalLine = false;
        while ((line = in.readLine()) != null) {
            isFinalLine = false;
            if (in.getLineNumber() < 4) {
                continue;
            }
            if (!readName) {
                queryCnt++;
                out.println("### Query " + nf.format(queryCnt) + " ###");
                out.println("# Name: " + line.trim());
                readName = true;
            } else if (!readHit) {
                out.println("# Hit: " + nf.format(Integer.parseInt(line.trim())));
                out.println();
                readHit = true;
            } else if (!readNum) {
                out.println("Top " + line.trim() + " List");
                out.println("Accession\tTitle\tFormula\tIon\tScore\tHit");
                out.println();
                readNum = true;
            } else {
                if (!line.trim().equals("")) {
                    String[] data = formatLine(line);
                    StringBuilder sb = new StringBuilder();
                    sb.append(data[0]).append("\t").append(data[1]).append("\t").append(data[2]).append("\t")
                            .append(data[3]).append("\t").append(data[4]).append("\t").append(data[5]);
                    out.println(sb.toString());
                } else {
                    out.println();
                    out.println();
                    readName = false;
                    readHit = false;
                    readNum = false;
                    isFinalLine = true;
                }
            }
        }
        if (!isFinalLine) {
            out.println();
            out.println();
        }
        out.println("##### END #####");
        out.println();
        out.println("**********************************************************");
        out.println("*  MassBank.jp - High Resolution Mass Spectral Database  *");
        out.println("*    URL: http://www.massbank.jp/                        *");
        out.println("**********************************************************");
        out.println();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
        }
        if (out != null) {
            out.flush();
            out.close();
        }
    }
}

From source file:com.cisco.dvbu.ps.common.util.CommonUtils.java

/**
 * Find Lines Containing passed in match String from the passed in file
 * @param filePath file Path/*from w w w .  j  av a 2s  . co m*/
 * @param findMe find String
 * @return List of Matching Strings
 */
public static List<String> getLinesWithStringsInFile(String filePath, String findMe) {
    LineNumberReader lineReader = null;
    List<String> passwordLineList = null;
    try {
        lineReader = new LineNumberReader(new FileReader(filePath));
        String line = null;
        passwordLineList = new ArrayList<String>();
        while ((line = lineReader.readLine()) != null) {
            if (line.contains(findMe)) {
                passwordLineList.add(line);
            }
        }

    } catch (FileNotFoundException ex) {
        logger.error(ex.getMessage());
    } catch (IOException ex) {
        logger.error(ex.getMessage());
    } finally {
        try {
            if (lineReader != null)
                lineReader.close();
        } catch (IOException ex) {
            logger.error(ex.getMessage());
        }
    }
    return passwordLineList;
}

From source file:com.castis.sysComp.PoisConverterSysComp.java

public void parseViewCountFile(File file) throws Exception {
    String line = "";
    FileInputStream in = null;/*from w w  w.  ja  v  a 2 s .  c om*/
    Reader isReader = null;
    LineNumberReader bufReader = null;
    if (file.getName().contains("channel")) {
        type = "channel";
    } else {
        type = "vod";
    }

    try {
        String encodingCharset = FILE_CHARSET;

        in = new FileInputStream(file);
        isReader = new InputStreamReader(in, encodingCharset);
        bufReader = new LineNumberReader(isReader);

        boolean first = true;

        while ((line = bufReader.readLine()) != null) {
            if (line.length() == 0) {
                continue;
            }

            InputDataDTO data = new InputDataDTO();
            String result[] = line.split("\\|");
            if (first == true && result.length <= 1) {
                first = false;
                continue;
            }

            if (result[0] == null || result[0].equals("")) {
                throw new DataParsingException("data parsing error(region)");
            }

            if (result[1] == null || result[1].equals("")) {
                throw new DataParsingException("data parsing error(category)");
            }

            if (result[2] == null || result[2].equals("")) {
                throw new DataParsingException("data parsing error(weekday)");
            }

            if (result[3] == null || result[3].equals("")) {
                throw new DataParsingException("data parsing error(hour)");
            }

            if (result[4] == null || result[4].equals("")) {
                throw new DataParsingException("data parsing error(platform)");
            }

            if (result[5] == null || result[5].equals("")) {
                throw new DataParsingException("data parsing error(count)");
            }

            String platform = result[4];

            if (platform != null && platform.equalsIgnoreCase("stb"))
                platform = "STB";
            else if (platform != null && platform.equalsIgnoreCase("mobile")) {
                platform = "Mobile";
            }
            data.setPlatform(platform);

            List<TreeNodeDTO> tree = treeMap.get(platform);

            if (tree == null) {
                tree = getAxis(platform);
                treeMap.put(platform, tree);
            }

            String fullpath = getFullPath(tree, result[0]);

            if (fullpath == "") {
                throw new DataParsingException("region ID[" + result[0] + "] can't find fullpath.");
            }

            data.setRegion(fullpath);
            data.setCategory(result[1]);
            data.setWeekday(result[2]);
            data.setHour(result[3]);
            data.setCount(Integer.parseInt(result[5]));

            insertTreeNode(data);
        }

        for (WeekHourPair key : trees.keySet()) {
            Map<String, TreeNodeForCount> map = trees.get(key);
            calculateCount(map);
        }

        writeFile(file);

    } catch (Exception e) {
        String errorMsg = "Fail to parsing Line.[current line(" + bufReader.getLineNumber() + ") :" + line
                + "] : ";
        log.error(errorMsg, e);
        throw new DataParsingException(errorMsg, e); //throw(e);

    } finally {
        if (in != null)
            in.close();
        if (isReader != null)
            isReader.close();
        if (bufReader != null)
            bufReader.close();
    }
}

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

/**
 * Returns number of lines in a file.//from   w  w  w.jav  a 2  s .  c o m
 * 
 * @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:edu.stanford.muse.util.Util.java

public static String readFile(String file) throws IOException {
    StringBuilder sb = new StringBuilder();
    LineNumberReader lnr = new LineNumberReader(new InputStreamReader(new FileInputStream(file)));
    while (true) {
        String line = lnr.readLine();
        if (line == null)
            break;
        line = line.trim();/*from   w w  w  .ja  v  a 2s  . co  m*/
        sb.append(line);
        sb.append("\n");
    }
    lnr.close();
    return sb.toString();
}

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.
 * //from  w ww .ja  v  a  2  s  .  c  o  m
 * 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:com.netcrest.pado.tools.pado.PadoShell.java

public void runScript(File scriptFile) throws IOException {
    LineNumberReader reader = null;
    try {/*from w  w w . j av a  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();
        }
    }
}