Example usage for java.util Scanner close

List of usage examples for java.util Scanner close

Introduction

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

Prototype

public void close() 

Source Link

Document

Closes this scanner.

Usage

From source file:com.all.login.services.LoginModelDao.java

private List<City> getCities() {
    if (cities == null) {
        synchronized (this) {
            if (cities == null) {
                List<City> cities = new ArrayList<City>();
                Scanner scanner = null;
                try {
                    scanner = new Scanner(getClass().getResourceAsStream("/scripts/cities.txt"));
                    while (scanner.hasNextLine()) {
                        String text = scanner.nextLine();
                        if (text.startsWith("('")) {
                            try {
                                City city = new City();
                                String[] data = getSmartData(text);
                                city.setCityId(data[0]);
                                city.setCityName(data[1]);
                                city.setCountryId(data[2]);
                                city.setCountryName(data[3]);
                                city.setStateId(data[4]);
                                city.setStateName(data[5]);
                                city.setPopIndex(data[6]);
                                cities.add(city);
                            } catch (Exception e) {
                                LOG.error(e, e);
                            }// www . j  ava 2s .c o  m
                        }
                    }
                } catch (Exception e) {
                    LOG.error(e, e);
                } finally {
                    try {
                        scanner.close();
                    } catch (Exception e) {
                        LOG.error(e, e);
                    }
                }

                this.cities = cities;
            }
        }
    }
    return cities;
}

From source file:org.eclipse.hono.example.ExampleSender.java

/**
 * Reads user input from the console and sends it to the Hono server.
 *///from  w  w  w.j  a  v a  2  s. c  o m
@EventListener(classes = { ApplicationReadyEvent.class })
public void readMessagesFromStdin() {

    Runnable reader = new Runnable() {

        public void run() {
            try {
                // give Spring Boot some time to log its startup messages
                Thread.sleep(50);
            } catch (InterruptedException e) {
            }
            LOG.info("sender for tenant [{}] created successfully", tenantId);
            LOG.info("Enter some message(s) (hit return to send, ctrl-c to quit)");
            String input;
            Scanner scanner = new Scanner(System.in);
            do {
                input = scanner.nextLine();
                final String msg = input;
                if (!msg.isEmpty()) {

                    final Map<String, Object> properties = new HashMap<>();
                    properties.put("my_prop_string", "I'm a string");
                    properties.put("my_prop_int", 10);
                    final CountDownLatch latch = new CountDownLatch(1);
                    Future<Boolean> sendTracker = Future.future();
                    sendTracker.setHandler(s -> {
                        if (s.failed()) {
                            LOG.info(s.cause().getMessage());
                        }
                    });

                    getRegistrationAssertion().compose(token -> {
                        return send(msg, properties, token);
                    }).compose(sent -> {
                        latch.countDown();
                        sendTracker.complete();
                    }, sendTracker);

                    try {
                        if (!latch.await(2, TimeUnit.SECONDS)) {
                            sendTracker.fail("cannot connect to server");
                        }
                    } catch (InterruptedException e) {
                        // nothing to do
                    }
                }
            } while (!input.isEmpty());
            scanner.close();
        };
    };
    new Thread(reader).start();
}

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

/**
 * Readhtmlfile fail./*from  w  ww .ja va  2  s  .  c o m*/
 *
 * @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:edu.harvard.iq.dataverse.dataaccess.TabularSubsetGenerator.java

public static Float[] subsetFloatVector(InputStream in, int column, int numCases) {
    Float[] retVector = new Float[numCases];
    Scanner scanner = new Scanner(in);
    scanner.useDelimiter("\\n");

    for (int caseIndex = 0; caseIndex < numCases; caseIndex++) {
        if (scanner.hasNext()) {
            String[] line = (scanner.next()).split("\t", -1);
            // Verified: new Float("nan") works correctly, 
            // resulting in Float.NaN;
            // Float("[+-]Inf") doesn't work however; 
            // (the constructor appears to be expecting it
            // to be spelled as "Infinity", "-Infinity", etc. 
            if ("inf".equalsIgnoreCase(line[column]) || "+inf".equalsIgnoreCase(line[column])) {
                retVector[caseIndex] = java.lang.Float.POSITIVE_INFINITY;
            } else if ("-inf".equalsIgnoreCase(line[column])) {
                retVector[caseIndex] = java.lang.Float.NEGATIVE_INFINITY;
            } else if (line[column] == null || line[column].equals("")) {
                // missing value:
                retVector[caseIndex] = null;
            } else {
                try {
                    retVector[caseIndex] = new Float(line[column]);
                } catch (NumberFormatException ex) {
                    retVector[caseIndex] = null; // missing value
                }// w ww  .  j  a  v  a 2  s  .  c  o m
            }
        } else {
            scanner.close();
            throw new RuntimeException("Tab file has fewer rows than the stored number of cases!");
        }
    }

    int tailIndex = numCases;
    while (scanner.hasNext()) {
        String nextLine = scanner.next();
        if (!"".equals(nextLine)) {
            scanner.close();
            throw new RuntimeException(
                    "Column " + column + ": tab file has more nonempty rows than the stored number of cases ("
                            + numCases + ")! current index: " + tailIndex + ", line: " + nextLine);
        }
        tailIndex++;
    }

    scanner.close();
    return retVector;

}

