Example usage for java.util Scanner hasNextLine

List of usage examples for java.util Scanner hasNextLine

Introduction

In this page you can find the example usage for java.util Scanner hasNextLine.

Prototype

public boolean hasNextLine() 

Source Link

Document

Returns true if there is another line in the input of this scanner.

Usage

From source file:com.cisco.dbds.utils.tims.TIMS.java

/**
 * Readhtmlfile fail./*from w w w .j  av  a  2  s  .  c om*/
 *
 * @return the array list
 * @throws FileNotFoundException the file not found exception
 */
public static ArrayList<String> readhtmlfileFail() throws FileNotFoundException {
    ArrayList<String> re = new ArrayList<String>();
    String fEncoding = "UTF-8";
    String tt = "";
    int cc = 0;
    Scanner scanner = new Scanner(new FileInputStream(fFileName), fEncoding);
    try {
        while (scanner.hasNextLine()) {

            tt = scanner.nextLine();
            tt = tt.trim();

            if (tt.contains("FAILED TIMS TEST CASES")) {
                cc = 1;
            }
            if (tt.contains("FAILED NON-TIMS TEST CASE ERROR LIST")) {
                return re;
            }
            if (cc == 1 && tt.contains("Ttv") && !(tt.contains("Precheck")) && !(tt.contains("Precondition"))) {
                int charCount = 0;
                int pos = 0;
                if (!tt.startsWith("Ttv")) {
                    for (int i = 0; i < tt.length(); i++) {
                        if (tt.charAt(i) == '_') {
                            charCount++;
                            if (charCount == 2) {
                                pos = i;
                                break;
                            }
                        }
                    }
                }

                String tcid = null;
                if (charCount == 2 && (!tt.startsWith("Ttv"))) {
                    int k = nthOccurrence(tt, '_', 0);
                    tcid = tt.substring(k + 1, tt.length() - 5);
                    if (!tcid.startsWith("Ttv")) {
                        tcid = tt.substring(16, tt.length() - 5);
                    }
                } else if (charCount == 2) {
                    tcid = tt.substring(pos - 11, tt.length() - 5);
                } else {
                    tcid = tt.substring(pos + 16, tt.length() - 5);
                }
                //System.out.println(tt);
                System.out.println(tcid);
                re.add(tcid);

            }

        }

    } finally {
        scanner.close();
    }
    return re;
}

From source file:com.sat.spvgt.utils.tims.TIMS.java

/**
 * Readhtmlfile fail.//from w w  w.  j  a  v  a 2s . c  om
 * 
 * @return the array list
 * @throws FileNotFoundException
 *             the file not found exception
 */
public static ArrayList<String> readhtmlfileFail() throws FileNotFoundException {
    ArrayList<String> re = new ArrayList<String>();
    String fEncoding = "UTF-8";
    String tt = "";
    int cc = 0;
    Scanner scanner = new Scanner(new FileInputStream(fFileName), fEncoding);
    try {
        while (scanner.hasNextLine()) {

            tt = scanner.nextLine();
            tt = tt.trim();

            if (tt.contains("FAILED TIMS TEST CASES")) {
                cc = 1;
            }
            if (tt.contains("FAILED NON-TIMS TEST CASE ERROR LIST")) {
                return re;
            }
            if (cc == 1 && tt.contains("Ttv") && !(tt.contains("Precheck")) && !(tt.contains("Precondition"))) {
                int charCount = 0;
                int pos = 0;
                if (!tt.startsWith("Ttv")) {
                    for (int i = 0; i < tt.length(); i++) {
                        if (tt.charAt(i) == '_') {
                            charCount++;
                            if (charCount == 2) {
                                pos = i;
                                break;
                            }
                        }
                    }
                }

                String tcid = null;
                if (charCount == 2 && (!tt.startsWith("Ttv"))) {
                    int k = nthOccurrence(tt, '_', 0);
                    tcid = tt.substring(k + 1, tt.length() - 5);
                    if (!tcid.startsWith("Ttv")) {
                        tcid = tt.substring(16, tt.length() - 5);
                    }
                } else if (charCount == 2) {
                    tcid = tt.substring(pos - 11, tt.length() - 5);
                } else {
                    tcid = tt.substring(pos + 16, tt.length() - 5);
                }
                // System.out.println(tt);
                System.out.println(tcid);
                re.add(tcid);

            }

        }

    } finally {
        scanner.close();
    }
    return re;
}

