List of usage examples for java.util Scanner nextLine
public String nextLine()
From source file:edu.harvard.med.iccbl.screensaver.io.screens.ScreenPrivacyExpirationUpdater.java
/** * Return the subject first and the message second. * Message://ww w .j a v a 2s . c om * {0} Screen Number * {1} Screen Title * {2} timeToNotify (tbd, formatting) * * @throws MessagingException */ private Pair<String, String> getScreenExpireNotificationSubjectMessage() throws MessagingException { InputStream in = null; if (isCommandLineFlagSet(EXPIRATION_EMAIL_MESSAGE_LOCATION[SHORT_OPTION_INDEX])) { try { in = new FileInputStream( new File(getCommandLineOptionValue(EXPIRATION_EMAIL_MESSAGE_LOCATION[SHORT_OPTION_INDEX]))); } catch (FileNotFoundException e) { sendErrorMail( "Operation not completed for ScreenPrivacyExpirationUpdater, could not locate expiration message", toString(), e); throw new DAOTransactionRollbackException(e); } } else { in = this.getClass().getResourceAsStream(EXPIRATION_MESSAGE_TXT_LOCATION); } Scanner scanner = new Scanner(in); try { StringBuilder builder = new StringBuilder(); String subject = scanner.nextLine(); // first line is the subject while (scanner.hasNextLine()) { builder.append(scanner.nextLine()).append("\n"); } return Pair.newPair(subject, builder.toString()); } finally { scanner.close(); } }
From source file:configurator.Configurator.java
/** * Method for configuring device via telnet. Connect to device, authorizes, * and send to cli one by one line from command list, analyse every answer * and make report/*w w w. jav a 2s. c o m*/ * * @param login username for authorization * @param password password for authorization * @param ip ip address of device * @param commandList command list for input on device * @return report of telnet configuring this device */ String telnetConfigure(String login, String password, String ip, String commandList) { StringBuilder report = new StringBuilder("Configure: "); report.append(ip); try { Telnet telnet = new Telnet(login, password, ip); telnet.init(usernamePrompt, passwordPrompt, commandPrompt); Scanner commandReader = new Scanner(commandList); while (commandReader.hasNextLine()) { final String command = commandReader.nextLine(); final String answer = telnet.sendCommand(command, commandPrompt); if (!(analysisMode == AnalysisMode.OFF)) { if (!answerAnalysis(answer)) { report.append("\n").append(command).append(":\n").append(answer); } } } report.append("\n").append("Complete"); } catch (IOException ex) { Logger.getLogger(Device.class.getName()).log(Level.SEVERE, null, ex); report.append("\nConnection problem"); } catch (LoginFailedException ex) { report.append("\nAutentification failed: ").append(ip).append(" login: ").append(login); } return report.toString(); }
From source file:com.sonyericsson.hudson.plugins.gerrit.trigger.playback.GerritMissedEventsPlaybackManager.java
/** * Takes a string of json events and creates a collection. * @param eventsString Events in json in a string. * @return collection of events.//www . j a va 2 s . com */ private List<GerritTriggeredEvent> createEventsFromString(String eventsString) { List<GerritTriggeredEvent> events = Collections.synchronizedList(new ArrayList<GerritTriggeredEvent>()); Scanner scanner = new Scanner(eventsString); while (scanner.hasNextLine()) { String line = scanner.nextLine(); logger.debug("found line: {}", line); JSONObject jsonObject = null; try { jsonObject = GerritJsonEventFactory.getJsonObjectIfInterestingAndUsable(line); if (jsonObject == null) { continue; } } catch (Exception ex) { logger.warn("Unanticipated error when creating DTO representation of JSON string.", ex); continue; } GerritEvent evt = GerritJsonEventFactory.getEvent(jsonObject); if (evt instanceof GerritTriggeredEvent) { Provider provider = new Provider(); provider.setName(serverName); ((GerritTriggeredEvent) evt).setProvider(provider); events.add((GerritTriggeredEvent) evt); } } scanner.close(); return events; }
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 a v a 2 s . 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:configurator.Configurator.java
/** * Method for getting address of configuration file of device by name * * @param name name of device;/*from w ww . j av a2s . c o m*/ * @return address of configuration file; * @throws FileNotFoundException */ String getAddressByModelName(String name) throws FileNotFoundException { Scanner switchReader = new Scanner(new FileReader("switchlist.txt")); String model; while (switchReader.hasNextLine()) { model = switchReader.nextLine(); if (model.contains(name)) { return model.split("->")[1]; } } return null; }
From source file:mase.MaseManagerTerminal.java
public void run(File runnersFile, File jobsFile) { try {//from www . java2 s . c o m if (runnersFile != null) { mng.loadRunners(runnersFile); } } catch (Exception ex) { ex.printStackTrace(); } try { if (jobsFile != null) { mng.loadJobs(jobsFile); } } catch (Exception ex) { ex.printStackTrace(); } final Scanner lineSC = new Scanner(System.in); while (true) { System.out.print("> "); String option = lineSC.next(); Scanner sc = new Scanner(lineSC.nextLine()); try { switch (option) { case "addrunner": mng.addRunner(sc.nextLine()); break; case "loadrunners": while (sc.hasNext()) { mng.loadRunners(new File(sc.next())); } break; case "addjobs": mng.addJob(sc.nextLine()); break; case "loadjobs": while (sc.hasNext()) { mng.loadJobs(new File(sc.next())); } break; case "remove": while (sc.hasNext()) { mng.removeFromWaiting(sc.next()); } break; case "killrunner": while (sc.hasNextInt()) { mng.killRunner(sc.nextInt()); } break; case "kill": while (sc.hasNext()) { mng.killJob(sc.next()); } break; case "killall": mng.failed.addAll(mng.waitingList); mng.waitingList.clear(); List<Job> running = new ArrayList<>(mng.running.values()); for (Job j : running) { mng.killJob(j.id); } break; case "output": int id = sc.nextInt(); int l = sc.hasNextInt() ? sc.nextInt() : lines; System.out.println(mng.getOutput(id, l)); break; case "jobs": while (sc.hasNext()) { String jobid = sc.next(); List<Job> found = mng.findJobs(jobid); for (Job j : found) { System.out.println(j.detailedToString() + "\n-----------------"); } } break; case "status": int ls = sc.hasNextInt() ? sc.nextInt() : lines; System.out.println("Completed: " + mng.completed.size() + "\tWaiting: " + mng.waitingList.size() + "\tFailed: " + mng.failed.size() + "\tRunning: " + mng.running.size() + "/" + mng.runners.size() + " " + (mng.runningStatus() ? "(ACTIVE)" : "(PAUSED)")); for (Entry<JobRunner, Job> e : mng.running.entrySet()) { System.out.println("== " + e.getValue() + " @ " + e.getKey() + " ========"); System.out.println(mng.getOutput(e.getKey().id, ls)); } break; case "list": while (sc.hasNext()) { String t = sc.next(); if (t.equals("failed")) { for (int i = mng.failed.size() - 1; i >= 0; i--) { Job j = mng.failed.get(i); System.out.println(df.format(j.submitted) + " " + j); } } else if (t.equals("completed")) { for (int i = mng.completed.size() - 1; i >= 0; i--) { Job j = mng.completed.get(i); System.out.println(df.format(j.submitted) + " " + j); } } else if (t.equals("waiting")) { for (int i = mng.waitingList.size() - 1; i >= 0; i--) { Job j = mng.waitingList.get(i); System.out.println(df.format(j.submitted) + " " + j); } } else if (t.equals("runners")) { for (JobRunner r : mng.runners.values()) { if (mng.running.containsKey(r)) { Job runningJob = mng.running.get(r); System.out .println(df.format(runningJob.started) + " " + r + " @ " + runningJob); } else { System.out.println("Idle " + r); } } } else { error("Unknown list: " + t); } } break; case "retry": while (sc.hasNext()) { mng.retryJob(sc.next()); } break; case "retryfailed": mng.retryFailed(); break; case "clear": while (sc.hasNext()) { String t = sc.next(); if (t.equals("failed")) { mng.failed.clear(); } else if (t.equals("completed")) { mng.completed.clear(); } else if (t.equals("waiting")) { mng.waitingList.clear(); } else if (t.equals("runners")) { List<Integer> runners = new ArrayList<>(mng.runners.keySet()); for (Integer r : runners) { mng.killRunner(r); } } else { error("Unknown list: " + t); } } break; case "priority": String type = sc.next(); while (sc.hasNext()) { String i = sc.next(); if (type.equals("top")) { mng.topPriority(i); } else if (type.equals("bottom")) { mng.lowestPriority(i); } } break; case "sort": String sort = sc.next(); if (sort.equals("job")) { mng.sortJobFirst(); } else if (sort.equals("date")) { mng.sortSubmissionDate(); } else { error("Unknown sorting method: " + sort); } break; case "pause": mng.pause(sc.hasNext() && sc.next().equals("force")); break; case "start": mng.resume(); break; case "exit": System.exit(0); break; case "set": String par = sc.next(); switch (par) { case "lines": lines = sc.nextInt(); break; case "maxtries": mng.setMaxTries(sc.nextInt()); break; } break; case "mute": this.mute = true; break; case "unmute": this.mute = false; break; case "help": System.out.println("Available commands:\n" + "-- addrunner runner_type [config]\n" + "-- loadrunners [file]...\n" + "-- addjobs job_params\n" + "-- loadjobs [file]...\n" + "-- killrunner [runner_id]...\n" + "-- remove [job_id]...\n" + "-- kill [job_id]...\n" + "-- killall \n" + "-- output runner_id [lines]\n" + "-- jobs [job_id]...\n" + "-- status [lines]\n" + "-- list [waiting|completed|failed|runners]...\n" + "-- retry [job_id]...\n" + "-- retryfailed \n" + "-- priority top|bottom [job_id]...\n" + "-- sort batch|job|date\n" + "-- clear [waiting|completed|failed|runners]...\n" + "-- pause [force]\n" + "-- start \n" + "-- mute|unmute \n" + "-- exit \n" + "-- set lines|tries value"); break; default: System.out.println("Unknown command. Try help."); } } catch (Exception e) { e.printStackTrace(); } } }
From source file:me.prokopyl.commandtools.commands.Commands.java
private void initDescriptions() { String fileName = "help/" + getUsualName() + ".txt"; InputStream stream = getClass().getClassLoader().getResourceAsStream(fileName); if (stream == null) { PluginLogger.LogWarning("Could not load description file for the " + getUsualName() + " command"); return;/*from www . j a v a 2s.c o m*/ } Scanner scanner = new Scanner(stream); StringBuilder builder = new StringBuilder(); //Getting the group's description //And then each command's description int colonIndex, firstSpaceIndex; boolean isGroupDescription = true; while (scanner.hasNextLine()) { String line = scanner.nextLine(); colonIndex = line.indexOf(':'); if (isGroupDescription) { firstSpaceIndex = line.indexOf(' '); if (colonIndex > 0 && firstSpaceIndex > colonIndex) isGroupDescription = false; } if (isGroupDescription) { builder.append(line).append('\n'); } else { commandsDescriptions.put(line.substring(0, colonIndex).trim(), line.substring(colonIndex + 1).trim()); } } scanner.close(); description = builder.toString().trim(); }
From source file:calendarioSeries.vistas.MainViewController.java
public MainViewController() { mesActual = new Mes(); Calendar cal = Calendar.getInstance(); this.hoy = cal.get(Calendar.DAY_OF_MONTH); this.esteMes = mesActual.getNumMes(); this.esteAno = mesActual.getNumAno(); File file = new File("data.db"); FileInputStream fis;/*from w w w .j a va 2 s . c om*/ ObjectInputStream ois; try { fis = new FileInputStream(file); ois = new ObjectInputStream(fis); this.series = (ArrayList<Serie>) ois.readObject(); ois.close(); } catch (IOException ex) { ex.printStackTrace(); this.series = new ArrayList<>(); try { File datos = new File("seriesUsuario.json"); Scanner in = new Scanner(datos); String toJson = ""; while (in.hasNext()) { toJson += in.nextLine(); } JSONObject sesion = new JSONObject(toJson); Set<String> ids = sesion.keySet(); for (String id : ids) { Serie aux = new Serie(id); if (series.contains(aux)) { JSONArray lastVisto = sesion.getJSONArray(id).getJSONArray(1); aux.setVistosHasta(lastVisto.getInt(0), lastVisto.getInt(1)); int i = 0; for (Serie serie : series) { if (serie.equals(aux)) { this.series.set(i, aux); } i++; } } else { this.series.add(aux); } } } catch (FileNotFoundException e) { } } catch (ClassNotFoundException ex) { ex.printStackTrace(); } }
From source file:ml.shifu.shifu.core.processor.PostTrainModelProcessor.java
/** * read the binary average score and update them into column list * /* w w w. j a va 2 s . com*/ * @param columnConfigList * input column config list * @return updated column config list * @throws IOException * for any io exception */ private List<ColumnConfig> updateColumnConfigWithBinAvgScore(List<ColumnConfig> columnConfigList) throws IOException { List<Scanner> scanners = ShifuFileUtils.getDataScanners(pathFinder.getBinAvgScorePath(), modelConfig.getDataSet().getSource()); // CommonUtils.getDataScanners(pathFinder.getBinAvgScorePath(), modelConfig.getDataSet().getSource()); for (Scanner scanner : scanners) { while (scanner.hasNextLine()) { List<Integer> scores = new ArrayList<Integer>(); String[] raw = scanner.nextLine().split("\\|"); int columnNum = Integer.parseInt(raw[0]); for (int i = 1; i < raw.length; i++) { scores.add(Integer.valueOf(raw[i])); } ColumnConfig config = columnConfigList.get(columnNum); config.setBinAvgScore(scores); } } // release closeScanners(scanners); return columnConfigList; }
From source file:fr.zcraft.zlib.components.commands.CommandGroup.java
private void initDescriptions() { String fileName = "help/" + getUsualName() + ".txt"; InputStream stream = getClass().getClassLoader().getResourceAsStream(fileName); if (stream == null) { PluginLogger.warning("Could not load description file for the " + getUsualName() + " command"); return;/* w w w .ja va2 s . co m*/ } Scanner scanner = new Scanner(stream); StringBuilder builder = new StringBuilder(); //Getting the group's description //And then each command's description int colonIndex, firstSpaceIndex; boolean isGroupDescription = true; while (scanner.hasNextLine()) { String line = scanner.nextLine(); colonIndex = line.indexOf(':'); if (isGroupDescription) { firstSpaceIndex = line.indexOf(' '); if (colonIndex > 0 && firstSpaceIndex > colonIndex) isGroupDescription = false; } if (isGroupDescription) { builder.append(line).append('\n'); } else { commandsDescriptions.put(line.substring(0, colonIndex).trim(), line.substring(colonIndex + 1).trim()); } } scanner.close(); description = builder.toString().trim(); }