Example usage for java.util Scanner nextLine

List of usage examples for java.util Scanner nextLine

Introduction

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

Prototype

public String nextLine() 

Source Link

Document

Advances this scanner past the current line and returns the input that was skipped.

Usage

From source file:GUI.MyCustomFilter.java

private void OpenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OpenActionPerformed
    if (projectSelected == 1) {
        JFileChooser chooser = new JFileChooser();
        int chooserValue = chooser.showOpenDialog(this);
        if (chooserValue == JFileChooser.APPROVE_OPTION) {
            String path = chooser.getSelectedFile().getAbsolutePath();
            String ext = FilenameUtils.getExtension(path);

            if (ext.equalsIgnoreCase("cpp")) {
                try {
                    fileSelected = 1;/*from  w w w  .j  a  v  a  2s  . co  m*/
                    Scanner fin = new Scanner(chooser.getSelectedFile());
                    String buffer = "";
                    while (fin.hasNext()) {
                        buffer += fin.nextLine() + "\n";
                    }
                    textarea.setText(buffer);
                    miniFile = path;
                    jTextPane2.setText(path);
                    //startButton.setVisible(true);
                } catch (FileNotFoundException ex) {
                    //Logger.getLogger(TextEditorFrame.class.getName()).log(Level.SEVERE, null, ex);   
                }

            } else {
                JOptionPane.showMessageDialog(this, "Please input .cpp or .c extension file",
                        "File Inaccessable", JOptionPane.ERROR_MESSAGE);
            }

        }
    } else {
        JOptionPane.showMessageDialog(this, "Select New Project first", "Error", JOptionPane.ERROR_MESSAGE);
    }
}

From source file:GUI.MyCustomFilter.java

private void startButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startButtonActionPerformed
    if (projectSelected == 1) {
        JFileChooser chooser = new JFileChooser();
        int chooserValue = chooser.showOpenDialog(this);
        if (chooserValue == JFileChooser.APPROVE_OPTION) {
            String path = chooser.getSelectedFile().getAbsolutePath();
            String ext = FilenameUtils.getExtension(path);

            if (ext.equalsIgnoreCase("cpp")) {
                try {
                    fileSelected = 1;//from  w w w  .  j  a v a 2  s.co m
                    Scanner fin = new Scanner(chooser.getSelectedFile());
                    String buffer = "";
                    while (fin.hasNext()) {
                        buffer += fin.nextLine() + "\n";
                    }
                    textarea.setText(buffer);
                    miniFile = path;
                    jTextPane2.setText(path);
                    //startButton.setVisible(true);
                } catch (FileNotFoundException ex) {
                    //Logger.getLogger(TextEditorFrame.class.getName()).log(Level.SEVERE, null, ex);   
                }

            } else {
                JOptionPane.showMessageDialog(this, "Please input .cpp or .c extension file",
                        "File Inaccessable", JOptionPane.ERROR_MESSAGE);
            }
        }
    } else {
        JOptionPane.showMessageDialog(this, "Select New Project first", "Error", JOptionPane.ERROR_MESSAGE);
    }

}

From source file:io.stallion.users.UserAdder.java

