java.io.Console Java Examples
The following examples show how to use
java.io.Console.
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: Utils.java From micro-integrator with Apache License 2.0 | 6 votes |
/** * Retrieve value via the console * * @param msg message to display in the inquiry * @param isPassword is the requested value a password or not * @return value provided by the user */ public static String getValueFromConsole(String msg, boolean isPassword) { Console console = System.console(); if (console != null) { if (isPassword) { char[] password; if ((password = console.readPassword("[%s]", msg)) != null) { return String.valueOf(password); } } else { String value; if ((value = console.readLine("[%s]", msg)) != null) { return value; } } } throw new SecureVaultException("String cannot be null"); }
Example #2
Source File: ConsoleDemo.java From Learn-Java-12-Programming with MIT License | 6 votes |
private static void console2(){ System.out.println("\nconsole2:"); Console console = System.console(); String line = console.readLine(); System.out.println("Entered 1: " + line); line = console.readLine("Enter something 2: "); System.out.println("Entered 2: " + line); line = console.readLine("Enter some%s", "thing 3: "); System.out.println("Entered 3: " + line); char[] password = console.readPassword(); System.out.println("Entered 4: " + new String(password)); password = console.readPassword("Enter password 5: "); System.out.println("Entered 5: " + new String(password)); password = console.readPassword("Enter pass%s", "word 6: "); System.out.println("Entered 6: " + new String(password)); }
Example #3
Source File: DefaultEncrypt.java From PoseidonX with Apache License 2.0 | 6 votes |
private static String encrypt() throws IOException, StreamingException { Console console = System.console(); if (console == null) { throw new IOException("Can not get System console. maybe it running in an IDE."); } char[] passwordArray = console.readPassword(DEFAULT_CLI_TIP); if(passwordArray == null || passwordArray.length == 0) { throw new IOException("User input can not be null."); } try { return new com.huawei.streaming.encrypt.NoneEncrypt().encrypt(new String(passwordArray)); } finally { //密码使用结束之后清空密码数组 Arrays.fill(passwordArray, ' '); } }
Example #4
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 #5
Source File: VaultInteractiveSession.java From tomcat-vault with Apache License 2.0 | 6 votes |
public static char[] getSensitiveValue(String passwordPrompt) { while (true) { if (passwordPrompt == null) passwordPrompt = "Enter your password"; Console console = System.console(); char[] passwd = console.readPassword(passwordPrompt + ": "); char[] passwd1 = console.readPassword(passwordPrompt + " again: "); boolean noMatch = !Arrays.equals(passwd, passwd1); if (noMatch) System.out.println("Values entered don't match"); else { System.out.println("Values match"); return passwd; } } }
Example #6
Source File: Cli.java From aion with MIT License | 6 votes |
private String getCertPass(Console console) { int minPassLen = 7; String certPass = String.valueOf( console.readPassword( "Enter certificate password (at least " + minPassLen + " characters):\n")); if (certPass.isEmpty()) { System.out.println("Error: no certificate password entered."); System.exit(SystemExitCodes.INITIALIZATION_ERROR); } else if (certPass.length() < minPassLen) { System.out.println( "Error: certificate password must be at least " + minPassLen + " characters long."); System.exit(SystemExitCodes.INITIALIZATION_ERROR); } return certPass; }
Example #7
Source File: TerminalIo.java From tmc-cli with MIT License | 6 votes |
@Override public String readPassword(String prompt) { Console console = System.console(); if (console != null) { try { return new String(console.readPassword(prompt)); } catch (Exception e) { logger.warn("Password could not be read.", e); } } else { logger.warn("Failed to read password due to System.console()"); } println("Unable to read password securely. Reading password in cleartext."); println("Press Ctrl+C to abort"); return readLine(prompt); }
Example #8
Source File: InteractiveManager.java From hub-detect with Apache License 2.0 | 6 votes |
public void configureInInteractiveMode(InteractiveMode interactiveMode) { // TODO: Find a way to close the PrintStream without closing System.out // DO NOT CLOSE THIS STREAM, IT WILL CLOSE SYSOUT! final PrintStream interactivePrintStream = new PrintStream(System.out); final InteractiveReader interactiveReader; final Console console = System.console(); if (console != null) { interactiveReader = new ConsoleInteractiveReader(console); } else { logger.warn("It may be insecure to enter passwords because you are running in a virtual console."); interactiveReader = new ScannerInteractiveReader(System.in); } interactiveMode.init(interactivePrintStream, interactiveReader); interactiveMode.println(""); interactiveMode.println("Interactive flag found."); interactiveMode.println("Starting default interactive mode."); interactiveMode.println(""); interactiveMode.configure(); final List<InteractiveOption> interactiveOptions = interactiveMode.getInteractiveOptions(); detectOptionManager.applyInteractiveOptions(interactiveOptions); }
Example #9
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 #10
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 #11
Source File: InteractiveManager.java From synopsys-detect with Apache License 2.0 | 6 votes |
public List<InteractiveOption> configureInInteractiveMode(final InteractiveMode interactiveMode) { // Using an UncloseablePrintStream so we don't accidentally close System.out try (final PrintStream interactivePrintStream = new UncloseablePrintStream(System.out)) { final InteractiveReader interactiveReader; final Console console = System.console(); if (console != null) { interactiveReader = new ConsoleInteractiveReader(console); } else { logger.warn("It may be insecure to enter passwords because you are running in a virtual console."); interactiveReader = new ScannerInteractiveReader(System.in); } interactiveMode.init(interactivePrintStream, interactiveReader); interactiveMode.println(""); interactiveMode.println("Interactive flag found."); interactiveMode.println("Starting default interactive mode."); interactiveMode.println(""); interactiveMode.configure(); return interactiveMode.getInteractiveOptions(); } }
Example #12
Source File: Shell.java From jql with MIT License | 5 votes |
private static Console getConsole() { Console console = System.console(); if (console == null) { System.err.print("No console available."); System.exit(1); } return console; }
Example #13
Source File: ConsoleCallbackHandler.java From tutorials with MIT License | 5 votes |
@Override public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { Console console = System.console(); for (Callback callback : callbacks) { if (callback instanceof NameCallback) { NameCallback nameCallback = (NameCallback) callback; nameCallback.setName(console.readLine(nameCallback.getPrompt())); } else if (callback instanceof PasswordCallback) { PasswordCallback passwordCallback = (PasswordCallback) callback; passwordCallback.setPassword(console.readPassword(passwordCallback.getPrompt())); } else { throw new UnsupportedCallbackException(callback); } } }
Example #14
Source File: Cli.java From aion with MIT License | 5 votes |
/** For security reasons we only want the ssl option to run in a console environment. */ private void checkConsoleExists(Console console) { if (console == null) { System.out.println( "No console found. This command can only be run interactively in a console environment."); System.exit(SystemExitCodes.INITIALIZATION_ERROR); } }
Example #15
Source File: Helper.java From Entitas-Java with MIT License | 5 votes |
public static boolean getUserDecision(String accept, String cancel) { String key = ""; Console console = System.console(); Scanner scanIn = new Scanner(System.in); do { key = scanIn.nextLine(); } while (!key.equals(accept) && !key.equals(cancel)); scanIn.close(); return key == accept; }
Example #16
Source File: ConsoleUtil.java From ranger with Apache License 2.0 | 5 votes |
/** * Ask a password from console, and return as a char array. * @param prompt the question which is prompted * @return the password. */ static char[] getPasswordFromConsole(String prompt) throws IOException { char pwd[]=null; Console c = System.console(); if (c == null) { System.out.print(prompt + " "); InputStream in = System.in; int max = 50; byte[] b = new byte[max]; int l = in.read(b); l--; // last character is \n pwd=new char[l]; if (l > 0) { byte[] e = new byte[l]; System.arraycopy(b, 0, e, 0, l); for (int i = 0; i < l; i++) { pwd[i] = (char) e[i]; } } } else { pwd = c.readPassword(prompt + " "); if (pwd == null) { pwd = new char[0]; } } return pwd; }
Example #17
Source File: AbstractRunner.java From jenetics with Apache License 2.0 | 5 votes |
public void join() throws InterruptedException { if (_trialThread == null) { throw new IllegalStateException("Trial thread is not running."); } try { final Console console = System.console(); if (console != null) { final Thread interrupter = new Thread(() -> { String command; do { command = console.readLine(); Trial.info("Got command '" + command + "'"); } while (!"exit".equals(command)); Trial.info("Stopping trial..."); _trialThread.interrupt(); }); interrupter.setName("Console read thread"); interrupter.setDaemon(true); interrupter.start(); } _trialThread.join(); Trial.info("Sopped trial."); } finally { _trialThread = null; } }
Example #18
Source File: Jdk6Helper.java From gemfirexd-oss with Apache License 2.0 | 5 votes |
/** * @see JdkHelper#readChars(InputStream, boolean) */ @Override public final String readChars(final InputStream in, final boolean noecho) { final Console console; if (noecho && (console = System.console()) != null) { return new String(console.readPassword()); } else { return super.readChars(in, noecho); } }
Example #19
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 #20
Source File: WebHDFSCommand.java From knox with Apache License 2.0 | 5 votes |
private String collectClearInput(String prompt) { Console c = System.console(); if (c == null) { System.err.println("No console."); System.exit(1); } String value = c.readLine(prompt); return value; }
Example #21
Source File: ParameterFormat.java From sis with Apache License 2.0 | 5 votes |
/** * 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 UncheckedIOException(e); // Should never happen since we are writing to stdout. } INSTANCE.set(f); }
Example #22
Source File: GfxdServerLauncher.java From gemfirexd-oss with Apache License 2.0 | 5 votes |
protected void readPassword(Map<String, String> envArgs) throws Exception { final Console cons = System.console(); if (cons == null) { throw new IllegalStateException( "No console found for reading the password."); } final char[] pwd = cons.readPassword(LocalizedResource .getMessage("UTIL_password_Prompt")); if (pwd != null) { final String passwd = new String(pwd); // encrypt the password with predefined key that is salted with host IP final byte[] keyBytes = getBytesEnv(); envArgs.put(ENV1, GemFireXDUtils.encrypt(passwd, null, keyBytes)); } }
Example #23
Source File: AddUser.java From keycloak with Apache License 2.0 | 5 votes |
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); }
Example #24
Source File: Group.java From CGroup4j with Apache License 2.0 | 5 votes |
private static String readPassword() { Console console = System.console(); if (console == null) { // In Eclipse System.out.print("Password: "); BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); try { return stdin.readLine(); } catch (IOException e) { throw new RuntimeException("Failed to read password", e); } } else { // Outside Eclipse char[] pwd = console.readPassword("Password: "); return new String(pwd); } }
Example #25
Source File: ConsoleInputReader.java From obevo with Apache License 2.0 | 5 votes |
private Console getConsole(String readType) { Console console = System.console(); if (console == null) { throw new IllegalStateException("Attempting to fetch System.console() to read in [" + readType + "], but the System.console() is not available in your environment. Try entering in your login via the input arguments or use the -noPrompt argument"); } return console; }
Example #26
Source File: ShapeUtilitiesViewer.java From sis with Apache License 2.0 | 5 votes |
/** * Creates a new panel where to paint the input and output values. */ @SuppressWarnings("UseOfSystemOutOrSystemErr") private ShapeUtilitiesViewer() { setBackground(Color.BLACK); input = new Path2D.Float(); output = new Path2D.Float(); random = new Random(); final Console console = System.console(); out = (console != null) ? console.writer() : new PrintWriter(System.out); }
Example #27
Source File: InputStreamClass.java From trygve with GNU General Public License v2.0 | 5 votes |
@Override public void keyTyped(KeyEvent e) { final int c = e.getKeyChar(); try { queue.put(c); } catch (InterruptedException ex) { Logger.getLogger(Console.class.getName()). log(Level.SEVERE, null, ex); } }
Example #28
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 #29
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 #30
Source File: NodeTool.java From stratio-cassandra with Apache License 2.0 | 5 votes |
private String promptAndReadPassword() { String password = EMPTY; Console console = System.console(); if (console != null) password = String.valueOf(console.readPassword("Password:")); return password; }