From source file:org.jbpm.designer.web.preprocessing.impl.JbpmPreprocessingUnit.java

protected static String readFile(String pathname) throws IOException {
    if (pathname == null) {
        return null;
    }/*from  ww w.  jav  a  2s . co m*/

    StringBuilder fileContents = new StringBuilder();
    String lineSeparator = System.getProperty("line.separator");

    Scanner scanner = null;
    try {
        scanner = new Scanner(new File(pathname), "UTF-8");
        while (scanner.hasNextLine()) {
            fileContents.append(scanner.nextLine() + lineSeparator);
        }
        return fileContents.toString();
    } finally {
        IOUtils.closeQuietly(scanner);
    }
}

From source file:eu.cassandra.utils.Utils.java

/**
 * This function is used when the user has already tracked the electrical
 * appliances installed in the installation. He can used them as a base case
 * and extend it with any additional ones that may be found during the later
 * stages of analysis of the consumption.
 * /* ww w.  j  a v  a  2 s .c o  m*/
 * @param filename
 *          The filename of the file containing the appliances.
 * @return
 *         A list of appliances
 * @throws FileNotFoundException
 */
public static ArrayList<Appliance> appliancesFromFile(String filename) throws FileNotFoundException {
    // Read appliance file and start appliance parsing
    File file = new File(filename);
    Scanner input = new Scanner(file);

    ArrayList<Appliance> appliances = new ArrayList<Appliance>();

    String nextLine;
    String[] line;

    while (input.hasNextLine()) {
        nextLine = input.nextLine();
        line = nextLine.split(",");
        String name = line[0];
        String activity = line[1];

        if (activity.contains("Standby") == false && activity.contains("Refrigeration") == false) {

            double p = Double.parseDouble(line[2]);
            double q = Double.parseDouble(line[3]);

            // For each appliance found in the file, an temporary Appliance
            // Entity is created.
            appliances.add(new Appliance(name, activity, p, q, 0, 100));

        }
    }

    System.out.println("Appliances:" + appliances.size());

    input.close();

    return appliances;
}

From source file:com.joliciel.talismane.stats.FScoreCalculator.java

/**
 * Combine the results of n cross validation results into a single f-score file.
 * @param directory//from w  w  w .ja  va2  s  .c o m
 * @param prefix
 * @param suffix
 * @param csvFileWriter
 */