public void execute(CommandOptionsBase options, String action) throws Exception {

    Log.info("Settings: siteName {0} email password {1}", Settings.instance().getSiteName(),
            Settings.instance().getEmail().getPassword());

    Scanner scanner = new Scanner(System.in);
    Console console = System.console();

    if (empty(action)) {
        //System.out.print("Create new user or edit existing? (new/edit): ");

        //String newEdit = scanner.next();

        System.out.print("Create new user or edit existing? (new/edit): ");
        //String newEdit = console.readLine("Create new user or edit existing? (new/edit): ");
        action = scanner.nextLine();
    }// w  w  w. j  a  va2  s . com
    User user = null;
    if ("new".equals(action)) {
        user = new User();
        user.setPredefined(true);
    } else if ("edit".equals(action)) {
        System.out.print("Enter the email, username, or ID of the user you wish to edit:");
        String idMaybe = scanner.next();
        if (StringUtils.isNumeric(idMaybe)) {
            user = (User) UserController.instance().forId(Long.parseLong(idMaybe));
        }
        if (user == null) {
            user = (User) UserController.instance().forUniqueKey("email", idMaybe);
        }
        if (user == null) {
            user = (User) UserController.instance().forUniqueKey("username", idMaybe);
        }
        if (user == null) {
            System.out.print("Could not find user for key: " + idMaybe);
            System.exit(1);
        }
    } else {
        System.out.print("Invalid choice. Choose either 'new' or 'edit'");
        System.exit(1);
    }

    System.out.print("User's given name: ");
    String givenName = scanner.nextLine();
    if (!empty(givenName)) {
        user.setGivenName(givenName);
    }

    System.out.print("User's family name: ");
    String familyName = scanner.nextLine();
    if (!empty(familyName)) {
        user.setFamilyName(familyName);
        user.setDisplayName(user.getGivenName() + " " + user.getFamilyName());
    }

    System.out.print("User's email: ");
    String email = scanner.nextLine();
    if (!empty(email)) {
        user.setEmail(email);
        user.setUsername(user.getEmail());
    }

    System.out.print("Enter password: ");
    String password = "";
    if (console != null) {
        password = new String(console.readPassword());
    } else {
        password = new String(scanner.nextLine());
    }
    //System.out.printf("password: \"%s\"\n", password);
    if (empty(password) && empty(user.getBcryptedPassword())) {
        throw new UsageException("You must set a password!");
    } else if (!empty(password)) {
        String hashed = BCrypt.hashpw(password, BCrypt.gensalt());
        user.setBcryptedPassword(hashed);
    }

    if (empty(user.getSecret())) {
        user.setSecret(RandomStringUtils.randomAlphanumeric(18));
    }
    if (empty(user.getEncryptionSecret())) {
        user.setEncryptionSecret(RandomStringUtils.randomAlphanumeric(36));
    }

    user.setPredefined(true);
    user.setRole(Role.ADMIN);
    user.setId(Context.dal().getTickets().nextId());
    user.setFilePath(GeneralUtils.slugify(user.getEmail() + "---" + user.getId().toString()) + ".json");
    UserController.instance().save(user);

    System.out.print("User saved with email " + user.getEmail() + " and id " + user.getId());

}

From source file:ml.shifu.shifu.core.processor.InitModelProcessor.java

private Map<Integer, Data> getCountInfoMap(SourceType source, String autoTypePath) throws IOException {
    String outputFilePattern = autoTypePath + Path.SEPARATOR + "part-*";
    if (!ShifuFileUtils.isFileExists(outputFilePattern, source)) {
        throw new RuntimeException("Auto type checking output file not exist.");
    }// w  w w. j  av a  2  s  . c  o  m

    Map<Integer, Data> distinctCountMap = new HashMap<Integer, Data>();
    List<Scanner> scanners = null;
    try {
        // here only works for 1 reducer
        FileStatus[] globStatus = ShifuFileUtils.getFileSystemBySourceType(source)
                .globStatus(new Path(outputFilePattern));
        if (globStatus == null || globStatus.length == 0) {
            throw new RuntimeException("Auto type checking output file not exist.");
        }
        scanners = ShifuFileUtils.getDataScanners(globStatus[0].getPath().toString(), source);
        Scanner scanner = scanners.get(0);
        String str = null;
        while (scanner.hasNext()) {
            str = scanner.nextLine().trim();
            if (str.contains(TAB_STR)) {
                String[] splits1 = str.split(TAB_STR);
                String[] splits2 = splits1[1].split(":", -1);

                distinctCountMap.put(Integer.valueOf(splits1[0]),
                        new Data(Long.valueOf(splits2[0]), Long.valueOf(splits2[1]), Long.valueOf(splits2[2]),
                                Long.valueOf(splits2[3]), splits2[4].split(",")));
            }
        }
        return distinctCountMap;
    } finally {
        if (scanners != null) {
            for (Scanner scanner : scanners) {
                if (scanner != null) {
                    scanner.close();
                }
            }
        }
    }
}

From source file:cz.cuni.amis.planning4j.validation.external.ValValidator.java

