Here are the examples of the java api class java.io.Console taken from open source projects.
1. AddUser#promptForInput()
Project: keycloak
File: AddUser.java
File: AddUser.java
private static String promptForInput() throws Exception { Console console = System.console(); if (console == null) { throw new Exception("Couldn't get Console instance"); } console.printf("Press ctrl-d (Unix) or ctrl-z (Windows) to exit\n"); char passwordArray[] = console.readPassword("Password: "); if (passwordArray == null) System.exit(0); return new String(passwordArray); }
2. Loader#getPassword()
Project: hmcScanner
File: Loader.java
File: Loader.java
private static String getPassword() { Console console = System.console(); if (console == null) { System.out.println("Couldn't get Console instance"); System.exit(0); } console.printf("Testing password%n"); char passwordArray[] = console.readPassword("Enter your password: "); String password = new String(passwordArray); //console.printf("Password entered was: %s%n", password); return password; }
3. KinitTool#getPassword()
Project: directory-kerby
File: KinitTool.java
File: KinitTool.java
/** * Get password for the input principal from console */ private static String getPassword(String principal) { Console console = System.console(); if (console == null) { System.out.println("Couldn't get Console instance, " + "maybe you're running this from within an IDE. " + "Use scanner to read password."); System.out.println("Password for " + principal + ":"); try (Scanner scanner = new Scanner(System.in, "UTF-8")) { return scanner.nextLine().trim(); } } console.printf("Password for " + principal + ":"); char[] passwordChars = console.readPassword(); String password = new String(passwordChars).trim(); Arrays.fill(passwordChars, ' '); return password; }
4. Credentials#prompt()
Project: lens
File: Credentials.java
File: Credentials.java
/** * Prompt. * * @return the credentials */ public static Credentials prompt() { Console console = System.console(); if (console == null) { System.err.println("Couldn't get Console instance"); System.exit(-1); } console.printf("username:"); String username = console.readLine().trim(); char[] passwordArray = console.readPassword("password for %s:", username); String password = new String(passwordArray); return new Credentials(username, password); }
5. ParameterFormat#print()
Project: sis
File: ParameterFormat.java
File: ParameterFormat.java
/** * Writes the given object to the console using a shared instance of {@code ParameterFormat}. */ @SuppressWarnings("UseOfSystemOutOrSystemErr") static void print(final Object object) { final Console console = System.console(); final Appendable out = (console != null) ? console.writer() : System.out; final ParameterFormat f = getSharedInstance(Colors.NAMING); try { f.format(object, out); } catch (IOException e) { throw new AssertionError(e); } INSTANCE.set(f); }
6. FormattableObject#print()
Project: sis
File: FormattableObject.java
File: FormattableObject.java
/** * Prints a string representation of this object to the {@linkplain System#out standard output stream}. * If a {@linkplain Console console} is attached to the running JVM (i.e. if the application is run * from the command-line and the output is not redirected to a file) and if Apache SIS thinks that * the console supports the ANSI escape codes (a.k.a. X3.64), then a syntax coloring will be applied. * * <p>This is a convenience method for debugging purpose and for console applications.</p> */ @Debug @SuppressWarnings("UseOfSystemOutOrSystemErr") public void print() { final Console console = System.console(); final PrintWriter out = (console != null) ? console.writer() : null; final String wkt = formatWKT(Convention.WKT2_SIMPLIFIED, (out != null) && X364.isAnsiSupported(), false); if (out != null) { out.println(wkt); } else { System.out.println(wkt); } }
7. Command#error()
Project: sis
File: Command.java
File: Command.java
/** * Prints the message of the given exception. This method is invoked only when the error occurred before * the {@link CommandRunner} has been built, otherwise the {@link CommandRunner#err} printer shall be used. * * @param args The command line arguments, used only for detecting if the {@code --debug} option was present. */ private static void error(final String[] args, final Exception e) { final boolean debug = ArraysExt.containsIgnoreCase(args, Option.PREFIX + "debug"); final Console console = System.console(); if (console != null) { final PrintWriter err = console.writer(); if (debug) { e.printStackTrace(err); } else { err.println(e.getLocalizedMessage()); } err.flush(); } else { @SuppressWarnings("UseOfSystemOutOrSystemErr") final PrintStream err = System.err; if (debug) { e.printStackTrace(err); } else { err.println(e.getLocalizedMessage()); } err.flush(); } }
8. BaseDatabaseConnectionOptionsParser#promptForPassword()
Project: SchemaCrawler
File: BaseDatabaseConnectionOptionsParser.java
File: BaseDatabaseConnectionOptionsParser.java
private String promptForPassword() { final Console console = System.console(); if (console == null) { LOGGER.log(Level.WARNING, "System console is not available"); return null; } try { console.format(Version.about()); final char[] passwordChars = console.readPassword("password: "); return new String(passwordChars); } catch (final Exception e) { LOGGER.log(Level.WARNING, "System console is not available", e); return null; } }
9. AddUserCommand#run()
Project: keywhiz
File: AddUserCommand.java
File: AddUserCommand.java
@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)); }
10. Main#promptForCredentialsIfMissing()
Project: flyway
File: Main.java
File: Main.java
/** * If no user or password has been provided, prompt for it. If you want to avoid the prompt, * pass in an empty user or password. * * @param properties The properties object to load to configuration into. */ private static void promptForCredentialsIfMissing(Properties properties) { Console console = System.console(); if (console == null) { // We are running in an automated build. Prompting is not possible. return; } if (!properties.containsKey("flyway.url")) { // URL is not set. We are doomed for failure anyway. return; } if (!properties.containsKey("flyway.user")) { properties.put("flyway.user", console.readLine("Database user: ")); } if (!properties.containsKey("flyway.password")) { char[] password = console.readPassword("Database password: "); properties.put("flyway.password", password == null ? "" : String.valueOf(password)); } }
11. TextApp#lookupWords()
Project: cloud-vision
File: TextApp.java
File: TextApp.java
/** * Looks up words in the index that the user enters into the console. */ public void lookupWords() { System.out.println("Entering word lookup mode."); System.out.println("To index a directory, add an input path argument when you run this command."); System.out.println(); Console console = System.console(); if (console == null) { System.err.println("No console."); System.exit(1); } while (true) { String words = console.readLine("Enter word(s) (comma-separated, leave blank to exit): ").trim(); if (words.equals("")) { break; } index.printLookup(Splitter.on(',').split(words)); } }
12. FormatMethods#main()
Project: checker-framework
File: FormatMethods.java
File: FormatMethods.java
public static void main(String... p) { Formatter f = new Formatter(); f.format("%d", 1337); f.format(Locale.GERMAN, "%d", 1337); //:: error: (argument.type.incompatible) f.format("%f", 1337); //:: error: (argument.type.incompatible) f.format(Locale.GERMAN, "%f", 1337); f.close(); String.format("%d", 1337); String.format(Locale.GERMAN, "%d", 1337); //:: error: (argument.type.incompatible) String.format("%f", 1337); //:: error: (argument.type.incompatible) String.format(Locale.GERMAN, "%f", 1337); PrintWriter pw = new PrintWriter(new ByteArrayOutputStream()); pw.format("%d", 1337); pw.format(Locale.GERMAN, "%d", 1337); pw.printf("%d", 1337); pw.printf(Locale.GERMAN, "%d", 1337); //:: error: (argument.type.incompatible) pw.format("%f", 1337); //:: error: (argument.type.incompatible) pw.format(Locale.GERMAN, "%f", 1337); //:: error: (argument.type.incompatible) pw.printf("%f", 1337); //:: error: (argument.type.incompatible) pw.printf(Locale.GERMAN, "%f", 1337); pw.close(); PrintStream ps = System.out; ps.format("%d", 1337); ps.format(Locale.GERMAN, "%d", 1337); ps.printf("%d", 1337); ps.printf(Locale.GERMAN, "%d", 1337); //:: error: (argument.type.incompatible) ps.format("%f", 1337); //:: error: (argument.type.incompatible) ps.format(Locale.GERMAN, "%f", 1337); //:: error: (argument.type.incompatible) ps.printf("%f", 1337); //:: error: (argument.type.incompatible) ps.printf(Locale.GERMAN, "%f", 1337); ps.close(); Console c = System.console(); c.format("%d", 1337); c.printf("%d", 1337); //:: error: (argument.type.incompatible) c.format("%f", 1337); //:: error: (argument.type.incompatible) c.printf("%f", 1337); }
13. DeployToWikiMojo#readInput()
Project: fabric8
File: DeployToWikiMojo.java
File: DeployToWikiMojo.java
protected String readInput(String prompt) { Console console = System.console(); System.out.print(prompt); return console.readLine(); }
14. MetadataCommand#isConsole()
Project: sis
File: MetadataCommand.java
File: MetadataCommand.java
/** * Returns {@code true} if {@link #out} is sending its output to the console. * If not, then we are probably writing to a file or the user specified his own encoding. * In such case, we will send the XML output to an {@code OutputStream} instead than to a * {@code Writer} and let the marshaller apply the encoding itself. */ private boolean isConsole() { // Special case for JUnit tests only. if (outputBuffer != null) return true; final Console console = System.console(); return (console != null) && console.writer() == out; }
15. ConsolePasswordCallbackHandler#handle()
Project: pgjdbc-ng
File: ConsolePasswordCallbackHandler.java
File: ConsolePasswordCallbackHandler.java
@Override public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { Console cons = System.console(); if (cons == null && password == null) { throw new UnsupportedCallbackException(callbacks[0], "Console is not available"); } for (int i = 0; i < callbacks.length; i++) { if (callbacks[i] instanceof PasswordCallback) { PasswordCallback passwordCallback = (PasswordCallback) callbacks[i]; if (password == null) { // It is used instead of cons.readPassword(prompt), because the prompt // may contain '%' characters passwordCallback.setPassword(cons.readPassword("%s", new Object[] { ((PasswordCallback) callbacks[i]).getPrompt() })); } else { passwordCallback.setPassword(password); } } else { throw new UnsupportedCallbackException(callbacks[i]); } } }
16. System#console()
Project: openjdk
File: System.java
File: System.java
/** * Returns the unique {@link java.io.Console Console} object associated * with the current Java virtual machine, if any. * * @return The system console, if any, otherwise {@code null}. * * @since 1.6 */ public static Console console() { Console c = cons; if (c == null) { synchronized (System.class) { cons = c = SharedSecrets.getJavaIOAccess().console(); } } return c; }
17. SimpleMySqlBackup#createNewConfigFile()
Project: MySqlBackup
File: SimpleMySqlBackup.java
File: SimpleMySqlBackup.java
public void createNewConfigFile() { // initializing variables Console con = System.console(); Scanner sc = new Scanner(con.reader()); DBData dbData = new DBData(); if (con != null) { // reading database data System.out.println(getTime() + "Configuration file don't exists, creating one, please put the connection information:"); // server address System.out.print("Server Address (localhost): "); dbData.setServerAddress(sc.next()); // port number System.out.print("Port Number (3306): "); dbData.setPortNumber(sc.next()); // database for backup System.out.print("Database for backup: "); dbData.setDatabase(sc.next()); // username System.out.print("Username (root): "); dbData.setUserName(sc.next()); // password System.out.print("Password: "); while (dbData.getPassword().isEmpty()) dbData.setPassword(sc.nextLine()); // backup folder System.out.print("Backup folder (./): "); while (true) { dbData.backupFolder = sc.nextLine(); if (dbData.backupFolder == null) continue; if (!dbData.backupFolder.isEmpty()) break; } // creating the file try { // retrieving data Properties connData = new Properties(); connData.setProperty("serveraddress", dbData.getServerAddress()); connData.setProperty("portNumber", dbData.getPortNumber()); connData.setProperty("username", dbData.getUserName()); connData.setProperty("password", dbData.getPassword()); connData.setProperty("database", dbData.getDatabase()); connData.setProperty("backupfolder", dbData.backupFolder); // store to file connData.store(new FileOutputStream(confFile), "Configuration file from MysqlBackup application with data for database connection"); } catch (IOException ioe) { System.out.println(getTime() + "Error while trying to write to the configuration file"); ioe.printStackTrace(); Thread.currentThread().interrupt(); } catch (NullPointerException npe) { System.out.println(getTime() + "Unexpected error while trying to write the connection information file"); npe.printStackTrace(); Thread.currentThread().interrupt(); } } else { System.out.println(getTime() + "Unexpected input error while trying to create the " + confFile); Thread.currentThread().interrupt(); } }
18. ClientUtils#readPassword()
Project: keywhiz
File: ClientUtils.java
File: ClientUtils.java
/** * Read password from console. * * Note that when the System.console() is null, there is no secure way of entering a password * without exposing it in the clear on the console (it is echoed onto the screen). * * For this reason, it is suggested that the user login prior to using functionality such as * input redirection since this could result in a null console. * * @param user who we are prompting a password for * @return user-inputted password */ public static char[] readPassword(String user) { Console console = System.console(); if (console != null) { System.out.format("password for '%s': ", user); return console.readPassword(); } else { throw new RuntimeException("Please login by running a command without piping.\n" + "For example: keywhiz.cli login"); } }
19. PrivateKeyProvider#askForPasswd()
Project: Jenkins2
File: PrivateKeyProvider.java
File: PrivateKeyProvider.java
private static String askForPasswd(String filePath) { Console cons = System.console(); String passwd = null; if (cons != null) { char[] p = cons.readPassword("%s", "Enter passphrase for " + filePath + ":"); passwd = String.valueOf(p); } return passwd; }
20. CommandLineMasterPasswordProvider#getCredentialManagerPasswordFromStdin()
Project: incubator-taverna-commandline
File: CommandLineMasterPasswordProvider.java
File: CommandLineMasterPasswordProvider.java
private String getCredentialManagerPasswordFromStdin() throws CommandLineMasterPasswordException { String password = null; Console console = System.console(); if (// password is being piped in, not entered in the terminal by user console == null) { BufferedReader buffReader = null; try { buffReader = new BufferedReader(new InputStreamReader(System.in)); password = buffReader.readLine(); } catch (IOException ex) { logger.error("An error occured while trying to read Credential Manager's password that was piped in: " + ex.getMessage(), ex); throw new CommandLineMasterPasswordException("An error occured while trying to read Credential Manager's password that was piped in: " + ex.getMessage(), ex); } finally { try { buffReader.close(); } catch (Exception ioe1) { } } } else // read the password from the terminal as entered by the user { try { // Block until user enters password char passwordArray[] = console.readPassword("Password for Credential Manager: "); if (// user did not abort input passwordArray != null) { password = new String(passwordArray); } // else password will be null } catch (Exception ex) { logger.error("An error occured while trying to read Credential Manager's password from the terminal: " + ex.getMessage(), ex); throw new CommandLineMasterPasswordException("An error occured while trying to read Credential Manager's password from the terminal: " + ex.getMessage(), ex); } } return password; }
21. RegexTestHarness#main()
Project: ical4j
File: RegexTestHarness.java
File: RegexTestHarness.java
public static void main(String[] args) { Console console = System.console(); if (console == null) { LOG.warn("No console."); System.exit(1); } while (true) { Pattern pattern = Pattern.compile(console.readLine("%nEnter your regex: ", new Object[] {})); Matcher matcher = pattern.matcher(console.readLine("Enter input string to search: ", new Object[] {})); boolean found = false; while (matcher.find()) { console.format("I found the text \"%s\" starting at " + "index %d and ending at index %d.%n", new Object[] { matcher.group(), Integer.valueOf(matcher.start()), Integer.valueOf(matcher.end()) }); found = true; } if (!found) { console.format("No match found.%n", new Object[] {}); } } }
22. PrivateKeyProvider#askForPasswd()
Project: hudson
File: PrivateKeyProvider.java
File: PrivateKeyProvider.java
private static String askForPasswd(String filePath) { Console cons = System.console(); String passwd = null; if (cons != null) { char[] p = cons.readPassword("%s", "Enter passphrase for " + filePath + ":"); passwd = String.valueOf(p); } return passwd; }
23. ConsoleUI#getInstance()
Project: gerrit
File: ConsoleUI.java
File: ConsoleUI.java
/** Get a UI instance, possibly forcing batch mode. */ public static ConsoleUI getInstance(final boolean batchMode) { Console console = batchMode ? null : System.console(); return console != null ? new Interactive(console) : new Batch(); }
24. DeployToWikiMojo#readPassword()
Project: fabric8
File: DeployToWikiMojo.java
File: DeployToWikiMojo.java
protected String readPassword(String prompt) { Console console = System.console(); System.out.print(prompt); char[] pw = console.readPassword(); return new String(pw); }
25. ChangePasswordCommand#getPassword()
Project: directory-kerby
File: ChangePasswordCommand.java
File: ChangePasswordCommand.java
/** * Get password from console */ private String getPassword(String principal) { String passwordOnce; String passwordTwice; Console console = System.console(); if (console == null) { System.out.println("Couldn't get Console instance, " + "maybe you're running this from within an IDE. " + "Use scanner to read password."); Scanner scanner = new Scanner(System.in, "UTF-8"); passwordOnce = getPassword(scanner, "Please enter new password \"" + principal + "\":"); passwordTwice = getPassword(scanner, "Please re-enter password =\"" + principal + "\":"); } else { passwordOnce = getPassword(console, "Please enter new password \"" + principal + "\":"); passwordTwice = getPassword(console, "Please re-enter password \"" + principal + "\":"); } if (!passwordOnce.equals(passwordTwice)) { System.err.println("change_password: Password mismatch while reading password for \"" + principal + "\"."); return null; } return passwordOnce; }
26. AddPrincipalCommand#getPassword()
Project: directory-kerby
File: AddPrincipalCommand.java
File: AddPrincipalCommand.java
/** * Get password for the input principal from console */ private String getPassword(String principal) { String passwordOnce; String passwordTwice; Console console = System.console(); if (console == null) { System.out.println("Couldn't get Console instance, " + "maybe you're running this from within an IDE. " + "Use scanner to read password."); Scanner scanner = new Scanner(System.in, "UTF-8"); passwordOnce = getPassword(scanner, "Enter password for principal \"" + principal + "\":"); passwordTwice = getPassword(scanner, "Re-enter password for principal \"" + principal + "\":"); } else { passwordOnce = getPassword(console, "Enter password for principal \"" + principal + "\":"); passwordTwice = getPassword(console, "Re-enter password for principal \"" + principal + "\":"); } if (!passwordOnce.equals(passwordTwice)) { System.err.println("add_principal: Password mismatch while reading password for \"" + principal + "\"."); return null; } return passwordOnce; }
27. CeylonVersionTool#confirm()
Project: ceylon-compiler
File: CeylonVersionTool.java
File: CeylonVersionTool.java
/** * Issues a confirmation * @param prompt * @return null means quit, empty string means no, anything else is the version string to use. * @throws IOException */ private String confirm(String msgKey, Object... args) throws IOException { if (confirm == Confirm.none) { return this.newVersion; } String version = this.newVersion; Console console = System.console(); while (true) { prompt: while (true) { // XXX Ugly: Need to replace the new version within the args array args[args.length - 1] = version; console.printf("%s", CeylonVersionMessages.msg(msgKey, args)); String ch = console.readLine(); if (ch.equals(CeylonVersionMessages.msg("mnemonic.yes"))) { return version; } else if (ch.equals(CeylonVersionMessages.msg("mnemonic.help"))) { out.append(CeylonVersionMessages.msg("help")).append(System.lineSeparator()); continue prompt; } else if (ch.equals(CeylonVersionMessages.msg("mnemonic.quit"))) { return null; } else if (ch.equals(CeylonVersionMessages.msg("mnemonic.all"))) { this.confirm = Confirm.none; return version; } else if (ch.equals(CeylonVersionMessages.msg("mnemonic.no"))) { return ""; } else if (ch.equals(CeylonVersionMessages.msg("mnemonic.edit"))) { break prompt; } else { continue prompt; } } console.printf(CeylonVersionMessages.msg("prompt.version")); version = console.readLine(); } }
28. CeylonVersionTool#confirm()
Project: ceylon
File: CeylonVersionTool.java
File: CeylonVersionTool.java
/** * Issues a confirmation * @param prompt * @return null means quit, empty string means no, anything else is the version string to use. * @throws IOException */ private String confirm(String msgKey, Object... args) throws IOException { if (confirm == Confirm.none) { return this.newVersion; } String version = this.newVersion; Console console = System.console(); while (true) { prompt: while (true) { // XXX Ugly: Need to replace the new version within the args array args[args.length - 1] = version; console.printf("%s", CeylonVersionMessages.msg(msgKey, args)); String ch = console.readLine(); if (ch.equals(CeylonVersionMessages.msg("mnemonic.yes"))) { return version; } else if (ch.equals(CeylonVersionMessages.msg("mnemonic.help"))) { out.append(CeylonVersionMessages.msg("help")).append(System.lineSeparator()); continue prompt; } else if (ch.equals(CeylonVersionMessages.msg("mnemonic.quit"))) { return null; } else if (ch.equals(CeylonVersionMessages.msg("mnemonic.all"))) { this.confirm = Confirm.none; return version; } else if (ch.equals(CeylonVersionMessages.msg("mnemonic.no"))) { return ""; } else if (ch.equals(CeylonVersionMessages.msg("mnemonic.edit"))) { break prompt; } else { continue prompt; } } console.printf(CeylonVersionMessages.msg("prompt.version")); version = console.readLine(); } }