static void combineCrossValidationResults(File directory, String prefix, String suffix, Writer csvFileWriter) {
    try {
        File[] files = directory.listFiles();
        Map<Integer, Map<String, FScoreStats>> fileStatsMap = new HashMap<Integer, Map<String, FScoreStats>>();
        for (File file : files) {
            if (file.getName().startsWith(prefix) && file.getName().endsWith(suffix)) {
                int index = Integer.parseInt(file.getName().substring(prefix.length(), prefix.length() + 1));
                Map<String, FScoreStats> statsMap = new HashMap<String, FScoreCalculator.FScoreStats>();
                fileStatsMap.put(index, statsMap);
                Scanner scanner = new Scanner(
                        new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")));

                boolean firstLine = true;
                int truePositivePos = -1;

                while (scanner.hasNextLine()) {
                    String line = scanner.nextLine();
                    List<String> cells = CSV.getCSVCells(line);
                    if (firstLine) {
                        int i = 0;
                        for (String cell : cells) {
                            if (cell.equals("true+")) {
                                truePositivePos = i;
                                break;
                            }
                            i++;
                        }
                        if (truePositivePos < 0) {
                            throw new JolicielException("Couldn't find true+ on first line");
                        }
                        firstLine = false;
                    } else {
                        FScoreStats stats = new FScoreStats();
                        String outcome = cells.get(0);
                        stats.outcome = outcome;
                        if (outcome.equals("AVERAGE"))
                            break;
                        stats.truePos = Integer.parseInt(cells.get(truePositivePos));
                        stats.falsePos = Integer.parseInt(cells.get(truePositivePos + 1));
                        stats.falseNeg = Integer.parseInt(cells.get(truePositivePos + 2));
                        stats.precision = Double.parseDouble(cells.get(truePositivePos + 3));
                        stats.recall = Double.parseDouble(cells.get(truePositivePos + 4));
                        stats.fScore = Double.parseDouble(cells.get(truePositivePos + 5));
                        statsMap.put(outcome, stats);
                    } // firstLine?
                } // has more lines
                scanner.close();
            } // file in current series
        } // next file

        int numFiles = fileStatsMap.size();
        if (numFiles == 0) {
            throw new JolicielException("No files found matching prefix and suffix provided");
        }
        Map<String, DescriptiveStatistics> descriptiveStatsMap = new HashMap<String, DescriptiveStatistics>();
        Map<String, FScoreStats> outcomeStats = new HashMap<String, FScoreCalculator.FScoreStats>();
        Set<String> outcomes = new TreeSet<String>();
        for (Map<String, FScoreStats> statsMap : fileStatsMap.values()) {
            for (FScoreStats stats : statsMap.values()) {
                DescriptiveStatistics fScoreStats = descriptiveStatsMap.get(stats.outcome + "fScore");
                if (fScoreStats == null) {
                    fScoreStats = new DescriptiveStatistics();
                    descriptiveStatsMap.put(stats.outcome + "fScore", fScoreStats);
                }
                fScoreStats.addValue(stats.fScore);
                DescriptiveStatistics precisionStats = descriptiveStatsMap.get(stats.outcome + "precision");
                if (precisionStats == null) {
                    precisionStats = new DescriptiveStatistics();
                    descriptiveStatsMap.put(stats.outcome + "precision", precisionStats);
                }
                precisionStats.addValue(stats.precision);
                DescriptiveStatistics recallStats = descriptiveStatsMap.get(stats.outcome + "recall");
                if (recallStats == null) {
                    recallStats = new DescriptiveStatistics();
                    descriptiveStatsMap.put(stats.outcome + "recall", recallStats);
                }
                recallStats.addValue(stats.recall);

                FScoreStats outcomeStat = outcomeStats.get(stats.outcome);
                if (outcomeStat == null) {
                    outcomeStat = new FScoreStats();
                    outcomeStat.outcome = stats.outcome;
                    outcomeStats.put(stats.outcome, outcomeStat);
                }
                outcomeStat.truePos += stats.truePos;
                outcomeStat.falsePos += stats.falsePos;
                outcomeStat.falseNeg += stats.falseNeg;

                outcomes.add(stats.outcome);
            }
        }

        csvFileWriter.write(CSV.format(prefix + suffix));
        csvFileWriter.write("\n");
        csvFileWriter.write(CSV.format("outcome"));
        csvFileWriter.write(CSV.format("true+") + CSV.format("false+") + CSV.format("false-")
                + CSV.format("tot precision") + CSV.format("avg precision") + CSV.format("dev precision")
                + CSV.format("tot recall") + CSV.format("avg recall") + CSV.format("dev recall")
                + CSV.format("tot f-score") + CSV.format("avg f-score") + CSV.format("dev f-score") + "\n");

        for (String outcome : outcomes) {
            csvFileWriter.write(CSV.format(outcome));
            FScoreStats outcomeStat = outcomeStats.get(outcome);
            DescriptiveStatistics fScoreStats = descriptiveStatsMap.get(outcome + "fScore");
            DescriptiveStatistics precisionStats = descriptiveStatsMap.get(outcome + "precision");
            DescriptiveStatistics recallStats = descriptiveStatsMap.get(outcome + "recall");
            outcomeStat.calculate();
            csvFileWriter.write(CSV.format(outcomeStat.truePos));
            csvFileWriter.write(CSV.format(outcomeStat.falsePos));
            csvFileWriter.write(CSV.format(outcomeStat.falseNeg));
            csvFileWriter.write(CSV.format(outcomeStat.precision * 100));
            csvFileWriter.write(CSV.format(precisionStats.getMean()));
            csvFileWriter.write(CSV.format(precisionStats.getStandardDeviation()));
            csvFileWriter.write(CSV.format(outcomeStat.recall * 100));
            csvFileWriter.write(CSV.format(recallStats.getMean()));
            csvFileWriter.write(CSV.format(recallStats.getStandardDeviation()));
            csvFileWriter.write(CSV.format(outcomeStat.fScore * 100));
            csvFileWriter.write(CSV.format(fScoreStats.getMean()));
            csvFileWriter.write(CSV.format(fScoreStats.getStandardDeviation()));
            csvFileWriter.write("\n");
            csvFileWriter.flush();
        }
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
}

From source file:com.tibco.tgdb.test.lib.TGAdmin.java

/**
 * Get connections synchronously. /*  w  w  w.j  a v  a2  s .c  o  m*/
 * Operation blocks until it is completed.
 * 
 * @param tgServer TG server to get connections from
 * @param tgNetListenerName Name of the net listener for TG Admin to connect to - if null connect to 1st one
 * @param logFile TG admin log file location - Generated by admin
 * @param logLevel Specify the log level: info/user1/user2/user3/debug/debugmemory/debugwire
 * @param timeout Number of milliseconds allowed to complete the stop server operation - If lower than 0 wait forever
 * @return Array of session IDs
 * @throws TGAdminException Admin execution fails or timeout occurs 
 */
public static String[] getConnections(TGServer tgServer, String tgNetListenerName, String logFile,
        String logLevel, long timeout) throws TGAdminException {

    String output = showConnections(tgServer, tgNetListenerName, logFile, logLevel, timeout);
    Scanner scanner = new Scanner(output);
    boolean counting = false;
    //int indexClientId;
    int indexSessionId = 0;
    int adminConnectionCount = 0;
    List<String> connectionList = new ArrayList<String>();
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        if (line.contains("Client ID")) {
            counting = true;
            //indexClientId = line.indexOf("Client ID");
            indexSessionId = line.indexOf("Session ID");
        } else if (line.contains("----------"))
            counting = false;
        else if (line.contains("connection(s) returned")) {
            counting = false;
            adminConnectionCount = Integer.parseInt(line.substring(0, line.indexOf(' ', 0)));
        } else if (counting) {
            connectionList.add(line.substring(indexSessionId, line.indexOf(' ', indexSessionId)));
        }
    }
    scanner.close();
    if (connectionList.size() != adminConnectionCount)
        throw new TGAdminException("TGAdmin - Not able to determine number of connections");
    return connectionList.toArray(new String[0]);
}

From source file:com.tibco.tgdb.test.lib.TGAdmin.java

/**
 * Get connections for a given user. // w  ww. j a  v a2  s  . c o  m
 * Operation blocks until it is completed.
 * 
 * @param tgServer TG server to get connections from
 * @param tgNetListenerName Name of the net listener for TG Admin to connect to - if null connect to 1st one
 * @param user User name to get the connections from
 * @param logFile TG admin log file location - Generated by admin
 * @param logLevel Specify the log level: info/user1/user2/user3/debug/debugmemory/debugwire
 * @param timeout Number of milliseconds allowed to complete the stop server operation - If lower than 0 wait forever
 *
 * @return Array of session IDs belonging to the user
 * @throws TGAdminException Admin execution fails or timeout occurs 
 */
public static String[] getConnectionsByUser(TGServer tgServer, String tgNetListenerName, String user,
        String logFile, String logLevel, long timeout) throws TGAdminException {

    String output = showConnections(tgServer, tgNetListenerName, logFile, logLevel, timeout);
    Scanner scanner = new Scanner(output);
    boolean counting = false;
    //int indexClientId;
    int indexSessionId = 0;
    //int adminConnectionCount = 0;
    List<String> connectionList = new ArrayList<String>();
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        if (line.contains("Client ID")) {
            counting = true;
            //indexClientId = line.indexOf("Client ID");
            indexSessionId = line.indexOf("Session ID");
        } else if (line.contains("----------"))
            counting = false;
        else if (line.contains("connection(s) returned")) {
            counting = false;
            //adminConnectionCount = Integer.parseInt(line.substring(0, line.indexOf(' ', 0)));
        } else if (counting) {
            if (line.contains(" " + user + " "))
                connectionList.add(line.substring(indexSessionId, line.indexOf(' ', indexSessionId)));
        }
    }
    scanner.close();
    //if (connectionList.size() != adminConnectionCount)
    //   throw new TGAdminException("TGAdmin - Not able to determine number of connections");
    return connectionList.toArray(new String[0]);
}