@Override
public IValidationResult validate(IPDDLFileDomainProvider domainProvider,
        IPDDLFileProblemProvider problemProvider, List<ActionDescription> plan) {
    File mainExecutable = new File(validatorDirectory,
            getValidatorFolderName() + File.separatorChar + getValidatorExecutableName());
    if (!mainExecutable.exists()) {
        String toolMessage = "Could not find validator executable '" + getValidatorExecutableName()
                + "' in directory " + validatorDirectory.getAbsolutePath();
        throw new ValidationException(toolMessage);
    }//from  ww w  .  jav a  2  s  .c om
    FileWriter planWriter = null;
    Process process = null;
    try {

        /**
         * Write the plan to a temp file
         */
        File planTempFile = File.createTempFile("plan", ".soln");
        planWriter = new FileWriter(planTempFile);
        for (ActionDescription action : plan) {
            planWriter.write(action.getStartTime() + ": (" + action.getName() + " ");
            for (String param : action.getParameters()) {
                planWriter.write(param + " ");
            }
            planWriter.write(") [" + action.getDuration() + "]\n");
        }

        planWriter.close();
        planWriter = null;
        /**
         * Invoke the validator
         */
        ProcessBuilder processBuilder = new ProcessBuilder(mainExecutable.getAbsolutePath(), "-s", //silent mode for simple parsing - only errors are printed to the stdout
                domainProvider.getDomainFile().getAbsolutePath(),
                problemProvider.getProblemFile().getAbsolutePath(), planTempFile.getAbsolutePath());

        logger.info("Starting VAL validator.");
        if (logger.isDebugEnabled()) {
            logger.debug("The command: " + processBuilder.command());
        }
        process = processBuilder.start();

        Scanner outputScanner = new Scanner(process.getInputStream());

        StringBuilder consoleOutputBuilder = new StringBuilder();

        boolean hasNonEmptyLines = false;
        if (logger.isTraceEnabled()) {
            logger.trace("Validator output:");
        }
        while (outputScanner.hasNextLine()) {
            String line = outputScanner.nextLine();
            if (!consoleOutputBuilder.toString().isEmpty()) {
                consoleOutputBuilder.append("\n");
            }
            if (!line.trim().isEmpty()) {
                hasNonEmptyLines = true;
            }
            consoleOutputBuilder.append(line);
            if (logger.isTraceEnabled()) {
                logger.trace(line);
            }
        }
        if (logger.isTraceEnabled()) {
            logger.trace("Validator output end.");
        }

        try {
            //clean the error stream. Otherwise this might prevent the process from being terminated / cleared from the process table
            IOUtils.toString(process.getErrorStream());
        } catch (IOException ex) {
            logger.warn("Could not clear error stream.", ex);
        }

        process.waitFor();
        boolean valid = !hasNonEmptyLines; //validator is run in silent mode, so any output means plan is not valid.
        logger.info("Validation finished. Result is: " + valid);
        return new ValidationResult(valid, consoleOutputBuilder.toString());
    } catch (Exception ex) {
        if (planWriter != null) {
            try {
                planWriter.close();
            } catch (Exception ignored) {
            }
        }
        if (process != null) {
            process.destroy();
            try {
                //clean the streams so that the process does not hang in the process table
                IOUtils.toString(process.getErrorStream());
                IOUtils.toString(process.getInputStream());
            } catch (Exception ignored) {
                logger.warn("Could not clear output/error stream.", ignored);
            }
        }
        throw new ValidationException("Error during validation", ex);
    }
}

From source file:jp.ikedam.jenkins.plugins.extensible_choice_parameter.DatabaseChoiceListProvider.java

/**
 * /*w w w .  j a  v  a2 s .  c  o  m*/
 * @return
 */
