Example usage for java.io Console readPassword

List of usage examples for java.io Console readPassword

Introduction

In this page you can find the example usage for java.io Console readPassword.

Prototype

public char[] readPassword() 

Source Link

Document

Reads a password or passphrase from the console with echoing disabled

Usage

From source file:gov.va.isaac.mojos.profileSync.ProfilesMojoBase.java

protected String getPassword() throws MojoExecutionException {
    if (password == null) {
        password = System.getProperty(PROFILE_SYNC_PASSWORD_PROPERTY);

        //still blank, try the passed in param
        if (StringUtils.isBlank(password)) {
            password = profileSyncPassword;
        }//from   w  w  w . j a  v  a 2  s.co m

        //still no password, prompt if allowed
        if (StringUtils.isBlank(password) && !Boolean.getBoolean(PROFILE_SYNC_NO_PROMPTS)) {
            Callable<Void> callable = new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    try {
                        if (!disableHintGiven) {
                            System.out.println("To disable remote sync during build, add '-D"
                                    + PROFILE_SYNC_DISABLE + "=true' to your maven command");
                            disableHintGiven = true;
                        }
                        System.out.println("Enter the " + config_.getChangeSetUrlType().name()
                                + " password for the Profiles/Changset remote store: ("
                                + config_.getChangeSetUrl() + "):");

                        //Use console if available, for password masking
                        Console console = System.console();
                        if (console != null) {
                            password = new String(console.readPassword());
                        } else {
                            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                            password = br.readLine();
                        }
                    } catch (IOException e) {
                        throw new MojoExecutionException("Error reading password from console");
                    }
                    return null;
                }
            };

            try {
                Executors.newSingleThreadExecutor(new ThreadFactory() {
                    @Override
                    public Thread newThread(Runnable r) {
                        Thread t = new Thread(r, "User Password Prompt Thread");
                        t.setDaemon(true);
                        return t;
                    }
                }).submit(callable).get(2, TimeUnit.MINUTES);
            } catch (TimeoutException | InterruptedException e) {
                throw new MojoExecutionException("Password not provided within timeout");
            } catch (ExecutionException ee) {
                throw (ee.getCause() instanceof MojoExecutionException ? (MojoExecutionException) ee.getCause()
                        : new MojoExecutionException("Unexpected", ee.getCause()));
            }
        }
    }
    return password;
}

From source file:sh.isaac.mojo.profileSync.ProfilesMojoBase.java

/**
 * Gets the password.//from w  w  w.  j  av a  2 s .co m
 *
 * @return the password
 * @throws MojoExecutionException the mojo execution exception
 */
protected char[] getPassword() throws MojoExecutionException // protected String getPassword() throws MojoExecutionException
{
    if (pwd == null) {
        pwd = System.getProperty(PROFILE_SYNC_PWD_PROPERTY).toCharArray();

        // still blank, try the passed in param
        if (pwd.length == 0) // if (StringUtils.isBlank(pwd))
        {
            pwd = this.profileSyncPassword.toCharArray();
        }

        // still no password, prompt if allowed
        if ((pwd.length == 0) && !Boolean.valueOf(System.getProperty(PROFILE_SYNC_NO_PROMPTS))) {
            final Callable<Void> callable = () -> {
                try {
                    if (!ProfilesMojoBase.this.disableHintGiven) {
                        System.out.println("To disable remote sync during build, add '-D" + PROFILE_SYNC_DISABLE
                                + "=true' to your maven command");
                        ProfilesMojoBase.this.disableHintGiven = true;
                    }

                    System.out.println("Enter the " + ProfilesMojoBase.this.changeSetURLType
                            + " password for the Profiles/Changset remote store: ("
                            + ProfilesMojoBase.this.changeSetURL + "):");

                    // Use console if available, for password masking
                    final Console console = System.console();

                    if (console != null) {
                        pwd = console.readPassword();
                    } else {
                        final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

                        pwd = br.readLine().toCharArray();
                    }
                } catch (final IOException e) {
                    throw new MojoExecutionException("Error reading password from console");
                }

                return null;
            };

            try {
                Executors.newSingleThreadExecutor(r -> {
                    final Thread t = new Thread(r, "User Password Prompt Thread");

                    t.setDaemon(true);
                    return t;
                }).submit(callable).get(2, TimeUnit.MINUTES);
            } catch (TimeoutException | InterruptedException e) {
                throw new MojoExecutionException("Password not provided within timeout");
            } catch (final ExecutionException ee) {
                throw ((ee.getCause() instanceof MojoExecutionException)
                        ? (MojoExecutionException) ee.getCause()
                        : new MojoExecutionException("Unexpected", ee.getCause()));
            }
        }
    }

    return pwd;
}