From source file:edu.harvard.iq.dataverse.dataaccess.TabularSubsetGenerator.java

public static Double[] subsetDoubleVector(InputStream in, int column, int numCases) {
    Double[] retVector = new Double[numCases];
    Scanner scanner = new Scanner(in);
    scanner.useDelimiter("\\n");

    for (int caseIndex = 0; caseIndex < numCases; caseIndex++) {
        if (scanner.hasNext()) {
            String[] line = (scanner.next()).split("\t", -1);

            // Verified: new Double("nan") works correctly, 
            // resulting in Double.NaN;
            // Double("[+-]Inf") doesn't work however; 
            // (the constructor appears to be expecting it
            // to be spelled as "Infinity", "-Infinity", etc. 
            if ("inf".equalsIgnoreCase(line[column]) || "+inf".equalsIgnoreCase(line[column])) {
                retVector[caseIndex] = java.lang.Double.POSITIVE_INFINITY;
            } else if ("-inf".equalsIgnoreCase(line[column])) {
                retVector[caseIndex] = java.lang.Double.NEGATIVE_INFINITY;
            } else if (line[column] == null || line[column].equals("")) {
                // missing value:
                retVector[caseIndex] = null;
            } else {
                try {
                    retVector[caseIndex] = new Double(line[column]);
                } catch (NumberFormatException ex) {
                    retVector[caseIndex] = null; // missing value
                }//from w  w w.  j  a  v a 2s.c  om
            }

        } else {
            scanner.close();
            throw new RuntimeException("Tab file has fewer rows than the stored number of cases!");
        }
    }

    int tailIndex = numCases;
    while (scanner.hasNext()) {
        String nextLine = scanner.next();
        if (!"".equals(nextLine)) {
            scanner.close();
            throw new RuntimeException(
                    "Column " + column + ": tab file has more nonempty rows than the stored number of cases ("
                            + numCases + ")! current index: " + tailIndex + ", line: " + nextLine);
        }
        tailIndex++;
    }

    scanner.close();
    return retVector;

}

From source file:edu.umd.cs.buildServer.BuildServer.java

public boolean alreadyRunning() throws Exception {
    int oldPid = getPidFileContents(false);
    if (oldPid < 0)
        return false;
    ProcessBuilder b = new ProcessBuilder(
            new String[] { "/bin/ps", "xww", "-o", "pid,lstart,user,state,pcpu,cputime,args" });
    String user = System.getProperty("user.name");

    Process p = b.start();/*from  ww  w . j  ava2 s  .c o m*/
    try {
        Scanner s = new Scanner(p.getInputStream());
        String header = s.nextLine();
        // log.trace("ps header: " + header);
        while (s.hasNext()) {
            String txt = s.nextLine();
            if (!txt.contains(user))
                continue;

            int pid = Integer.parseInt(txt.substring(0, 5).trim());
            if (pid == oldPid) {
                if (!isQuiet()) {
                    System.out.println("BuildServer is already running");
                    System.out.println(txt);
                }
                return true;
            }
        }
        s.close();
    } finally {
        p.destroy();
    }
    long pidLastModified = getPidFile().lastModified();
    String msg = "Previous buildserver pid " + oldPid + " died; had started at " + new Date(pidLastModified);

    System.out.println(msg);
    File currentFile = getCurrentFile();
    long currentFileLastModified = currentFile.lastModified();
    if (currentFile.exists() && currentFileLastModified >= pidLastModified) {
        Scanner scanner = new Scanner(currentFile);
        int submissionPK = scanner.nextInt();
        int testSetupPK = scanner.nextInt();
        scanner.nextLine(); // skip EOL
        String kind = scanner.nextLine().trim();
        String load = scanner.nextLine().trim();
        scanner.close();
        reportBuildServerDeath(submissionPK, testSetupPK, currentFileLastModified, kind, load);
    }
    currentFile.delete();
    getPidFile().delete();
    System.out.println("Deleting old pid file");
    return false;

}

From source file:eu.cassandra.training.entities.Installation.java

/**
 * This is the parser for the measurement file. It parses through the file and
 * creates the arrays of the active and reactive power consumptions.
 *//*from w  w  w.j a  va2  s .c o m*/