private List<String> performDbQuery() {

    Connection conn = null;
    ResultSet resultat = null;
    List<String> resultList = new ArrayList<String>();
    try {
        String driver = getJdbcDriver();
        if (driver == null || StringUtils.isEmpty(driver)) {
            LOGGER.log(Level.WARNING, "Invalid driver");
        }

        Class.forName(driver);

        String user = getDbUsername();
        if (user == null || StringUtils.isEmpty(user)) {
            LOGGER.log(Level.WARNING, "Invalid user");
        }

        String password = getDbPassword();
        if (password == null || StringUtils.isEmpty(password)) {
            LOGGER.log(Level.WARNING, "Invalid password");
        }

        String urlBase = getJdbcUrl();
        if (urlBase == null || StringUtils.isEmpty(urlBase)) {
            LOGGER.log(Level.WARNING, "Invalid JDBC URL");
        }

        String colomndb = getDbColumn();
        if (colomndb == null || StringUtils.isEmpty(colomndb)) {
            LOGGER.log(Level.WARNING, "Invalid column");
        }

        String namedb = getDbName();
        if (namedb == null || StringUtils.isEmpty(namedb)) {
            LOGGER.log(Level.WARNING, "Invalid DB name");
        }

        String tabledb = getDbTable();
        if (tabledb == null || StringUtils.isEmpty(tabledb)) {
            LOGGER.log(Level.WARNING, "table database invalid");
        }

        conn = DriverManager.getConnection(urlBase, user, password);

        // By default, a SELECT * is performed
        String selectQuery = "select " + colomndb + " from " + namedb + "." + tabledb;

        // Use plain old JDBC to build and execute the query against the configured db
        Statement statement = conn.createStatement();
        boolean result = statement.execute(selectQuery);
        if (result) {
            resultat = statement.executeQuery(selectQuery);
            while (resultat.next()) {
                resultList.add(resultat.getString(1));
            }
        } else {
            LOGGER.log(Level.WARNING, "No result found with the query: " + selectQuery);
        }
    } catch (SQLException se) {
        LOGGER.log(Level.SEVERE, "Unable to access the database: " + dbName + "." + se);
    } catch (ClassNotFoundException e) {
        LOGGER.log(Level.SEVERE, "The driver " + jdbcDriver + " cannot be found in the classpath.");
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, "Unable to access the database: " + dbName + "." + e);
    } finally {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException se) {
            LOGGER.log(Level.SEVERE, "Fermeture de connection impossible, SQLException : " + se);
        }
    }

    // If no results are returned, read values from the fallback file if configured
    if (resultList.isEmpty()) {

        Scanner scanner = null;
        try {
            scanner = new Scanner(new FileInputStream(getFallbackFilePath()));
            while (scanner.hasNextLine()) {
                String env = scanner.nextLine().trim();
                if (StringUtils.isNotBlank(env)) {
                    resultList.add(env);
                }
            }
        } catch (FileNotFoundException e) {
            LOGGER.log(Level.WARNING, "Unable to read the fallback file: " + e);
        } finally {
            if (scanner != null) {
                scanner.close();
            }
        }
    }

    // Perform alphabetical sorting on results
    Collections.sort(resultList);

    return resultList;
}

From source file:com.l2jfree.gameserver.datatables.ExtractableItemsData.java

private ExtractableItemsData() {
    _items.clear();// ww w.  jav a 2  s  . co m

    Scanner s;

    try {
        s = new Scanner(new File(Config.DATAPACK_ROOT, "data/extractable_items.csv"));
    } catch (Exception e) {
        _log.warn("Extractable items data: Can not find '" + Config.DATAPACK_ROOT
                + "data/extractable_items.csv'");
        return;
    }

    int lineCount = 0;

    while (s.hasNextLine()) {
        lineCount++;

        String line = s.nextLine().trim();

        if (line.startsWith("#"))
            continue;
        else if (line.isEmpty())
            continue;

        String[] lineSplit = line.split(";");
        boolean ok = true;
        int itemID = 0;

        try {
            itemID = Integer.parseInt(lineSplit[0]);
        } catch (Exception e) {
            _log.warn("Extractable items data: Error in line " + lineCount
                    + " -> invalid item id or wrong seperator after item id!");
            _log.warn("      " + line);
            ok = false;
        }

        if (!ok)
            continue;

        FastList<L2ExtractableProductItem> product_temp = new FastList<L2ExtractableProductItem>();

        for (int i = 0; i < lineSplit.length - 1; i++) {
            ok = true;

            String[] lineSplit2 = lineSplit[i + 1].split(",");

            if (lineSplit2.length < 3) {
                _log.warn("Extractable items data: Error in line " + lineCount + " -> wrong seperator!");
                _log.warn("      " + line);
                ok = false;
            }

            if (!ok)
                continue;

            int[] production = null;
            int[] amount = null;
            int chance = 0;

            try {
                int k = 0;
                production = new int[(lineSplit2.length - 1) / 2];
                amount = new int[(lineSplit2.length - 1) / 2];
                for (int j = 0; j < lineSplit2.length - 1; j++) {
                    production[k] = Integer.parseInt(lineSplit2[j]);
                    amount[k] = Integer.parseInt(lineSplit2[j += 1]);
                    k++;
                }

                chance = Integer.parseInt(lineSplit2[lineSplit2.length - 1]);
            } catch (Exception e) {
                _log.warn("Extractable items data: Error in line " + lineCount
                        + " -> incomplete/invalid production data or wrong seperator!");
                _log.warn("      " + line);
                ok = false;
            }

            if (!ok)
                continue;

            L2ExtractableProductItem product = new L2ExtractableProductItem(production, amount, chance);
            product_temp.add(product);
        }

        int fullChances = 0;

        for (L2ExtractableProductItem Pi : product_temp)
            fullChances += Pi.getChance();

        if (fullChances > 100) {
            _log.warn("Extractable items data: Error in line " + lineCount
                    + " -> all chances together are more then 100!");
            _log.warn("      " + line);
            continue;
        }
        L2ExtractableItem product = new L2ExtractableItem(itemID, product_temp);
        _items.put(itemID, product);
    }

    s.close();
    _log.info("Extractable items data: Loaded " + _items.size() + " extractable items!");
}

