Example usage for java.util Scanner Scanner

List of usage examples for java.util Scanner Scanner

Introduction

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

Prototype

public Scanner(ReadableByteChannel source) 

Source Link

Document

Constructs a new Scanner that produces values scanned from the specified channel.

Usage

From source file:io.stallion.utils.Prompter.java

public Prompter(String message) {
    this.scanner = new Scanner(System.in);
    this.message = message;
}

From source file:com.codenjoy.dojo.client.OneCommandSolver.java

@Override
public String get(T board) {
    if (processed) {
        System.exit(0);// ww w.  j a v  a2s. co m
        return StringUtils.EMPTY;
    } else {
        processed = true;
    }
    System.out.printf("Are you sure you want to run the command '%s' (y/n)?\n", command);
    String answer = new Scanner(System.in).next();
    if (answer.equals("y")) {
        System.out.printf("Sending '%s' to the server\n", command);
        return command;
    } else {
        System.exit(0);
        return StringUtils.EMPTY;
    }
}

From source file:com.dickthedeployer.dick.web.service.CommandService.java

public String invoke(Path workingDir, String... command) throws RuntimeException {
    try {/*  w w  w. ja  v  a  2 s  .c  o  m*/
        log.info("Executing command {} in path {}", Arrays.toString(command), workingDir.toString());
        StringBuilder text = new StringBuilder();
        ProcessBuilder builder = new ProcessBuilder(command);
        builder.directory(workingDir.toFile());
        builder.redirectErrorStream(true);

        Process process = builder.start();

        try (Scanner s = new Scanner(process.getInputStream())) {
            while (s.hasNextLine()) {
                text.append(s.nextLine());
            }
            int result = process.waitFor();
            log.info("Process exited with result {} and output {}", result, text);

            if (result != 0) {
                throw new CommandExecutionException();
            }
            return text.toString();
        }
    } catch (IOException | InterruptedException ex) {
        throw new CommandExecutionException(ex);
    }
}

From source file:example.springdata.rest.stores.StoreInitializer.java

/**
 * Reads a file {@code starbucks.csv} from the class path and parses it into {@link Store} instances about to
 * persisted.// ww w .  j  a  va  2  s .co m
 * 
 * @return
 * @throws Exception
 */
public static List<Store> readStores() throws Exception {

    ClassPathResource resource = new ClassPathResource("starbucks.csv");
    Scanner scanner = new Scanner(resource.getInputStream());
    String line = scanner.nextLine();
    scanner.close();

    FlatFileItemReader<Store> itemReader = new FlatFileItemReader<Store>();
    itemReader.setResource(resource);

    // DelimitedLineTokenizer defaults to comma as its delimiter
    DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer();
    tokenizer.setNames(line.split(","));
    tokenizer.setStrict(false);

    DefaultLineMapper<Store> lineMapper = new DefaultLineMapper<Store>();
    lineMapper.setFieldSetMapper(fields -> {

        Point location = new Point(fields.readDouble("Longitude"), fields.readDouble("Latitude"));
        Address address = new Address(fields.readString("Street Address"), fields.readString("City"),
                fields.readString("Zip"), location);

        return new Store(fields.readString("Name"), address);
    });

    lineMapper.setLineTokenizer(tokenizer);
    itemReader.setLineMapper(lineMapper);
    itemReader.setRecordSeparatorPolicy(new DefaultRecordSeparatorPolicy());
    itemReader.setLinesToSkip(1);
    itemReader.open(new ExecutionContext());

    List<Store> stores = new ArrayList<>();
    Store store = null;

    do {

        store = itemReader.read();

        if (store != null) {
            stores.add(store);
        }

    } while (store != null);

    return stores;
}

From source file:com.switchfly.inputvalidation.sanitizer.UrlStripHtmlSanitizer.java

public static List<NameValuePair> parse(String queryString) {
    List<NameValuePair> result = Collections.emptyList();
    if (queryString != null && queryString.length() > 0) {
        result = new ArrayList<NameValuePair>();
        parse(result, new Scanner(queryString));
    }//from w w  w  .j av a  2s  .  co  m
    return result;
}

From source file:com.example.op.tutorial678.MyItemReader.java

public List<Person> read(InputStream inputStream) throws JSONException {
    List<Person> items = new ArrayList<Person>();
    String json = new Scanner(inputStream).useDelimiter(REGEX_INPUT_BOUNDARY_BEGINNING).next();
    JSONArray array = new JSONArray(json);

    listAvatars.add(R.drawable.avatar);//w  ww  .j ava  2s.c om
    listAvatars.add(R.drawable.avatar2);
    listAvatars.add(R.drawable.avatar3);
    listAvatars.add(R.drawable.bighero6);
    listAvatars.add(R.drawable.ff8);
    listAvatars.add(R.drawable.avatar_film);

    for (int i = 0; i < array.length(); i++) {
        String name = null;
        String email = null;
        String phoneNumber = null;

        JSONObject object = array.getJSONObject(i);
        double lat = object.getDouble("lat");
        double lng = object.getDouble("lng");
        //pictureResource =
        if (!object.isNull("name")) {
            name = object.getString("name");
        }
        if (!object.isNull("email")) {
            email = object.getString("email");
        }

        if (!object.isNull("phoneNumber")) {
            phoneNumber = object.getString("phoneNumber");
        }

        int idx = random.nextInt(listAvatars.size());
        items.add(new Person(new LatLng(lat, lng), name, email, phoneNumber, listAvatars.get(idx)));
    }
    return items;
}