public void parseMeasurementsFile() throws IOException {

    ArrayList<Double> temp = new ArrayList<Double>();
    ArrayList<Double> temp2 = new ArrayList<Double>();

    String extension = measurementsFile.substring(measurementsFile.length() - 3, measurementsFile.length());

    switch (extension) {

    case "csv":

        boolean startFlag = true;

        File file = new File(measurementsFile);
        Scanner scanner = new Scanner(file);

        int counter = 0;

        while (scanner.hasNext()) {

            String line = scanner.nextLine();
            // System.out.println(line);

            if (startFlag) {
                if (line.split(",")[0].equalsIgnoreCase("1")) {

                    startDate = new DateTime(2012, 01, 01, 00, 00);

                } else {

                    int year = Integer.parseInt(line.split(",")[0].substring(0, 4));
                    int month = Integer.parseInt(line.split(",")[0].substring(4, 6));
                    int day = Integer.parseInt(line.split(",")[0].substring(6, 8));
                    int hour = 0;
                    int minute = 0;

                    startDate = new DateTime(year, month, day, hour, minute);

                }

                // System.out.println(startDate.toString());
                startFlag = false;
            }

            temp.add(Double.parseDouble(line.split(",")[1]));

            if (!activeOnly)
                temp2.add(Double.parseDouble(line.split(",")[2]));

            counter++;
        }

        endDate = startDate.plusMinutes(counter);

        // System.out.println(endDate.toString());

        scanner.close();
        break;

    case "xls":

        HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(measurementsFile));

        // Get the first sheet.
        HSSFSheet sheet = workbook.getSheetAt(0);
        for (int i = 0; i < sheet.getLastRowNum(); i++) {

            // Set value of the first cell.
            HSSFRow row = sheet.getRow(i + 1);
            temp.add(row.getCell(1).getNumericCellValue());
            if (!activeOnly)
                temp2.add(row.getCell(2).getNumericCellValue());
        }

        break;

    }

    activePower = new double[temp.size()];

    for (int i = 0; i < temp.size(); i++)
        activePower[i] = temp.get(i);

    if (!activeOnly) {
        reactivePower = new double[temp2.size()];
        for (int i = 0; i < temp2.size(); i++)
            reactivePower[i] = temp2.get(i);
    }

}

From source file:de.evaluationtool.gui.EvaluationFrame.java

public String[][] loadNT(File f) throws FileNotFoundException {
    List<String[]> rows = new LinkedList<String[]>();
    Scanner in = new Scanner(f);
    while (in.hasNextLine()) {
        String line = in.nextLine();
        String[] tokens = line.split("\\s");
        // remove <> signs
        String entity1 = tokens[0].substring(1, tokens[0].length() - 1);
        setProperty(tokens[1]);//from w ww.java  2  s .  c o m
        String entity2 = tokens[2].substring(1, tokens[2].length() - 1);
        String[] row = new String[] { entity1, getProperty(), entity2 };
        rows.add(row);
    }
    in.close();
    return rows.toArray(new String[0][]);
}

From source file:com.wandrell.example.swss.client.console.ConsoleClient.java

/**
 * Runs the main application loop.//  ww w  .ja  va 2s  .  co m
 * <p>
 * This is what keeps the client running and living. It can be stopped by
 * the user through a specific console command.
 *
 * @param output
 *            output where all the information will be printed
 * @param clients
 *            an {@code EntityClient} instance for each security method
 * @param uris
 *            an endpoint URI for each security method
 */
private static final void runMainLoop(final PrintStream output, final Map<Security, EntityClient> clients,
        final Map<Security, String> uris) {
    final Scanner scanner; // Scanner for reading the input
    Security security; // Selected security method
    EntityClient client; // Client for the selected security
    String uri; // Endpoint for the selected security
    String command; // Current user command

    scanner = new Scanner(System.in, "UTF-8");
    // The main loop
    // Stops when the 'exit' command is received
    do {
        // Prints options
        output.println();
        printClientOptions(output);
        output.println();

        // Reads command
        output.print("Pick an option: ");
        command = scanner.next();
        output.println();

        // Loads security from the command
        switch (command) {
        case "1":
            security = Security.UNSECURE;
            break;
        case "2":
            security = Security.PASSWORD_PLAIN_XWSS;
            break;
        case "3":
            security = Security.PASSWORD_PLAIN_WSS4J;
            break;
        case "4":
            security = Security.PASSWORD_DIGEST_XWSS;
            break;
        case "5":
            security = Security.PASSWORD_DIGEST_WSS4J;
            break;
        case "6":
            security = Security.SIGNATURE_XWSS;
            break;
        case "7":
            security = Security.SIGNATURE_WSS4J;
            break;
        case "8":
            security = Security.ENCRYPTION_XWSS;
            break;
        case "9":
            security = Security.ENCRYPTION_WSS4J;
            break;
        default:
            security = null;
            break;
        }

        // Checks if it was a valid option
        if (security != null) {
            // Valid option
            // The client and URI are acquired
            client = clients.get(security);
            uri = uris.get(security);

            // The endpoint is queried
            printQueryHeader(uri, security, output);
            callEndpoint(client, uri, output, scanner);
        }
    } while (!"exit".equalsIgnoreCase(command));

    scanner.close();
}

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

/**
 * Readhtmlfile fail.// w  w w. ja v a2  s. c  o m
 * 
 * @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;
}