List of usage examples for java.lang System console
public static Console console()
From source file:jeffaschenk.tomcat.zuul.util.KeyFileUtils.java
/** * Helper method to read a Password from the command line, * hiding input if in true terminal and not IDE. * * @param prompt - Display Prompt/* ww w .ja va 2 s .co m*/ * @return char[] - Character Array of Entered Data. */ private static char[] readPassword(String prompt) { System.out.print(prompt); if (System.console() != null) { return System.console().readPassword(); } else { try { return new BufferedReader(new InputStreamReader(System.in)).readLine().toCharArray(); } catch (IOException ioe) { return null; } } }
From source file:wptools.lib.Misc.java
/** * Get the password to use; look at environment first. * @return A string containing the password. *///from w ww. j av a 2s . c o m public static String getPassword() { String ret = System.getenv("WPTOOLS_PASS"); if (ret != null) return ret; return new String(System.console().readPassword("Password: ", (Object) null)); }
From source file:org.apache.ranger.ldapconfigcheck.CommandLineOptions.java
private void readCLI() { boolean repeat; Console console = System.console(); do {//from w ww . j a va 2s.co m repeat = false; System.out.print("Ldap url [ldap://ldap.example.com:389]: "); ldapUrl = console.readLine(); if (ldapUrl == null || ldapUrl.isEmpty()) { System.out.println("Please enter valid ldap url."); repeat = true; } } while (repeat == true); do { repeat = false; System.out.print("Bind DN [cn=admin,ou=users,dc=example,dc=com]: "); bindDn = console.readLine(); if (bindDn == null || bindDn.isEmpty()) { System.out.println("Please enter valid bindDn."); repeat = true; } } while (repeat == true); do { repeat = false; System.out.print("Bind Password: "); char[] password = console.readPassword(); bindPassword = String.valueOf(password); if (bindPassword == null || bindPassword.isEmpty()) { System.out.println("Bind Password can't be empty."); repeat = true; } } while (repeat == true); System.out.print("User Search Base [ou=users,dc=example,dc=com]: "); userSearchBase = console.readLine(); System.out.print("User Search Filter [cn=user1]: "); userSearchFilter = console.readLine(); if (isAuthEnabled) { do { repeat = false; System.out.print("Sample Authentication User [user1]: "); authUser = console.readLine(); if (authUser == null || authUser.isEmpty()) { System.out.println("Sample Authentication user must not be empty!"); repeat = true; } } while (repeat == true); do { repeat = false; System.out.print("Sample Authentication Password: "); char[] password = console.readPassword(); authPass = String.valueOf(password); if (authPass == null || authPass.isEmpty()) { System.out.println("Sample Authentication password must not be empty!"); repeat = true; } } while (repeat == true); } }
From source file:it.flavianopetrocchi.jpdfbookmarks.JPdfBookmarks.java
private byte[] askUserPassword() { //avoid the use of strings when dealing with passwords they remain in memomory Console cons;//from w w w . ja v a 2s. c o m char[] passwdChars = null; byte[] passwdBytes = null; if ((cons = System.console()) != null && (passwdChars = cons.readPassword("[%s:]", Res.getString("PASSWORD"))) != null) { passwdBytes = Ut.arrayOfCharsToArrayOfBytes(passwdChars); Arrays.fill(passwdChars, ' '); } else { out.print("[" + Res.getString("LABEL_PASSWORD") + "]"); out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); passwdChars = new char[MAX_PASSWORD_LEN]; try { int charsRead = in.read(passwdChars, 0, MAX_PASSWORD_LEN); //remove \r and \n from the password for (int i = charsRead - 1; i >= 0; i--) { if (passwdChars[i] == '\r' || passwdChars[i] == '\n') { charsRead--; } else { break; } } char[] trimmedPasswd = Arrays.copyOf(passwdChars, charsRead); Arrays.fill(passwdChars, ' '); passwdBytes = Ut.arrayOfCharsToArrayOfBytes(trimmedPasswd); Arrays.fill(trimmedPasswd, ' '); } catch (IOException ex) { } } return passwdBytes; }
From source file:org.wso2.carbon.securevault.DefaultSecretCallbackHandler.java
public void handleSingleSecretCallback(SingleSecretCallback singleSecretCallback) { if (keyStorePassWord == null && privateKeyPassWord == null) { String textFileName;//from ww w. j a v a 2 s .c om String textFileName_tmp; String textFilePersist; boolean sameKeyAndKeyStorePass = true; boolean persistPassword = false; String passwords[]; String carbonHome = System.getProperty(CARBON_HOME); String osName = System.getProperty("os.name"); if (osName.toLowerCase().indexOf("win") == -1) { textFileName = "password"; textFileName_tmp = "password-tmp"; textFilePersist = "password-persist"; } else { textFileName = "password.txt"; textFileName_tmp = "password-tmp.txt"; textFilePersist = "password-persist.txt"; } String keyPassword = System.getProperty(KEY_PASSWORD); if (keyPassword != null && keyPassword.trim().equals("true")) { sameKeyAndKeyStorePass = false; } String persistPasswordProperty = System.getProperty(PERSIST_PASSWORD); if (persistPasswordProperty != null && persistPasswordProperty.trim().equals("true")) { persistPassword = true; } keyDataFile = new File(carbonHome + File.separator + textFileName); if (keyDataFile.exists()) { passwords = readPassword(keyDataFile, sameKeyAndKeyStorePass); keyStorePassWord = passwords[0]; if (sameKeyAndKeyStorePass) { privateKeyPassWord = keyStorePassWord; } else { privateKeyPassWord = passwords[1]; } if (!persistPassword) { if (!renameConfigFile(textFileName_tmp)) { handleException("Error renaming Password config File"); } } } else { keyDataFile = new File(carbonHome + File.separator + textFileName_tmp); if (keyDataFile.exists()) { passwords = readPassword(keyDataFile, sameKeyAndKeyStorePass); keyStorePassWord = passwords[0]; if (sameKeyAndKeyStorePass) { privateKeyPassWord = keyStorePassWord; } else { privateKeyPassWord = passwords[1]; } if (!persistPassword) { if (!deleteConfigFile()) { handleException("Error deleting Password config File"); } } } else { keyDataFile = new File(carbonHome + File.separator + textFilePersist); if (keyDataFile.exists()) { passwords = readPassword(keyDataFile, sameKeyAndKeyStorePass); keyStorePassWord = passwords[0]; if (sameKeyAndKeyStorePass) { privateKeyPassWord = keyStorePassWord; } else { privateKeyPassWord = passwords[1]; } } else { Console console; char[] password; if (sameKeyAndKeyStorePass) { if ((console = System.console()) != null && (password = console.readPassword("[%s]", "Enter KeyStore and Private Key Password :")) != null) { keyStorePassWord = String.valueOf(password); privateKeyPassWord = keyStorePassWord; } } else { if ((console = System.console()) != null && (password = console.readPassword("[%s]", "Enter KeyStore Password :")) != null) { keyStorePassWord = String.valueOf(password); } if ((console = System.console()) != null && (password = console.readPassword("[%s]", "Enter Private Key Password : ")) != null) { privateKeyPassWord = String.valueOf(password); } } } } } } if (singleSecretCallback.getId().equals("identity.key.password")) { singleSecretCallback.setSecret(privateKeyPassWord); } else { singleSecretCallback.setSecret(keyStorePassWord); } }
From source file:keywhiz.cli.ClientUtils.java
/** * Read password from console.//w w w . j ava2 s . c o m * * 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. * * @return user-inputted password */ public static String readPassword() throws IOException { Console console = System.console(); if (console != null) { System.out.format("password for '%s': ", USER_NAME.value()); return String.copyValueOf(System.console().readPassword()); } else { throw new IOException( "Please login by running a command without piping.\n" + "For example: keywhiz.cli login"); } }
From source file:org.apache.chemistry.shell.Main.java
public void parseArgs(String[] args) throws IOException { if (args.length > 0) { for (int i = 0; i < args.length; i++) { String arg = args[i]; if ("-u".equals(arg)) { // username if (++i == args.length) { error("Invalid option -u without value. Username required."); }//w w w . ja v a 2 s . c om username = args[i]; } else if ("-p".equals(arg)) { // password if (++i == args.length) { error("Invalid option -p without value. Password required."); } password = args[i]; } else if ("-t".equals(arg)) { // test mode testMode = true; } else if ("--enable-time".equals(arg)) { // enable time setting by default enableTime = true; } else if ("-e".equals(arg)) { // execute mode // execute one command execMode = true; StringBuilder buf = new StringBuilder(); for (i++; i < args.length; i++) { buf.append(args[i]).append(" "); } command = buf.toString(); break; } else if ("-b".equals(arg)) { // batch mode // execute commands in the given file or if no specified // read from stdin batchMode = true; if (++i < args.length) { // read commands from a file command = args[i]; } break; } else if ("-h".equals(arg) || "--help".equals(arg)) { // help // execute help command usage(); System.exit(0); } else if (!arg.startsWith("-")) { url = arg; } else if ("-j".equals(arg)) { // use json binding useJSONBinding = true; } else if ("--compression".equals(arg)) { // use compression useCompression = true; } else if ("--version".equals(arg)) { // print actual version version(); System.exit(0); } else if ("--insecure".equals(arg)) { acceptSelfSignedCertificates(); System.setProperty("jsse.enableSNIExtension", "false"); } else { System.err.println("Skipping unknown argument: " + arg); } } if (url != null) { if (!url.contains("://")) { url = "http://" + url; } try { URL u = new URL(url); if (username == null) { String userInfo = u.getUserInfo(); if (userInfo != null) { if (userInfo.contains(":")) { int p = userInfo.indexOf(':'); username = userInfo.substring(0, p); if (password == null && p < userInfo.length() - 1) { password = userInfo.substring(p + 1); } } else { username = userInfo; } } } } catch (MalformedURLException e) { System.err.println("Malformed URL: " + e.getLocalizedMessage()); System.exit(1); } } if (url != null && username == null) { username = System.console().readLine("User: "); } if (username != null && password == null) { password = PasswordReader.read(); } } }
From source file:com.netflix.spinnaker.halyard.cli.command.v1.NestableCommand.java
/** * This recursively walks the chain of subcommands, until it finds the last in the chain, and runs executeThis. * * @see NestableCommand#executeThis()//from w ww.ja v a 2 s . com */ public void execute() { String subCommand = commander.getParsedCommand(); if (subCommand == null) { if (help) { showHelp(); } else { if (this instanceof DeprecatedCommand) { AnsiUi.warning("This command is deprecated."); AnsiUi.warning(((DeprecatedCommand) this).getDeprecatedWarning()); } if (this instanceof ProtectedCommand && !GlobalOptions.getGlobalOptions().isQuiet()) { String prompt = ((ProtectedCommand) this).getPrompt(); Console console = System.console(); String input = console.readLine(prompt + " Do you want to continue? (Y/n) "); if (!input.equalsIgnoreCase("y")) { AnsiUi.raw("Aborted."); return; } } safeExecuteThis(); } } else { subcommands.get(subCommand).execute(); } }
From source file:org.nanocom.console.Application.java
/** * Runs the current application./*w w w.ja va 2s . com*/ * * @param input An Input instance * @param output An Output instance * * @return 0 if everything went fine, or an error code */ public int doRun(InputInterface input, OutputInterface output) throws RuntimeException { String commandName = getCommandName(input); if (true == input.hasParameterOption(Arrays.asList("--ansi"))) { output.setDecorated(true); } else if (true == input.hasParameterOption(Arrays.asList("--no-ansi"))) { output.setDecorated(false); } if (true == input.hasParameterOption(Arrays.asList("--help", "-h"))) { if (null == commandName) { commandName = "help"; Map<String, String> arrayInputParams = new HashMap<String, String>(); arrayInputParams.put("command", "help"); input = new ArrayInput(arrayInputParams); } else { wantHelps = true; } } if (true == input.hasParameterOption(Arrays.asList("--no-interaction", "-n"))) { input.setInteractive(false); } if (null != System.console() && getHelperSet().has("dialog")) { // TODO // InputStream inputStream = ((DialogHelper) getHelperSet().get("dialog")).getInputStream(); /*if (!posix_isatty(inputStream)) { input.setInteractive(false); }*/ } if (true == input.hasParameterOption(Arrays.asList("--quiet", "-q"))) { output.setVerbosity(VerbosityLevel.QUIET); } else if (true == input.hasParameterOption(Arrays.asList("--verbose", "-v"))) { output.setVerbosity(VerbosityLevel.VERBOSE); } if (true == input.hasParameterOption(Arrays.asList("--version", "-V"))) { output.writeln(getLongVersion()); return 0; } if (null == commandName) { commandName = "list"; Map<String, String> arrayInputParams = new HashMap<String, String>(); arrayInputParams.put("command", "list"); input = new ArrayInput(arrayInputParams); } // The command name MUST be the first element of the input Command command = find(commandName); runningCommand = command; int statusCode = command.run(input, output); runningCommand = null; return statusCode; }
From source file:net.pflaeging.PortableSigner.SignCommandLine.java
/** Creates a new instance of CommandLine */ public SignCommandLine(String args[]) { langcodes = ""; java.util.Enumeration<String> langCodes = ResourceBundle .getBundle("net/pflaeging/PortableSigner/SignatureblockLanguages").getKeys(); while (langCodes.hasMoreElements()) { langcodes = langcodes + langCodes.nextElement() + "|"; }//from w w w .jav a 2 s . co m langcodes = langcodes.substring(0, langcodes.length() - 1); // System.out.println("Langcodes: " + langcodes); CommandLine cmd; Options options = new Options(); options.addOption("t", true, rbi18n.getString("CLI-InputFile")); options.addOption("o", true, rbi18n.getString("CLI-OutputFile")); options.addOption("s", true, rbi18n.getString("CLI-SignatureFile")); options.addOption("p", true, rbi18n.getString("CLI-Password")); options.addOption("n", false, rbi18n.getString("CLI-WithoutGUI")); options.addOption("f", false, rbi18n.getString("CLI-Finalize")); options.addOption("h", false, rbi18n.getString("CLI-Help")); options.addOption("b", true, rbi18n.getString("CLI-SigBlock") + langcodes); options.addOption("i", true, rbi18n.getString("CLI-SigImage")); options.addOption("c", true, rbi18n.getString("CLI-SigComment")); options.addOption("r", true, rbi18n.getString("CLI-SigReason")); options.addOption("l", true, rbi18n.getString("CLI-SigLocation")); options.addOption("e", true, rbi18n.getString("CLI-EmbedSignature")); options.addOption("pwdfile", true, rbi18n.getString("CLI-PasswdFile")); options.addOption("ownerpwd", true, rbi18n.getString("CLI-OwnerPasswd")); options.addOption("ownerpwdfile", true, rbi18n.getString("CLI-OwnerPasswdFile")); options.addOption("z", false, rbi18n.getString("CLI-LastPage")); CommandLineParser parser = new PosixParser(); HelpFormatter usage = new HelpFormatter(); try { cmd = parser.parse(options, args); input = cmd.getOptionValue("t", ""); output = cmd.getOptionValue("o", ""); signature = cmd.getOptionValue("s", ""); password = cmd.getOptionValue("p", ""); nogui = cmd.hasOption("n"); help = cmd.hasOption("h"); finalize = !cmd.hasOption("f"); sigblock = cmd.getOptionValue("b", ""); sigimage = cmd.getOptionValue("i", ""); comment = cmd.getOptionValue("c", ""); reason = cmd.getOptionValue("r", ""); location = cmd.getOptionValue("l", ""); embedParams = cmd.getOptionValue("e", ""); pwdFile = cmd.getOptionValue("pwdfile", ""); ownerPwdString = cmd.getOptionValue("ownerpwd", ""); ownerPwdFile = cmd.getOptionValue("ownerpwdfile", ""); lastPage = !cmd.hasOption("z"); if (cmd.getArgs().length != 0) { throw new ParseException(rbi18n.getString("CLI-UnknownArguments")); } } catch (ParseException e) { System.err.println(rbi18n.getString("CLI-WrongArguments")); usage.printHelp("PortableSigner", options); System.exit(3); } if (nogui) { if (input.equals("") || output.equals("") || signature.equals("")) { System.err.println(rbi18n.getString("CLI-MissingArguments")); usage.printHelp("PortableSigner", options); System.exit(2); } if (!help) { if (password.equals("")) { // password missing if (!pwdFile.equals("")) { // read the password from the given file try { FileInputStream pwdfis = new FileInputStream(pwdFile); byte[] pwd = new byte[1024]; password = ""; try { do { int r = pwdfis.read(pwd); if (r < 0) { break; } password += new String(pwd); password = password.trim(); } while (pwdfis.available() > 0); pwdfis.close(); } catch (IOException ex) { } } catch (FileNotFoundException fnfex) { } } else { // no password file given, read from standard input System.out.print(rbi18n.getString("CLI-MissingPassword")); Console con = System.console(); if (con == null) { byte[] pwd = new byte[1024]; password = ""; try { do { int r = System.in.read(pwd); if (r < 0) { break; } password += new String(pwd); password = password.trim(); } while (System.in.available() > 0); } catch (IOException ex) { } } else { // Console not null. Use it to read the password without echo char[] pwd = con.readPassword(); if (pwd != null) { password = new String(pwd); } } } } if (ownerPwdString.equals("") && ownerPwdFile.equals("")) { // no owner password or owner password file given, read from standard input System.out.print(rbi18n.getString("CLI-MissingOwnerPassword") + " "); Console con = System.console(); if (con == null) { byte[] pwd = new byte[1024]; String tmppassword = ""; try { do { int r = System.in.read(pwd); if (r < 0) { break; } tmppassword += new String(pwd, 0, r); tmppassword = tmppassword.trim(); } while (System.in.available() > 0); } catch (java.io.IOException ex) { // TODO: perhaps notify the user } ownerPwd = tmppassword.getBytes(); } else { // Console not null. Use it to read the password without echo char[] pwd = con.readPassword(); if (pwd != null) { ownerPwd = new byte[pwd.length]; for (int i = 0; i < pwd.length; i++) { ownerPwd[i] = (byte) pwd[i]; } } } } else if (!ownerPwdString.equals("")) { ownerPwd = ownerPwdString.getBytes(); } else if (!ownerPwdFile.equals("")) { try { FileInputStream pwdfis = new FileInputStream(ownerPwdFile); ownerPwd = new byte[0]; byte[] tmp = new byte[1024]; byte[] full; try { do { int r = pwdfis.read(tmp); if (r < 0) { break; } // trim the length: tmp = Arrays.copyOfRange(tmp, 0, r); //System.arraycopy(tmp, 0, tmp, 0, r); full = new byte[ownerPwd.length + tmp.length]; System.arraycopy(ownerPwd, 0, full, 0, ownerPwd.length); System.arraycopy(tmp, 0, full, ownerPwd.length, tmp.length); ownerPwd = full; } while (pwdfis.available() > 0); pwdfis.close(); } catch (IOException ex) { } } catch (FileNotFoundException fnfex) { } } } } if (!embedParams.equals("")) { String[] parameter = null; parameter = embedParams.split(","); try { Float vPosF = new Float(parameter[0]), lMarginF = new Float(parameter[1]), rMarginF = new Float(parameter[2]); vPos = vPosF.floatValue(); lMargin = lMarginF.floatValue(); rMargin = rMarginF.floatValue(); noSigPage = true; } catch (NumberFormatException nfe) { System.err.println(rbi18n.getString("CLI-embedParameter-Error")); usage.printHelp("PortableSigner", options); System.exit(5); } } if (!(langcodes.contains(sigblock) || sigblock.equals(""))) { System.err.println(rbi18n.getString("CLI-Only-german-english") + langcodes); usage.printHelp("PortableSigner", options); System.exit(4); } if (help) { usage.printHelp("PortableSigner", options); System.exit(1); } // System.err.println("CMDline: input: " + input); // System.err.println("CMDline: output: " + output); // System.err.println("CMDline: signature: " + signature); // System.err.println("CMDline: password: " + password); // System.err.println("CMDline: sigblock: " + sigblock); // System.err.println("CMDline: sigimage: " + sigimage); // System.err.println("CMDline: comment: " + comment); // System.err.println("CMDline: reason: " + reason); // System.err.println("CMDline: location: " + location); // System.err.println("CMDline: pwdFile: " + pwdFile); // System.err.println("CMDline: ownerPwdFile: " + ownerPwdFile); // System.err.println("CMDline: ownerPwdString: " + ownerPwdString); // System.err.println("CMDline: ownerPwd: " + ownerPwd.toString()); }