From source file:com.project.atm.core.App.java

static void loadDistanceMatrix() throws FileNotFoundException {

    //change the path file to correct location !         
    scDistance = new Scanner(new FileReader("/home/andry/Documents/atm/atmDistance.txt"));

    // load data from file
    int i = 1;//from   w w w.  j  ava2  s  .  c  o  m
    int j = 1;
    int total = locationList.size();

    distance = new double[total][total];

    logger.info("loading distance matrix tab file.................");

    StopWatch stopWatch = new StopWatch("Travel distance calculation");
    stopWatch.start("load distance matrix file");

    // convert matrix data to array
    while (scDistance.hasNextLine()) {

        //logger.info("i => "+ i +", j => "+j);
        distance[i - 1][j - 1] = scDistance.nextDouble();
        if ((j % total) == 0) {
            i++;
            j = 0;
            if (i == total + 1)
                break;
        }
        j++;
    }
    stopWatch.stop();
    logger.info(stopWatch.prettyPrint());
    logger.info(stopWatch.prettyPrint());
}

From source file:com.test.sharksharding.use.resource.RedisResourceTest.java

public @Test void testInsert() {
    while (true) {
        System.out.println("input-->");
        Scanner scan = new Scanner(System.in);
        final String uid = scan.nextLine();
        JdbcTemplate jdbcTemlate = GetJdbcTemplate.getJdbcTemplate();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("uid", Long.valueOf(uid));
        params.put("userName", "gaoxianglong");
        final String sql = sqlTemplate.getSql("setUserInfo", params);
        jdbcTemlate.update(sql);/*  w w w  .j a  v  a  2 s  .c o m*/
    }
}

From source file:DataSci.main.JsonRequestResponseController.java

/**
 * Read the API key and API URL of Azure ML request response REST API
 * //from w  ww.  j  av  a2 s  .  c  o  m
 * @param filename fully qualified file name that contains API key and API URL
 */
public void readApiInfo(String filename) {

    try {
        File apiFile = new File(filename);
        Scanner sc = new Scanner(apiFile);

        apiurl = sc.nextLine();
        apikey = sc.nextLine();

        sc.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:es.upct.girtel.net2plan.plugins.activepce.pce.PCEMainServer.java

@Override
public void executeFromCommandLine(String[] args) throws ParseException {
    System.out.println("PCE MAIN SERVER");
    System.out.println("==============================");

    Scanner scanner = new Scanner(System.in);

    System.out.println("Starting PCEP & BGP-LS servers...");

    PCEPServer serverPCEP;// w ww  . j  a va  2s. co m
    BGPServer serverBGP;

    try {
        serverPCEP = new PCEPServer();
        serverBGP = new BGPServer();
    } catch (Net2PlanException e) {
        throw (e);
    } catch (Throwable e) {
        throw new RuntimeException(e);
    }

    /* Create and start PCE Server */
    serverPCEP.acceptConnections();

    /* Create and start BGP server */
    serverBGP.acceptConnections();

    System.out.println("PCE successfully started");

    while (true) {
        String option;

        System.out.println("============================");
        System.out.println("|    MULTILAYER AS-PCE     |");
        System.out.println("============================");
        System.out.println("| Options:                 |");
        System.out.println("| 1. View current sessions |");
        System.out.println("| 2. Print TEDB and LSPDB  |");
        System.out.println("| 3. Exit                  |");
        System.out.println("============================");
        System.out.println("");
        System.out.print("Choose an option (1-3): ");

        option = scanner.nextLine();

        Set<InetAddress> activeSessions = PCEMasterController.getInstance().getActiveSessions();
        switch (option) {
        case "1":
            if (activeSessions.isEmpty())
                System.out.println("No active session");
            else
                System.out.println("Active sessions: " + activeSessions);
            break;

        case "2":
            switch (activeSessions.size()) {
            case 0:
                System.out.println("No active session");
                break;

            case 1:
                System.out.println("Network state: " + PCEMasterController.getInstance()
                        .getPCEEntity(activeSessions.iterator().next()).getNetworkState());
                break;

            default:
                System.out.println(">> Active sessions: " + activeSessions);
                System.out.print(">> Choose a session: ");
                try {
                    String session = scanner.nextLine();
                    IPCEEntity pceEntity = PCEMasterController.getInstance()
                            .getPCEEntity(InetAddress.getByName(session));
                    System.out.println("Network state: " + pceEntity.getNetworkState());
                } catch (Throwable e) {
                    e.printStackTrace();
                }
                break;
            }
            break;

        case "3":
            System.exit(0);

        default:
            System.out.println("Wrong option");
        }
    }
}