List of usage examples for java.util Scanner nextLine
public String nextLine()
From source file:com.chortitzer.web.admin.controller.TiemposBean.java
public void processMarcasFile() { try {/*from ww w.j a v a2s .co m*/ FacesContext.getCurrentInstance().addMessage("form:msgs", new FacesMessage(FacesMessage.SEVERITY_INFO, "", "Cargando...")); String fileName = "C:\\Users\\adriang\\Documents\\Synel\\SYBridge\\Data\\Collect.dat"; if (Files.exists(Paths.get(fileName))) { Path file = Paths.get(fileName); Integer countNoRegistrados = 0; Scanner scanner = new Scanner(file, StandardCharsets.UTF_8.name()); while (scanner.hasNextLine()) { String aLine = scanner.nextLine(); SimpleDateFormat formatter = new SimpleDateFormat("ddMMyyHHmm"); Date d = formatter.parse(aLine.substring(10, 16) + aLine.substring(29, 33)); //System.out.println(d.toString()); //System.out.println(aLine.substring(18, 29)); //System.out.println(aLine.substring(16, 17)); RrhhMarcas rrhhMarcas = new RrhhMarcas(); rrhhMarcas.setFechahora(d); rrhhMarcas.setNroEmpleado(rrhhEmpleadosRepo.findOne(Integer.parseInt(aLine.substring(18, 29)))); rrhhMarcas.setEntradaSalida(Integer.parseInt(aLine.substring(17, 18))); //if (em.find(RrhhTiempos.class, rrhhTiemposPK) == null) { if (rrhhMarcas.getNroEmpleado() == null) { FacesContext.getCurrentInstance().addMessage(null, new FacesMessage( FacesMessage.SEVERITY_ERROR, "Error!", "Existen registros para empleados no identificacdos en la base de datos! - Nro.: " + aLine.substring(18, 29))); countNoRegistrados += 1; System.out.println("Empleado sin registro: " + aLine.substring(18, 29)); } else { rrhhMarcasRepo.save(rrhhMarcas); } } limpiarMarcasDobles(); if (countNoRegistrados == 0) { Files.deleteIfExists(file); } } } catch (Exception ex) { LOGGER.error(Thread.currentThread().getStackTrace()[1].getMethodName(), ex); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", ex.getMessage())); } }
From source file:io.github.mikesaelim.arxivoaiharvester.CommandLineInterface.java
/** * Handle a single response to a "ListRecords" request. */// w ww . j a v a 2 s . co m private static boolean handleListRecordResponse(Scanner scanner, ListRecordsResponse response) { System.out.println("Response received!"); printLine(" Response datetime: ", response.getResponseDate()); List<ArticleMetadata> records = response.getRecords(); if (records.size() == 0) { System.out.println(" No records found."); return true; // No records found, but there still could be a legal resumption token returned. } printLine(" Number of records retrieved in this batch: ", records.size()); if (response.hasResumption()) { System.out.println(" Resumption token returned - there is another batch of records after this one."); } printLine(" Current cursor position: ", response.getCursor()); printLine(" Complete list size: ", response.getCompleteListSize()); System.out.println(); System.out .println("Now you can view each of the records in this batch individually. Simply press ENTER to " + "bring up the next record. If there is another batch after this one, the harvester will make a " + "request to retrieve it when you get to the end. Type \'q\' and ENTER to exit."); for (int recordNumber = 0; recordNumber < records.size(); recordNumber += 999) { String readerInput = scanner.nextLine(); if ("q".equals(readerInput.trim())) { return false; } System.out.println( "************ Record " + (recordNumber + 1) + " of " + records.size() + " ************"); printRecord(records.get(recordNumber)); System.out.println("***************************************"); System.out.println(); } if (!response.hasResumption()) { System.out.println("End of records."); } else { System.out.println("End of records, but there is another batch after this. Press ENTER to send the " + "resumption request. Type \'q\' and ENTER to exit."); String readerInput = scanner.nextLine(); if ("q".equals(readerInput.trim())) { return false; } } return true; }
From source file:controller.CLI.java
void run() { Scanner s = new Scanner(System.in); System.out.println(Data.FWELCOME); for (;;) {/*w w w . j a va 2 s .c o m*/ System.out.print("pplex> "); String cmd = s.nextLine(); System.out.println(parseCmd(cmd)); } }
From source file:gemlite.core.util.CommandBase.java
/*** * false,?/*w w w. j ava 2 s . c o m*/ * * @return * @throws CmdLineException */ protected boolean waitUserInput(String[] args, String msg) { Scanner reader = new Scanner(System.in); boolean hasInitInput = args != null && args.length > 0; if (!hasInitInput) System.out.println(msg); do//while (hasInitInput && reader.hasNextLine()) { String line = null; String[] newArgs = null; if (hasInitInput) { newArgs = args; } else { line = reader.nextLine(); if (line.equalsIgnoreCase("X")) { reader.close(); return false; } newArgs = line.split(" "); } try { if (newArgs.length > 0 && !newArgs[0].isEmpty()) parser.parseArgument(newArgs); else System.err.println("please input your args!"); printValue(); } catch (CmdLineException e) { e.printStackTrace(); System.out.println("Error, last Input:[" + line + "]\nInput:"); continue; } break; } while (true); reader.close(); return true; }
From source file:mucom.Footing.DirectionGetter.java
public void getRoute() //public ArrayList<GeoPoint> getRoute() { if (loadcoords == 0) { String startc = startp.getLatitudeE6() / 1E6 + "," + startp.getLongitudeE6() / 1E6; String endc = endp.getLatitudeE6() / 1E6 + "," + endp.getLongitudeE6() / 1E6; String urlString = "http://maps.google.com/maps/api/directions/json?origin=" + startc + "&destination=" + endc + "&mode=walking&sensor=false"; Log.i("Coords", urlString); String result = ""; try {/*from w ww.ja v a 2 s. c o m*/ Log.i("DGetter", "Connecting.."); URL url = new URL(urlString); Scanner in = new Scanner(new InputStreamReader(url.openStream())); Log.i("DGetter", "Connected OK"); while (in.hasNext()) { result += in.nextLine(); } Log.i("DGetter", "Download OK"); } catch (Exception e) { Log.e("DGetter", "Connection Error"); } //parse json data try { //overlays.clear(); mpo.removeAllOverlays(); fa.pnts.clear(); JSONObject jsonObject = new JSONObject(result); // parse response into json object // routesArray contains ALL routes JSONArray routesArray = jsonObject.getJSONArray("routes"); // Grab the first route JSONObject route = routesArray.getJSONObject(0); // Take all legs from the route JSONArray legs = route.getJSONArray("legs"); // Grab first leg JSONObject leg = legs.getJSONObject(0); // Grab steps JSONArray steps = leg.getJSONArray("steps"); JSONObject durationObject = leg.getJSONObject("duration"); JSONObject startObj = leg.getJSONObject("start_location"); String duration = durationObject.getString("text"); Log.i("Dirs", "JSon parsing OK"); double lat; double lon; //add starting point lat = startObj.getDouble("lat"); lon = startObj.getDouble("lng"); GeoPoint g = new GeoPoint((int) (lat * 1E6), (int) (lon * 1E6)); fa.pnts.add(g); OverlayItem overlayitem = new OverlayItem(g, "Hola, Mundo!", "I'm in Mexico City!"); mpo.addOverlay(overlayitem, icons[0]); Log.i("Dirs", "Added " + lat + ", " + lon); //setup segments array fa.segments = new GeoPoint[steps.length()][2]; Log.i("Segments", "array of " + steps.length()); int i = 0; for (i = 0; i < steps.length(); i++) { lat = steps.getJSONObject(i).getJSONObject("end_location").getDouble("lat"); lon = steps.getJSONObject(i).getJSONObject("end_location").getDouble("lng"); g = new GeoPoint((int) (lat * 1E6), (int) (lon * 1E6)); fa.pnts.add(g); overlayitem = new OverlayItem(g, "Hola, Mundo!", "I'm in Mexico City!"); if (i < steps.length() - 1) mpo.addOverlay(overlayitem, icons[1]); else mpo.addOverlay(overlayitem, icons[2]); //add to segments array //add end location fa.segments[i][1] = g; //add start location lat = steps.getJSONObject(i).getJSONObject("start_location").getDouble("lat"); lon = steps.getJSONObject(i).getJSONObject("start_location").getDouble("lng"); g = new GeoPoint((int) (lat * 1E6), (int) (lon * 1E6)); fa.segments[i][0] = g; Log.i("Dirs", "Added " + lat + ", " + lon); } //overlays.add(mpo); Log.i("Dirs", "OK, added " + mpo.size() + " overlays pts"); } catch (JSONException e) { Log.e("log_tag", "Error parsing data " + e.toString()); } } else //if asked to load coords { List<GeoPoint> lpoints = new ArrayList<GeoPoint>(); switch (loadcoords) { //Glasgow map case 1: lpoints.add(new GeoPoint((int) (55.861706 * 1E6), (int) (-4.251194 * 1E6))); lpoints.add(new GeoPoint((int) (55.861427 * 1E6), (int) (-4.248898 * 1E6))); lpoints.add(new GeoPoint((int) (55.859901 * 1E6), (int) (-4.249467 * 1E6))); lpoints.add(new GeoPoint((int) (55.859730 * 1E6), (int) (-4.247664 * 1E6))); lpoints.add(new GeoPoint((int) (55.858677 * 1E6), (int) (-4.247932 * 1E6))); lpoints.add(new GeoPoint((int) (55.858353 * 1E6), (int) (-4.245669 * 1E6))); break; case 2: //Patras 1 - prokat - prutaneia lpoints.add(new GeoPoint((int) (38.283730 * 1E6), (int) (21.788706 * 1E6))); lpoints.add(new GeoPoint((int) (38.284023 * 1E6), (int) (21.788473 * 1E6))); lpoints.add(new GeoPoint((int) (38.283794 * 1E6), (int) (21.787975 * 1E6))); lpoints.add(new GeoPoint((int) (38.284672 * 1E6), (int) (21.787218 * 1E6))); lpoints.add(new GeoPoint((int) (38.284920 * 1E6), (int) (21.787636 * 1E6))); lpoints.add(new GeoPoint((int) (38.285336 * 1E6), (int) (21.787300 * 1E6))); lpoints.add(new GeoPoint((int) (38.285599 * 1E6), (int) (21.787697 * 1E6))); lpoints.add(new GeoPoint((int) (38.286354 * 1E6), (int) (21.787073 * 1E6))); lpoints.add(new GeoPoint((int) (38.286205 * 1E6), (int) (21.786655 * 1E6))); break; case 3: //Patras 2 - prutaneia - near prokat lpoints.add(new GeoPoint((int) (38.286205 * 1E6), (int) (21.786661 * 1E6))); lpoints.add(new GeoPoint((int) (38.286350 * 1E6), (int) (21.787071 * 1E6))); lpoints.add(new GeoPoint((int) (38.285618 * 1E6), (int) (21.787687 * 1E6))); lpoints.add(new GeoPoint((int) (38.285339 * 1E6), (int) (21.787306 * 1E6))); lpoints.add(new GeoPoint((int) (38.284920 * 1E6), (int) (21.787636 * 1E6))); lpoints.add(new GeoPoint((int) (38.284504 * 1E6), (int) (21.786835 * 1E6))); lpoints.add(new GeoPoint((int) (38.284107 * 1E6), (int) (21.787334 * 1E6))); lpoints.add(new GeoPoint((int) (38.283817 * 1E6), (int) (21.787506 * 1E6))); lpoints.add(new GeoPoint((int) (38.283390 * 1E6), (int) (21.787561 * 1E6))); break; } mpo.removeAllOverlays(); fa.pnts.clear(); //add points to fa plist for (GeoPoint p : lpoints) { fa.pnts.add(p); } //add start and end overlay OverlayItem overlayitem = new OverlayItem(lpoints.get(0), "Hola, Mundo!", "I'm in Mexico City!"); mpo.addOverlay(overlayitem, icons[0]); overlayitem = new OverlayItem(lpoints.get(lpoints.size() - 1), "Hola, Mundo!", "I'm in Mexico City!"); mpo.addOverlay(overlayitem, icons[2]); fa.startp = lpoints.get(0); fa.endp = lpoints.get(lpoints.size() - 1); //setup segments array fa.segments = new GeoPoint[lpoints.size() - 1][2]; for (int i = 0; i < lpoints.size() - 1; i++) { overlayitem = new OverlayItem(lpoints.get(i), "Hola, Mundo!", "I'm in Mexico City!"); mpo.addOverlay(overlayitem, icons[1]); fa.segments[i][0] = lpoints.get(i); fa.segments[i][1] = lpoints.get(i + 1); } } }
From source file:UniqueInstance.java
/** * Reoit un message d'une socket s'tant connecte au serveur d'coute. Si ce message est le message de l'instance * unique, l'application demande le focus. * * @param socket// w w w .j a v a 2 s. co m * Socket connect au serveur d'coute. */ private void receive(Socket socket) { Scanner sc = null; try { /* On n'coute que 5 secondes, si aucun message n'est reu, tant pis... */ socket.setSoTimeout(5000); /* On dfinit un Scanner pour lire sur l'entre de la socket. */ sc = new Scanner(socket.getInputStream()); /* On ne lit qu'une ligne. */ String s = sc.nextLine(); /* Si cette ligne est le message de l'instance unique... */ if (message.equals(s)) { /* On excute le code demand. */ runOnReceive.run(); } } catch (IOException e) { Logger.getLogger("UniqueInstance").warning("Lecture du flux d'entre de la socket chou."); } finally { if (sc != null) { sc.close(); } } }
From source file:de.iteratec.iteraplan.general.PropertiesTest.java
/** * @see {@link #testJspKeys()}/* w ww . jav a 2 s .co m*/ * @param collectedBundleKeys * Bundle keys collected so far. Acts as in-out parameter. * @param p * The pattern to find. * @param fileToProcess * The file to be looked at. * @return true if a bundle key was missing. * @throws FileNotFoundException */ private boolean parseJspForBundleKeys(Set<String> collectedBundleKeys, Pattern p, File fileToProcess) throws FileNotFoundException { boolean wasSuccessful = true; if (fileToProcess.isDirectory()) { for (File f : fileToProcess.listFiles()) { boolean containedSuccess = parseJspForBundleKeys(collectedBundleKeys, p, f); if (!containedSuccess) { wasSuccessful = false; } } } else if (fileToProcess.getName().toLowerCase().endsWith("jsp")) { Scanner sc = new Scanner(fileToProcess); StringBuffer jspAsStringBuffer = new StringBuffer(); while (sc.hasNextLine()) { jspAsStringBuffer.append(sc.nextLine()); } String jspAsString = jspAsStringBuffer.toString(); MatchResult result = null; sc = new Scanner(jspAsString); while (true) { if (sc.findInLine(p) == null) { break; } result = sc.match(); String bundleKey = result.group(POSITION_OF_PROPERTY_IN_JSP_TAG); // refers to regexp which is passed into this method collectedBundleKeys.add(bundleKey); // omit registered keys and keys which contain variables if (!ACCEPTABLE_MISSES_LIST.contains(bundleKey) && !(bundleKey.contains("$"))) { for (LanguageFile l : languageFiles) { if (!l.keySet().contains(bundleKey)) { wasSuccessful = false; LOGGER.info( "Bundle key {0} defined in JSP {1} was not found in {2} ApplicationResources.properties!", bundleKey, fileToProcess, l.language); } } } } } return wasSuccessful; }
From source file:br.univali.ps.fuzzy.portugolFuzzyCorretor.core.PortugolFuzzyCorretor.java
private int contarNumeroLinhas() { int linhas = 0; Scanner scanner = new Scanner(this.codigoPortugol); // Para possibilitar a edio do texto dentro do programa // Caso no seja necessrio, contabilizar dentro do FileController while (scanner.hasNextLine()) { linhas++;/*from www . jav a 2s . c om*/ scanner.nextLine(); } scanner.close(); return linhas; }
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 www.j a va 2 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:com.mgmtp.perfload.perfalyzer.binning.MeasuringAggregatedRequestsBinningStrategy.java
@Override public void binData(final Scanner scanner, final WritableByteChannel destChannel) throws IOException { BinManager binSecondManager = new BinManager(startOfFirstBin, PerfAlyzerConstants.BIN_SIZE_MILLIS_1_SECOND); BinManager binMinuteManager = new BinManager(startOfFirstBin, PerfAlyzerConstants.BIN_SIZE_MILLIS_1_MINUTE); int requestCounter = 0; int errorCounter = 0; while (scanner.hasNextLine()) { tokenizer.reset(scanner.nextLine()); String[] tokens = tokenizer.getTokenArray(); long timestampMillis = Long.parseLong(tokens[0]); if (!"AGENT".equals(tokens[MEASURING_NORMALIZED_COL_REQUEST_TYPE])) { requestCounter++;// ww w .j a v a 2 s. c o m binSecondManager.addValue(timestampMillis); binMinuteManager.addValue(timestampMillis); } if ("ERROR".equals(tokens[MEASURING_NORMALIZED_COL_RESULT])) { errorCounter++; } } // binSecondManager.completeLastBin(); // binMinuteManager.completeLastBin(); double[] requestsPerSecond = binSecondManager.countStream().asDoubleStream().toArray();// Doubles.toArray(binSecondManager.getBins().values().stream().map(longToDouble()).collect(toList())); double minRequestsPerSecond = StatUtils.min(requestsPerSecond); double medianRequestsPerSecond = StatUtils.percentile(requestsPerSecond, 50d); double maxRequestsPerSecond = StatUtils.max(requestsPerSecond); double[] requestsPerMinute = binMinuteManager.countStream().asDoubleStream().toArray(); // Doubles.toArray(binMinuteManager.getBins().values().stream().map(longToDouble()).collect(toList())); double minRequestsPerMinute = StatUtils.min(requestsPerMinute); double medianRequestsPerMinute = StatUtils.percentile(requestsPerMinute, 50d); double maxRequestsPerMinute = StatUtils.max(requestsPerMinute); StrBuilder sb = new StrBuilder(); appendEscapedAndQuoted(sb, DELIMITER, "numRequests"); appendEscapedAndQuoted(sb, DELIMITER, "numErrors"); appendEscapedAndQuoted(sb, DELIMITER, "minReqPerSec"); appendEscapedAndQuoted(sb, DELIMITER, "medianReqPerSec"); appendEscapedAndQuoted(sb, DELIMITER, "maxReqPerSec"); appendEscapedAndQuoted(sb, DELIMITER, "minReqPerMin"); appendEscapedAndQuoted(sb, DELIMITER, "medianReqPerMin"); appendEscapedAndQuoted(sb, DELIMITER, "maxReqPerMin"); writeLineToChannel(destChannel, sb.toString(), Charsets.UTF_8); sb = new StrBuilder(); appendEscapedAndQuoted(sb, DELIMITER, intNumberFormat.format(requestCounter)); appendEscapedAndQuoted(sb, DELIMITER, intNumberFormat.format(errorCounter)); appendEscapedAndQuoted(sb, DELIMITER, intNumberFormat.format(minRequestsPerSecond)); appendEscapedAndQuoted(sb, DELIMITER, intNumberFormat.format(medianRequestsPerSecond)); appendEscapedAndQuoted(sb, DELIMITER, intNumberFormat.format(maxRequestsPerSecond)); appendEscapedAndQuoted(sb, DELIMITER, intNumberFormat.format(minRequestsPerMinute)); appendEscapedAndQuoted(sb, DELIMITER, intNumberFormat.format(medianRequestsPerMinute)); appendEscapedAndQuoted(sb, DELIMITER, intNumberFormat.format(maxRequestsPerMinute)); writeLineToChannel(destChannel, sb.toString(), Charsets.UTF_8); }