Java Code Examples for java.io.Console#readLine()
The following examples show how to use
java.io.Console#readLine() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TruffleMumblerMain.java From mumbler with GNU General Public License v3.0 | 6 votes |
private static void startREPL() throws IOException { Console console = System.console(); while (true) { // READ String data = console.readLine(PROMPT); if (data == null) { // EOF sent break; } MumblerContext context = new MumblerContext(); Source source = Source.newBuilder(ID, data, "<console>").build(); ListSyntax sexp = Reader.read(source); Converter converter = new Converter(null, flags.tailCallOptimizationEnabled); MumblerNode[] nodes = converter.convertSexp(context, sexp); // EVAL Object result = execute(nodes, context.getGlobalFrame()); // PRINT if (result != MumblerList.EMPTY) { System.out.println(result); } } }
Example 2
Source File: BenchmarkMotifDiscovery.java From SAX with GNU General Public License v2.0 | 6 votes |
public static void main(String[] args) throws Exception { series = TSProcessor.readFileColumn(TEST_DATA_FNAME, 0, 0); Console c = System.console(); if (c != null) { c.format("\nPress ENTER to proceed.\n"); c.readLine(); } Date start = new Date(); // motifsBF = BruteForceMotifImplementation.series2BruteForceMotifs(series, MOTIF_SIZE, // MOTIF_RANGE, ZNORM_THRESHOLD); // System.out.println(motifsBF); MotifRecord motifsEMMA = EMMAImplementation.series2EMMAMotifs(series, MOTIF_SIZE, MOTIF_RANGE, PAA_SIZE, ALPHABET_SIZE, ZNORM_THRESHOLD); Date end = new Date(); System.out.println(motifsEMMA); System.out.println("done in " + SAXProcessor.timeToString(start.getTime(), end.getTime())); }
Example 3
Source File: Shell.java From jql with MIT License | 6 votes |
public static void main(String[] args) { String databaseFile = ""; if (args.length >= 1) { databaseFile = args[0]; } DataSource dataSource = getDataSourceFrom(databaseFile); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); resultSetExtractor = new StringResultSetExtractor(); queryExecutor = new QueryExecutor(jdbcTemplate); Console console = getConsole(); String command; while (true) { System.out.print("$>"); command = console.readLine(); if (command.equalsIgnoreCase("quit")) { break; } process(command); } System.out.println("bye!"); }
Example 4
Source File: Projects.java From rundeck-cli with Apache License 2.0 | 6 votes |
@Command(description = "Delete a project") public boolean delete(ProjectDelete options, CommandOutput output) throws IOException, InputError { String project = projectOrEnv(options); if (!options.isConfirm()) { //request confirmation Console console = System.console(); String s = "n"; if (null != console) { s = console.readLine("Really delete project %s? (y/N) ", project); } else { output.warning("No console input available, and --confirm/-y was not set."); } if (!"y".equals(s)) { output.warning(String.format("Not deleting project %s.", project)); return false; } } apiCall(api -> api.deleteProject(project)); output.info(String.format("Project was deleted: %s%n", project)); return true; }
Example 5
Source File: Util.java From rundeck-cli with Apache License 2.0 | 6 votes |
/** * Use console to prompt user for input * * @param prompt prompt string * @param handler input handler, returns parsed value, or empty to prompt again * @param defval default value to return if no input available or user cancels input * @param <T> result type * @return result */ public static <T> T readPrompt(String prompt, Function<String, Optional<T>> handler, T defval) { Console console = System.console(); if (null == console) { return defval; } while (true) { String load = console.readLine(prompt); if (null == load) { return defval; } Optional<T> o = handler.apply(load.trim()); if (o.isPresent()) { return o.get(); } } }
Example 6
Source File: DictApply.java From morfologik-stemming with BSD 3-Clause "New" or "Revised" License | 6 votes |
private LineSupplier determineInput() throws IOException { if (this.input != null) { return new ReaderLineSupplier(Files.newBufferedReader(this.input, Charset.forName(inputEncoding))); } final Console c = System.console(); if (c != null) { System.err.println("NOTE: Using Console for input, character encoding is unknown but should be all right."); return new LineSupplier() { @Override public String nextLine() throws IOException { return c.readLine(); } }; } Charset charset = this.inputEncoding != null ? Charset.forName(this.inputEncoding) : Charset.defaultCharset(); System.err.println("NOTE: Using stdin for input, character encoding set to: " + charset.name() + " (use " + ARG_ENCODING + " to override)."); return new ReaderLineSupplier( new BufferedReader( new InputStreamReader( new BufferedInputStream(System.in), charset))); }
Example 7
Source File: AuthenticateInWebApplication.java From google-ads-java with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws Exception { // To fill in the values below, generate a client ID and client secret from the Google Cloud // Console (https://console.cloud.google.com) by creating credentials for a Web application. // Set the "Authorized redirect URIs" to: // http://localhost/oauth2callback String clientId; String clientSecret; String loginEmailAddressHint; Console console = System.console(); if (console == null) { // The console will be null when running this example in some IDEs. In this case, please // set the clientId and clientSecret in the lines below. clientId = "INSERT_CLIENT_ID_HERE"; clientSecret = "INSERT_CLIENT_SECRET_HERE"; // Optional: If your application knows which user is trying to authenticate, you can set this // to the user's email address so that the Google Authentication Server will automatically // populate the account selection prompt with that address. loginEmailAddressHint = null; // Ensures that the client ID and client secret are not the "INSERT_..._HERE" values. Preconditions.checkArgument( !clientId.matches("INSERT_.*_HERE"), "Client ID is invalid. Please update the example and try again."); Preconditions.checkArgument( !clientSecret.matches("INSERT_.*_HERE"), "Client secret is invalid. Please update the example and try again."); } else { console.printf( "NOTE: When prompting for the client secret below, echoing will be disabled%n"); console.printf(" since the client secret is sensitive information.%n"); console.printf("Enter your client ID:%n"); clientId = console.readLine(); console.printf("Enter your client secret:%n"); clientSecret = String.valueOf(console.readPassword()); console.printf("(Optional) Enter the login email address hint:%n"); loginEmailAddressHint = Strings.emptyToNull(console.readLine()); } new AuthenticateInWebApplication().runExample(clientId, clientSecret, loginEmailAddressHint); }
Example 8
Source File: RestOrderServer.java From camelinaction2 with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws Exception { // create dummy backend DummyOrderService dummy = new DummyOrderService(); dummy.setupDummyOrders(); // create CXF REST service and inject the dummy backend RestOrderService rest = new RestOrderService(); rest.setOrderService(dummy); // setup Apache CXF REST server on port 9000 JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean(); sf.setResourceClasses(RestOrderService.class); sf.setResourceProvider(RestOrderService.class, new SingletonResourceProvider(rest)); // to use jackson for json sf.setProvider(JacksonJsonProvider.class); sf.setAddress("http://localhost:9000/"); // create and start the CXF server (non blocking) Server server = sf.create(); server.start(); // keep the JVM running Console console = System.console(); System.out.println("Server started on http://localhost:9000/"); System.out.println(""); // If you run the main class from IDEA/Eclipse then you may not have a console, which is null) if (console != null) { System.out.println(" Press ENTER to stop server"); console.readLine(); } else { System.out.println(" Stopping after 5 minutes or press ctrl + C to stop"); Thread.sleep(5 * 60 * 1000); } // stop CXF server server.stop(); System.exit(0); }
Example 9
Source File: AuthenticateInStandaloneApplication.java From google-ads-java with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws IOException { // Generates the client ID and client secret from the Google Cloud Console: // https://console.cloud.google.com String clientId; String clientSecret; Console console = System.console(); if (console == null) { // The console will be null when running this example in some IDEs. In this case, please // set the clientId and clientSecret in the lines below. clientId = "INSERT_CLIENT_ID_HERE"; clientSecret = "INSERT_CLIENT_SECRET_HERE"; // Ensures that the client ID and client secret are not the "INSERT_..._HERE" values. Preconditions.checkArgument( !clientId.matches("INSERT_.*_HERE"), "Client ID is invalid. Please update the example and try again."); Preconditions.checkArgument( !clientSecret.matches("INSERT_.*_HERE"), "Client secret is invalid. Please update the example and try again."); } else { console.printf( "NOTE: When prompting for the client secret below, echoing will be disabled%n"); console.printf(" since the client secret is sensitive information.%n"); console.printf("Enter your client ID:%n"); clientId = console.readLine(); console.printf("Enter your client secret:%n"); clientSecret = String.valueOf(console.readPassword()); } new AuthenticateInStandaloneApplication().runExample(clientId, clientSecret); }
Example 10
Source File: EvaluationExample.java From jpmml-evaluator with GNU Affero General Public License v3.0 | 5 votes |
static private void waitForUserInput(){ Console console = System.console(); if(console == null){ throw new IllegalStateException(); } console.readLine("Press ENTER to continue"); }
Example 11
Source File: RubyConsole.java From emissary with Apache License 2.0 | 5 votes |
public void shell() { // JDK 1.6 + Console jconsole = System.console(); if (jconsole == null) { System.out.println("no tty"); return; } // Put some nice words on screen for the user System.out.println("Emissary Ruby Console v" + new emissary.util.Version()); String input; do { try { System.out.print(getPrompt()); input = jconsole.readLine(); if (input == null || input.equals("quit")) { break; } if (input.equals("reset")) { reset(); continue; } evalConsoleInput(input, true); } catch (Exception ex) { System.out.println(ex.getMessage()); } } while (true); }
Example 12
Source File: Cli.java From aion with MIT License | 5 votes |
private String getCertName(Console console) { console.printf("Enter certificate name:\n"); String certName = console.readLine(); if ((certName == null) || (certName.isEmpty())) { System.out.println("Error: no certificate name entered."); System.exit(SystemExitCodes.INITIALIZATION_ERROR); } return certName; }
Example 13
Source File: Common.java From iBioSim with Apache License 2.0 | 5 votes |
public static boolean brk(Console con) { char cmd = 'y'; prln("Do you want to continue? y/n"); while (true) { // prln("simulate " + iterations++ + " >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> "); if (con == null) { break; } String line = con.readLine(); if (line == null) { pErr("line==null"); } else if (line.length() > 0) { cmd = line.charAt(0); if (cmd == 'n' || cmd == 'y') { break; } prln("Wrong command. Try again"); } else { pErr("type 'y' OR 'n'"); } } if (cmd == 'n') { return false; } return true; }
Example 14
Source File: AddUserCommand.java From keywhiz with Apache License 2.0 | 5 votes |
@Override protected void run(Bootstrap<KeywhizConfig> bootstrap, Namespace namespace, KeywhizConfig config) throws Exception { DataSource dataSource = config.getDataSourceFactory() .build(new MetricRegistry(), "add-user-datasource"); Console console = System.console(); System.out.format("New username:"); String user = console.readLine(); System.out.format("password for '%s': ", user); char[] password = console.readPassword(); DSLContext dslContext = DSLContexts.databaseAgnostic(dataSource); new UserDAO(dslContext).createUser(user, new String(password)); }
Example 15
Source File: KMarketAccessControl.java From balana with Apache License 2.0 | 4 votes |
public static void main(String[] args){ Console console; String userName = null; String productName = null; int numberOfProducts = 1; int totalAmount = 0; printDescription(); initData(); initBalana(); System.out.println("\nYou can select one of following item for your shopping chart : \n"); System.out.println(products); if ((console = System.console()) != null){ userName = console.readLine("Enter User name : "); if(userName == null || userName.trim().length() < 1 ){ System.err.println("\nUser name can not be empty\n"); return; } String productId = console.readLine("Enter Product Id : "); if(productId == null || productId.trim().length() < 1 ){ System.err.println("\nProduct Id can not be empty\n"); return; } else { productName = idMap.get(productId); if(productName == null){ System.err.println("\nEnter valid product Id\n"); return; } } String productAmount = console.readLine("Enter No of Products : "); if(productAmount == null || productAmount.trim().length() < 1 ){ numberOfProducts = 1; } else { numberOfProducts = Integer.parseInt(productAmount); } } totalAmount = calculateTotal(productName, numberOfProducts); System.err.println("\nTotal Amount is : " + totalAmount + "\n"); String request = createXACMLRequest(userName, productName, numberOfProducts, totalAmount); //String request = createXACMLRequest("bob", "Food", 2, 40); PDP pdp = getPDPNewInstance(); System.out.println("\n======================== XACML Request ===================="); System.out.println(request); System.out.println("==========================================================="); String response = pdp.evaluate(request); System.out.println("\n======================== XACML Response ==================="); System.out.println(response); System.out.println("==========================================================="); try { ResponseCtx responseCtx = ResponseCtx.getInstance(getXacmlResponse(response)); AbstractResult result = responseCtx.getResults().iterator().next(); if(AbstractResult.DECISION_PERMIT == result.getDecision()){ System.out.println("\n" + userName + " is authorized to perform this purchase\n\n"); } else { System.out.println("\n" + userName + " is NOT authorized to perform this purchase\n"); List<Advice> advices = result.getAdvices(); for(Advice advice : advices){ List<AttributeAssignment> assignments = advice.getAssignments(); for(AttributeAssignment assignment : assignments){ System.out.println("Advice : " + assignment.getContent() +"\n\n"); } } } } catch (ParsingException e) { e.printStackTrace(); } }
Example 16
Source File: ShellCommand.java From baratine with GNU General Public License v2.0 | 4 votes |
private String readLine(Console console, String prompt) { return console.readLine(prompt); }
Example 17
Source File: RestOrderServer.java From camelinaction2 with Apache License 2.0 | 4 votes |
public static void main(String[] args) throws Exception { // create dummy backend DummyOrderService dummy = new DummyOrderService(); dummy.setupDummyOrders(); // create a Camel route that routes the REST services OrderRoute route = new OrderRoute(); route.setOrderService(dummy); // create CamelContext and add the route CamelContext camel = new DefaultCamelContext(); camel.addRoutes(route); // create a ProducerTemplate that the CXF REST service will use to integrate with Camel ProducerTemplate producer = camel.createProducerTemplate(); // create CXF REST service and inject the Camel ProducerTemplate // which we use to call the Camel route RestOrderService rest = new RestOrderService(); rest.setProducerTemplate(producer); // setup Apache CXF REST server on port 9000 JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean(); sf.setResourceClasses(RestOrderService.class); sf.setResourceProvider(RestOrderService.class, new SingletonResourceProvider(rest)); // to use jackson for json sf.setProvider(JacksonJsonProvider.class); sf.setAddress("http://localhost:9000/"); // create the CXF server Server server = sf.create(); // start Camel and CXF (non blocking) camel.start(); server.start(); // keep the JVM running Console console = System.console(); System.out.println("Server started on http://localhost:9000/"); System.out.println(""); // If you run the main class from IDEA/Eclipse then you may not have a console, which is null) if (console != null) { System.out.println(" Press ENTER to stop server"); console.readLine(); } else { System.out.println(" Stopping after 5 minutes or press ctrl + C to stop"); Thread.sleep(5 * 60 * 1000); } // stop Camel and CXF server camel.stop(); server.stop(); System.exit(0); }
Example 18
Source File: Main.java From balana with Apache License 2.0 | 4 votes |
public static void main(String[] args){ Console console; String userName = "none"; String content = "foo"; initBalana(); if ((console = System.console()) != null){ userName = console.readLine("Enter User name [bob, peter, alice] : "); if(userName == null || userName.trim().length() < 1 ){ System.err.println("\nUser name can not be empty\n"); return; } } String request = createXACMLRequest(userName, content); PDP pdp = getPDPNewInstance(); System.out.println("\n======================== XACML Request ===================="); System.out.println(request); System.out.println("==========================================================="); String response = pdp.evaluate(request); System.out.println("\n======================== XACML Response ==================="); System.out.println(response); System.out.println("==========================================================="); try { ResponseCtx responseCtx = ResponseCtx.getInstance(getXacmlResponse(response)); AbstractResult result = responseCtx.getResults().iterator().next(); if(AbstractResult.DECISION_PERMIT == result.getDecision()){ System.out.println("\n" + userName + " is authorized to perform this access\n\n"); } else { System.out.println("\n" + userName + " is NOT authorized to perform this access\n"); } } catch (ParsingException e) { e.printStackTrace(); } }
Example 19
Source File: UserCredentials.java From tutorials with MIT License | 4 votes |
public String readUsernameWithPrompt() { Console console = System.console(); return console == null ? null : // Console not available console.readLine("%s", "Enter your name: "); }
Example 20
Source File: AdvancedClassDesignChapter1Test.java From algorithms with MIT License | 3 votes |
/** * Suppose that we have the following property files and code. Which bundle is used on lines * 7 and 8, respectively? * <p> * Dolphins.properties * <p> * name=The Dolphin * age=0 * <p> * Dolphins_fr.properties * <p> * name=Dolly * <p> * Dolphins_fr_CA.properties * <p> * name=Dolly * age=4 * 5: Locale fr = new Locale("fr"); * 6: ResourceBundle b = ResourceBundle.getBundle("Dolphins", fr); * 7: b.getString("name"); * 8: b.getString("age"); * <p> * A. Dolphins.properties and Dolphins.properties * B. Dolphins.properties and Dolphins_fr.properties * C. Dolphins_fr.properties and Dolphins_fr.properties * D. Dolphins_fr.properties and Dolphins.properties * E. Dolphins_fr.properties and Dolphins_fr_CA.properties * F. Dolphins_fr_CA.properties and Dolphins_fr.properties * <p> * D is correct. File Dolphins_fr.properties exact match and has name, and age is not found, * go higher in the hierarchy to Dolphins.properties */ // --- End of Question 12. // Java 8 certification Question 13. @Test(expected = NullPointerException.class) public void testConsole() { String line; Console c = System.console(); if ((line = c.readLine()) != null) { // ! does not throw IOException. NullPointerException may be throw if console is not available // if console exists - prints what User enters System.out.println(line); } }