From source file:com.kscs.server.web.source.JavaSourceCode.java

public String readfile(String filename) {
    File file = new File("/home/sinhlk/myspace/tool/src/main/resources/" + filename);
    StringBuilder result = new StringBuilder("");
    try {//from  w w  w  .j  a  va  2s . c  om
        Scanner scanner = new Scanner(file);
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            result.append(line).append("\n");
        }

        scanner.close();

    } catch (IOException e) {
        e.printStackTrace();
    }

    String sourceFile = result.toString();
    return sourceFile;
}

From source file:csns.importer.parser.csula.StudentsParserImpl.java

/**
 * This parser handles data copy&pasted from an Excel file produced from GET
 * data. The format is expected to be <quarter cin first_name last_name ...>
 * where quarter is a 4-digit code. Currently we only process the first four
 * fields./* ww  w .  j a va  2 s. c om*/
 */
@Override
public List<ImportedUser> parse(String text) {
    List<ImportedUser> students = new ArrayList<ImportedUser>();

    Scanner scanner = new Scanner(text);
    while (scanner.hasNextLine()) {
        ImportedUser student = parseLine(scanner.nextLine());
        if (student != null)
            students.add(student);
    }
    scanner.close();

    return students;
}

From source file:com.nextdoor.bender.Bender.java

