List of usage examples for java.util Scanner Scanner
public Scanner(ReadableByteChannel source)
From source file:com.github.horrorho.inflatabledonkey.Main.java
/** * @param args the command line arguments * @throws IOException/*from ww w . jav a 2 s . c om*/ */ public static void main(String[] args) throws IOException { try { if (!PropertyLoader.instance().test(args)) { return; } } catch (IllegalArgumentException ex) { System.out.println("Argument error: " + ex.getMessage()); System.out.println("Try '" + Property.APP_NAME.value() + " --help' for more information."); System.exit(-1); } // SystemDefault HttpClient. // TODO concurrent CloseableHttpClient httpClient = HttpClients.custom().setUserAgent("CloudKit/479 (13A404)") .useSystemProperties().build(); // Auth // TODO rework when we have UncheckedIOException for Authenticator Auth auth = Property.AUTHENTICATION_TOKEN.value().map(Auth::new).orElse(null); if (auth == null) { auth = Authenticator.authenticate(httpClient, Property.AUTHENTICATION_APPLEID.value().get(), Property.AUTHENTICATION_PASSWORD.value().get()); } logger.debug("-- main() - auth: {}", auth); logger.info("-- main() - dsPrsID:mmeAuthToken: {}:{}", auth.dsPrsID(), auth.mmeAuthToken()); if (Property.ARGS_TOKEN.booleanValue().orElse(false)) { System.out.println("DsPrsID:mmeAuthToken " + auth.dsPrsID() + ":" + auth.mmeAuthToken()); return; } logger.info("-- main() - Apple ID: {}", Property.AUTHENTICATION_APPLEID.value()); logger.info("-- main() - password: {}", Property.AUTHENTICATION_PASSWORD.value()); logger.info("-- main() - token: {}", Property.AUTHENTICATION_TOKEN.value()); // Account Account account = Accounts.account(httpClient, auth); // Backup Backup backup = Backup.create(httpClient, account); // BackupAccount BackupAccount backupAccount = backup.backupAccount(httpClient); logger.debug("-- main() - backup account: {}", backupAccount); // Devices List<Device> devices = backup.devices(httpClient, backupAccount.devices()); logger.debug("-- main() - device count: {}", devices.size()); // Snapshots List<SnapshotID> snapshotIDs = devices.stream().map(Device::snapshots).flatMap(Collection::stream) .collect(Collectors.toList()); logger.info("-- main() - total snapshot count: {}", snapshotIDs.size()); Map<String, Snapshot> snapshots = backup.snapshot(httpClient, snapshotIDs).stream().collect( Collectors.toMap(s -> s.record().getRecordIdentifier().getValue().getName(), Function.identity())); boolean repeat = false; do { for (int i = 0; i < devices.size(); i++) { Device device = devices.get(i); List<SnapshotID> deviceSnapshotIDs = device.snapshots(); System.out.println(i + " " + device.info()); for (int j = 0; j < deviceSnapshotIDs.size(); j++) { SnapshotID sid = deviceSnapshotIDs.get(j); System.out.println("\t" + j + snapshots.get(sid.id()).info() + " " + sid.timestamp()); } } if (Property.PRINT_SNAPSHOTS.booleanValue().orElse(false)) { return; } // Selection Scanner input = new Scanner(System.in); int deviceIndex; int snapshotIndex = Property.SELECT_SNAPSHOT_INDEX.intValue().get(); if (devices.size() > 1) { System.out.printf("Select a device [0 - %d]: ", devices.size() - 1); deviceIndex = input.nextInt(); } else deviceIndex = Property.SELECT_DEVICE_INDEX.intValue().get(); if (deviceIndex >= devices.size() || deviceIndex < 0) { System.out.println("No such device: " + deviceIndex); System.exit(-1); } Device device = devices.get(deviceIndex); System.out.println("Selected device: " + deviceIndex + ", " + device.info()); if (device.snapshots().size() > 1) { System.out.printf("Select a snapshot [0 - %d]: ", device.snapshots().size() - 1); snapshotIndex = input.nextInt(); } else snapshotIndex = Property.SELECT_SNAPSHOT_INDEX.intValue().get(); if (snapshotIndex >= devices.get(deviceIndex).snapshots().size() || snapshotIndex < 0) { System.out.println("No such snapshot for selected device: " + snapshotIndex); System.exit(-1); } logger.info("-- main() - arg device index: {}", deviceIndex); logger.info("-- main() - arg snapshot index: {}", snapshotIndex); String selected = devices.get(deviceIndex).snapshots().get(snapshotIndex).id(); Snapshot snapshot = snapshots.get(selected); System.out.println("Selected snapshot: " + snapshotIndex + ", " + snapshot.info()); // Asset list. List<Assets> assetsList = backup.assetsList(httpClient, snapshot); logger.info("-- main() - assets count: {}", assetsList.size()); // Domains filter --domain option String chosenDomain = Property.FILTER_DOMAIN.value().orElse("").toLowerCase(Locale.US); logger.info("-- main() - arg domain substring filter: {}", Property.FILTER_DOMAIN.value()); // Output domains --domains option if (Property.PRINT_DOMAIN_LIST.booleanValue().orElse(false)) { System.out.println("Domains / file count:"); assetsList.stream().filter(a -> a.domain().isPresent()) .map(a -> a.domain().get() + " / " + a.files().size()).sorted() .forEach(System.out::println); System.out.print("Type a domain ('null' to exit): "); chosenDomain = input.next().toLowerCase(Locale.US); if (chosenDomain.equals("null")) return; // TODO check Assets without domain information. } String domainSubstring = chosenDomain; Predicate<Optional<String>> domainFilter = domain -> domain.map(d -> d.toLowerCase(Locale.US)) .map(d -> d.contains(domainSubstring)).orElse(false); List<String> files = Assets.files(assetsList, domainFilter); logger.info("-- main() - domain filtered file count: {}", files.size()); // Output folders. Path outputFolder = Paths.get(Property.OUTPUT_FOLDER.value().orElse("output")); Path assetOutputFolder = outputFolder.resolve("assets"); // TODO assets value injection Path chunkOutputFolder = outputFolder.resolve("chunks"); // TODO chunks value injection logger.info("-- main() - output folder chunks: {}", chunkOutputFolder); logger.info("-- main() - output folder assets: {}", assetOutputFolder); // Download tools. AuthorizeAssets authorizeAssets = AuthorizeAssets.backupd(); DiskChunkStore chunkStore = new DiskChunkStore(chunkOutputFolder); StandardChunkEngine chunkEngine = new StandardChunkEngine(chunkStore); AssetDownloader assetDownloader = new AssetDownloader(chunkEngine); KeyBagManager keyBagManager = backup.newKeyBagManager(); // Mystery Moo. Moo moo = new Moo(authorizeAssets, assetDownloader, keyBagManager); // Filename extension filter. String filenameExtension = Property.FILTER_EXTENSION.value().orElse("").toLowerCase(Locale.US); logger.info("-- main() - arg filename extension filter: {}", Property.FILTER_EXTENSION.value()); Predicate<Asset> assetFilter = asset -> asset.relativePath().map(d -> d.toLowerCase(Locale.US)) .map(d -> d.endsWith(filenameExtension)).orElse(false); // Batch process files in groups of 100. // TODO group files into batches based on file size. List<List<String>> batches = ListUtils.partition(files, 100); for (List<String> batch : batches) { List<Asset> assets = backup.assets(httpClient, batch).stream().filter(assetFilter::test) .collect(Collectors.toList()); logger.info("-- main() - filtered asset count: {}", assets.size()); moo.download(httpClient, assets, assetOutputFolder); } System.out.print("Download other snapshot (Y/N)? "); repeat = input.next().toLowerCase(Locale.US).charAt(0) == 'y'; } while (repeat == true); }
From source file:Graph_with_jframe_and_arduino.java
public static void main(String[] args) { // create and configure the window JFrame window = new JFrame(); window.setTitle("Sensor Graph GUI"); window.setSize(600, 400);/*from w ww . j a va 2s .com*/ window.setLayout(new BorderLayout()); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // create a drop-down box and connect button, then place them at the top of the window JComboBox<String> portList_combobox = new JComboBox<String>(); Dimension d = new Dimension(300, 100); portList_combobox.setSize(d); JButton connectButton = new JButton("Connect"); JPanel topPanel = new JPanel(); topPanel.add(portList_combobox); topPanel.add(connectButton); window.add(topPanel, BorderLayout.NORTH); //pause button JButton Pause_btn = new JButton("Start"); // populate the drop-down box SerialPort[] portNames; portNames = SerialPort.getCommPorts(); //check for new port available Thread thread_port = new Thread() { @Override public void run() { while (true) { SerialPort[] sp = SerialPort.getCommPorts(); if (sp.length > 0) { for (SerialPort sp_name : sp) { int l = portList_combobox.getItemCount(), i; for (i = 0; i < l; i++) { //check port name already exist or not if (sp_name.getSystemPortName().equalsIgnoreCase(portList_combobox.getItemAt(i))) { break; } } if (i == l) { portList_combobox.addItem(sp_name.getSystemPortName()); } } } else { portList_combobox.removeAllItems(); } portList_combobox.repaint(); } } }; thread_port.start(); for (SerialPort sp_name : portNames) portList_combobox.addItem(sp_name.getSystemPortName()); //for(int i = 0; i < portNames.length; i++) // portList.addItem(portNames[i].getSystemPortName()); // create the line graph XYSeries series = new XYSeries("line 1"); XYSeries series2 = new XYSeries("line 2"); XYSeries series3 = new XYSeries("line 3"); XYSeries series4 = new XYSeries("line 4"); for (int i = 0; i < 100; i++) { series.add(x, 0); series2.add(x, 0); series3.add(x, 0); series4.add(x, 10); x++; } XYSeriesCollection dataset = new XYSeriesCollection(); dataset.addSeries(series); dataset.addSeries(series2); XYSeriesCollection dataset2 = new XYSeriesCollection(); dataset2.addSeries(series3); dataset2.addSeries(series4); //create jfree chart JFreeChart chart = ChartFactory.createXYLineChart("Sensor Readings", "Time (seconds)", "Arduino Reading", dataset); JFreeChart chart2 = ChartFactory.createXYLineChart("Sensor Readings", "Time (seconds)", "Arduino Reading 2", dataset2); //color render for chart 1 XYLineAndShapeRenderer r1 = new XYLineAndShapeRenderer(); r1.setSeriesPaint(0, Color.RED); r1.setSeriesPaint(1, Color.GREEN); r1.setSeriesShapesVisible(0, false); r1.setSeriesShapesVisible(1, false); XYPlot plot = chart.getXYPlot(); plot.setRenderer(0, r1); plot.setRenderer(1, r1); plot.setBackgroundPaint(Color.WHITE); plot.setDomainGridlinePaint(Color.DARK_GRAY); plot.setRangeGridlinePaint(Color.blue); //color render for chart 2 XYLineAndShapeRenderer r2 = new XYLineAndShapeRenderer(); r2.setSeriesPaint(0, Color.BLUE); r2.setSeriesPaint(1, Color.ORANGE); r2.setSeriesShapesVisible(0, false); r2.setSeriesShapesVisible(1, false); XYPlot plot2 = chart2.getXYPlot(); plot2.setRenderer(0, r2); plot2.setRenderer(1, r2); ChartPanel cp = new ChartPanel(chart); ChartPanel cp2 = new ChartPanel(chart2); //multiple graph container JPanel graph_container = new JPanel(); graph_container.setLayout(new BoxLayout(graph_container, BoxLayout.X_AXIS)); graph_container.add(cp); graph_container.add(cp2); //add chart panel in main window window.add(graph_container, BorderLayout.CENTER); //window.add(cp2, BorderLayout.WEST); window.add(Pause_btn, BorderLayout.AFTER_LAST_LINE); Pause_btn.setEnabled(false); //pause btn action Pause_btn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (Pause_btn.getText().equalsIgnoreCase("Pause")) { if (chosenPort.isOpen()) { try { Output.write(0); } catch (IOException ex) { Logger.getLogger(Graph_with_jframe_and_arduino.class.getName()).log(Level.SEVERE, null, ex); } } Pause_btn.setText("Start"); } else { if (chosenPort.isOpen()) { try { Output.write(1); } catch (IOException ex) { Logger.getLogger(Graph_with_jframe_and_arduino.class.getName()).log(Level.SEVERE, null, ex); } } Pause_btn.setText("Pause"); } throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }); // configure the connect button and use another thread to listen for data connectButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { if (connectButton.getText().equals("Connect")) { // attempt to connect to the serial port chosenPort = SerialPort.getCommPort(portList_combobox.getSelectedItem().toString()); chosenPort.setComPortTimeouts(SerialPort.TIMEOUT_SCANNER, 0, 0); if (chosenPort.openPort()) { Output = chosenPort.getOutputStream(); connectButton.setText("Disconnect"); Pause_btn.setEnabled(true); portList_combobox.setEnabled(false); } // create a new thread that listens for incoming text and populates the graph Thread thread = new Thread() { @Override public void run() { Scanner scanner = new Scanner(chosenPort.getInputStream()); while (scanner.hasNextLine()) { try { String line = scanner.nextLine(); int number = Integer.parseInt(line); series.add(x, number); series2.add(x, number / 2); series3.add(x, number / 1.5); series4.add(x, number / 5); if (x > 100) { series.remove(0); series2.remove(0); series3.remove(0); series4.remove(0); } x++; window.repaint(); } catch (Exception e) { } } scanner.close(); } }; thread.start(); } else { // disconnect from the serial port chosenPort.closePort(); portList_combobox.setEnabled(true); Pause_btn.setEnabled(false); connectButton.setText("Connect"); } } }); // show the window window.setVisible(true); }
From source file:Main.java
static void parseLine(String line) { Scanner lineScanner = new Scanner(line); lineScanner.useDelimiter("\\s*,\\s*"); String name = lineScanner.next(); int age = lineScanner.nextInt(); boolean isCertified = lineScanner.nextBoolean(); System.out.println("It is " + isCertified + " that " + name + ", age " + age + ", is certified."); }
From source file:Main.java
public static int[] readNumsFromCommandLine() { Scanner s = new Scanner(System.in); int count = s.nextInt(); s.nextLine(); // throw away the newline. int[] numbers = new int[count]; Scanner numScanner = new Scanner(s.nextLine()); for (int i = 0; i < count; i++) { if (numScanner.hasNextInt()) { numbers[i] = numScanner.nextInt(); } else {//from ww w .j a va 2 s .c om System.out.println("You didn't provide enough numbers"); break; } } return numbers; }
From source file:Main.java
public static String convertStreamToString(java.io.InputStream is) { Scanner s = new Scanner(is).useDelimiter("\\A"); return s.hasNext() ? s.next() : ""; }
From source file:Main.java
private static int getChoice() { Scanner input = new Scanner(System.in); int choice = 1; //default value to force skip of first if statement check do {//w w w .j a v a 2s .c om if (choice < 1 | choice > 4) System.out.println("Invalid choice..."); System.out.print("Choice: "); /*This while loop checks the buffer stream for the next incoming input. *the purpose is to check if the input can be assigned an int value. *at this time choice has not be assigned*/ while (!input.hasNextInt()) { // ask for an input, if input NOT nextInt then: input.next(); // consumes the token and returns to top of loop for another token System.out.print("Try again: "); //don't want println as that would shift cursor to new line } choice = input.nextInt(); //once the input has been found to be an int, assign to choice /*now choice needs to be checked for the correct range of values. * if its not within 1-4 then repeat while loop above*/ } while (choice < 1 | choice > 4); //input.close(); return choice; }
From source file:Main.java
private static String drainStream(InputStream in) { Scanner s = new Scanner(in).useDelimiter("\\A"); return s.hasNext() ? s.next() : ""; }
From source file:Main.java
public static String convertStreamToString(InputStream is) { return new Scanner(is).useDelimiter("\\A").next(); }
From source file:Main.java
static Long toNumeric(String ip) { Scanner sc = new Scanner(ip).useDelimiter("\\."); Long l = (sc.nextLong() << 24) + (sc.nextLong() << 16) + (sc.nextLong() << 8) + (sc.nextLong()); sc.close();/* w w w . java2 s.c o m*/ return l; }
From source file:Main.java
static String convertStreamToString(java.io.InputStream is) { try {// www . jav a2 s .c o m return new Scanner(is).useDelimiter("\\A").next(); } catch (java.util.NoSuchElementException e) { return ""; } }