From source file:com.netscape.cmstools.cli.MainCLI.java

public String promptForPassword(String prompt) throws IOException {
    char[] password = null;
    Console console = System.console();
    System.out.print(prompt);//from   w w  w.  ja  v  a 2  s .  c o m
    password = console.readPassword();
    return new String(password);
}

From source file:org.apache.ranger.ldapconfigcheck.CommandLineOptions.java

private void readCLI() {
    boolean repeat;
    Console console = System.console();
    do {/*from  w  w  w.  jav a  2 s  .  c om*/
        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: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 ww  w.  j av a 2 s  .  com
    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());
}

From source file:io.stallion.users.UserAdder.java

public void execute(CommandOptionsBase options, String action) throws Exception {

    Log.info("Settings: siteName {0} email password {1}", Settings.instance().getSiteName(),
            Settings.instance().getEmail().getPassword());

    Scanner scanner = new Scanner(System.in);
    Console console = System.console();

    if (empty(action)) {
        //System.out.print("Create new user or edit existing? (new/edit): ");

        //String newEdit = scanner.next();

        System.out.print("Create new user or edit existing? (new/edit): ");
        //String newEdit = console.readLine("Create new user or edit existing? (new/edit): ");
        action = scanner.nextLine();/*from   ww  w . j  a v  a 2 s  . co  m*/
    }
    User user = null;
    if ("new".equals(action)) {
        user = new User();
        user.setPredefined(true);
    } else if ("edit".equals(action)) {
        System.out.print("Enter the email, username, or ID of the user you wish to edit:");
        String idMaybe = scanner.next();
        if (StringUtils.isNumeric(idMaybe)) {
            user = (User) UserController.instance().forId(Long.parseLong(idMaybe));
        }
        if (user == null) {
            user = (User) UserController.instance().forUniqueKey("email", idMaybe);
        }
        if (user == null) {
            user = (User) UserController.instance().forUniqueKey("username", idMaybe);
        }
        if (user == null) {
            System.out.print("Could not find user for key: " + idMaybe);
            System.exit(1);
        }
    } else {
        System.out.print("Invalid choice. Choose either 'new' or 'edit'");
        System.exit(1);
    }

    System.out.print("User's given name: ");
    String givenName = scanner.nextLine();
    if (!empty(givenName)) {
        user.setGivenName(givenName);
    }

    System.out.print("User's family name: ");
    String familyName = scanner.nextLine();
    if (!empty(familyName)) {
        user.setFamilyName(familyName);
        user.setDisplayName(user.getGivenName() + " " + user.getFamilyName());
    }

    System.out.print("User's email: ");
    String email = scanner.nextLine();
    if (!empty(email)) {
        user.setEmail(email);
        user.setUsername(user.getEmail());
    }

    System.out.print("Enter password: ");
    String password = "";
    if (console != null) {
        password = new String(console.readPassword());
    } else {
        password = new String(scanner.nextLine());
    }
    //System.out.printf("password: \"%s\"\n", password);
    if (empty(password) && empty(user.getBcryptedPassword())) {
        throw new UsageException("You must set a password!");
    } else if (!empty(password)) {
        String hashed = BCrypt.hashpw(password, BCrypt.gensalt());
        user.setBcryptedPassword(hashed);
    }

    if (empty(user.getSecret())) {
        user.setSecret(RandomStringUtils.randomAlphanumeric(18));
    }
    if (empty(user.getEncryptionSecret())) {
        user.setEncryptionSecret(RandomStringUtils.randomAlphanumeric(36));
    }

    user.setPredefined(true);
    user.setRole(Role.ADMIN);
    user.setId(Context.dal().getTickets().nextId());
    user.setFilePath(GeneralUtils.slugify(user.getEmail() + "---" + user.getId().toString()) + ".json");
    UserController.instance().save(user);

    System.out.print("User saved with email " + user.getEmail() + " and id " + user.getId());

}