protected static void invokeKinesisHandler(String stream_name, String source_file) throws HandlerException {
    String sourceArn = "arn:aws:kinesis:" + AWS_REGION + ":" + AWS_ACCOUNT + ":stream/" + stream_name;
    logger.info("Invoking the Kinesis Handler...");

    TestContext ctx = getContext();/*from ww  w  . ja  va 2 s .  c  o  m*/
    KinesisHandler handler = new KinesisHandler();

    /*
     * Set the arrival timestamp as the function run time.
     */
    Date approximateArrivalTimestamp = new Date();
    approximateArrivalTimestamp.setTime(System.currentTimeMillis());

    /*
     * Open up the source file for events
     */
    Scanner scan = null;
    try {
        scan = new Scanner(new File(source_file));
    } catch (FileNotFoundException e) {
        logger.error("Could not find source file (" + source_file + "): " + e);
        System.exit(1);
    }

    /*
     * Create a series of KinesisEvents from the source file. All of these events will be treated as
     * a single batch that was pushed to Kinesis, so they will all have the same Arrival Time.
     */
    logger.info("Parsing " + source_file + "...");

    List<KinesisEvent.KinesisEventRecord> events = new ArrayList<KinesisEvent.KinesisEventRecord>();
    int r = 0;

    /*
     * Walk through the source file. For each line in the file, turn the line into a KinesisRecord.
     */
    while (scan.hasNextLine()) {
        String line = scan.nextLine();
        Record rec = new Record();
        rec.withPartitionKey("1").withSequenceNumber(r + "").withData(ByteBuffer.wrap(line.getBytes()))
                .withApproximateArrivalTimestamp(approximateArrivalTimestamp);

        KinesisEventRecord krecord = new KinesisEventRecord();
        krecord.setKinesis(rec);
        krecord.setEventSourceARN(sourceArn);
        krecord.setEventID("shardId-000000000000:" + UUID.randomUUID());
        events.add(krecord);

        r += 1;
    }

    logger.info("Read " + r + " records");

    /*
     * Create the main Kinesis Event object - this holds all of the data and records that will be
     * passed into the Kinesis Handler.
     */
    KinesisEvent kevent = new KinesisEvent();
    kevent.setRecords(events);

    /*
     * Invoke handler
     */
    handler.handler(kevent, ctx);
    handler.shutdown();
}