From source file:com.joliciel.talismane.other.standoff.StandoffReader.java

public StandoffReader(Scanner scanner) {
    PosTagSet posTagSet = TalismaneSession.getPosTagSet();

    Map<Integer, StandoffToken> sortedTokens = new TreeMap<Integer, StandoffReader.StandoffToken>();
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        if (line.startsWith("T")) {

            String[] parts = line.split("[\\t]");
            String id = parts[0];
            String[] posTagParts = parts[1].split(" ");
            String posTagCode = posTagParts[0].replace('_', '+');
            int startPos = Integer.parseInt(posTagParts[1]);
            String text = parts[2];

            PosTag posTag = null;/*from  w w  w .  j  a  v  a  2s  . c  om*/
            if (posTagCode.equalsIgnoreCase(PosTag.ROOT_POS_TAG_CODE)) {
                posTag = PosTag.ROOT_POS_TAG;
            } else {
                try {
                    posTag = posTagSet.getPosTag(posTagCode);
                } catch (UnknownPosTagException upte) {
                    throw new TalismaneException("Unknown posTag on line " + lineNumber + ": " + posTagCode);
                }
            }

            StandoffToken token = new StandoffToken();
            token.posTag = posTag;
            token.text = text;
            token.id = id;

            sortedTokens.put(startPos, token);
            tokenMap.put(id, token);

        } else if (line.startsWith("R")) {

            String[] parts = line.split("[\\t :]");
            String id = parts[0];
            String label = parts[1];
            String headId = parts[3];
            String dependentId = parts[5];
            StandoffRelation relation = new StandoffRelation();
            relation.fromToken = headId;
            relation.toToken = dependentId;
            relation.label = label;
            idRelationMap.put(id, relation);
            relationMap.put(dependentId, relation);
        } else if (line.startsWith("#")) {
            String[] parts = line.split("\t");
            String itemId = parts[1].substring("AnnotatorNotes ".length());
            String note = parts[2];
            notes.put(itemId, note);
        }
    }

    for (String itemId : notes.keySet()) {
        String comment = notes.get(itemId);
        if (itemId.startsWith("R")) {
            StandoffRelation relation = idRelationMap.get(itemId);
            relation.comment = comment;
        } else {
            StandoffToken token = tokenMap.get(itemId);
            token.comment = comment;
        }
    }

    List<StandoffToken> currentSentence = null;
    for (StandoffToken token : sortedTokens.values()) {
        if (token.text.equals("ROOT")) {
            if (currentSentence != null)
                sentences.add(currentSentence);
            currentSentence = new ArrayList<StandoffReader.StandoffToken>();
        }
        currentSentence.add(token);
    }
    if (currentSentence != null)
        sentences.add(currentSentence);
}

From source file:com.moorestudio.seniorimageprocessing.SeniorSorter.java

public void getStudentData() throws FileNotFoundException, Exception {
    try {/*  w w w . j  a  va2s  .c om*/
        Scanner scanner = new Scanner(dataFile);

        //get the line count for the GUI
        int lineCount = getLineCount(dataFile);

        //the csv file does not contain headers
        while (scanner.hasNextLine()) {
            //Create the new student map
            String studentId;
            Long timestamp;
            String line = scanner.nextLine();
            //check to make sure there arent just empty rows
            if (!line.replace("\"", "").replace(",", "").isEmpty()) {
                String[] lineInformation = line.replace("\"", "").split(",");
                SimpleDateFormat dateParser = new SimpleDateFormat("M/dd/yy HH:mm:ss");
                studentId = lineInformation[0];
                timestamp = dateParser.parse(lineInformation[3] + " " + lineInformation[2]).getTime();
                timestampData.put(studentId, timestamp);
            }

            //update the GUI
            parent.addProgress((.125 / parent.numThreads) / lineCount);
        }
    } catch (FileNotFoundException e) {
        throw new FileNotFoundException("Data file at: " + dataFile.getAbsolutePath() + " does not exist!");
    } catch (ParseException ex) {
        throw new Exception(
                "The date in the data file at: " + dataFile.getAbsolutePath() + " is not formatted correctly!");
    }
}