Java 类java.io.Console 实例源码

项目:BankAccount_PasaskevakosG_BootCamp3    文件:LoginScreen.java   
/**
 * ask user for Credentials
 */
private void userCredentials() {
    AdvancedEncryptionStandard myEncryption = new AdvancedEncryptionStandard();
    Scanner input = new Scanner(System.in, "utf-8");
    Console console = System.console();
    console.printf("Username: ");
    this.username = input.nextLine();

    //Password Field is not prompted
    console.printf("Password: ");
    char[] pass = console.readPassword();
    this.decryptPassword = new String(pass);
    //ecrypts input user password
    this.encryptPassword = myEncryption.encrypt(decryptPassword);
    this.password = encryptPassword;
    System.out.println();
}
项目:dataninja-smartcontent-api-sdk-java    文件:SmartContentDemo.java   
/**
 * Run through the Smart Content APIs and show usage
 */
public void process() {
    SmartContentApi client = new SmartContentClient().getClient();
    String input;

    Console cmdline = System.console();
    if (cmdline == null) {
        System.err.println("No console for command line demo.");
        System.exit(1);
    }

    // Find a Smart Data concept
    input = cmdline.readLine("Enter text to find concepts, categories or entities: ");

    System.out.println(findSmartContentDemo(client, input).toString());
}
项目:floodlight-hardware    文件:AuthTool.java   
protected void init(String[] args) {
    try {
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        System.err.println(e.getMessage());
        parser.printUsage(System.err);
        System.exit(1);
    }
    if (help) {
        parser.printUsage(System.err);
        System.exit(1);
    }
    if (!AuthScheme.NO_AUTH.equals(authScheme)) {
        if (keyStorePath == null) {
            System.err.println("keyStorePath is required when " +
                               "authScheme is " + authScheme);
            parser.printUsage(System.err);
            System.exit(1);
        }
        if (keyStorePassword == null) {
            Console con = System.console();
            char[] password = con.readPassword("Enter key store password: ");
            keyStorePassword = new String(password);
        }
    }
}
项目:light    文件:Main.java   
private void doConsole() throws Exception
{
    Console console = System.console();

    if (console != null) // IDE not support
    {
        String className = console.readLine("> ");

        CommandManager commandManager = new CommandManager();

        while (commandManager.execute(new CommandFactory().createCommand(className)))
        {
            console.printf(NEW_LINE);

            className = console.readLine("> ");
        }
    }
}
项目:identity-agent-sso    文件:Encryption.java   
/**
 * Main entry point.
 *
 * @param args The password you wanted to encrypt.
 * @throws Exception If an error occurred.
 */
public static void main(String[] args) {

    String encryptedVal;
    Console console = System.console();
    if (console == null) {
        System.err.println("Couldn't get Console instance");
        System.exit(0);
    }

    // Get the password used for encryption.
    char passwordArray[] = console.readPassword("Please Enter a password you want to use for the encryption: ");
    try {
        encryptedVal = encrypt(args[0], passwordArray);
        Files.write(Paths.get("./encrypted_password.txt"), encryptedVal.getBytes(StandardCharsets.UTF_8));
    } catch (EncryptingException | IOException ex) {
        System.err.println("Error occurred while encrypting or while writing in to the file ");
        ex.printStackTrace();
        return;
    }
    Arrays.fill(passwordArray, (char) 0);
    System.out.println("File with encrypted value created successfully in your current location");
}
项目:ACAMPController    文件:AuthTool.java   
protected void init(String[] args) {
    try {
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        System.err.println(e.getMessage());
        parser.printUsage(System.err);
        System.exit(1);
    }
    if (help) {
        parser.printUsage(System.err);
        System.exit(1);
    }
    if (!AuthScheme.NO_AUTH.equals(authScheme)) {
        if (keyStorePath == null) {
            System.err.println("keyStorePath is required when " + 
                               "authScheme is " + authScheme);
            parser.printUsage(System.err);
            System.exit(1);
        }
        if (keyStorePassword == null) {
            Console con = System.console();
            char[] password = con.readPassword("Enter key store password: ");
            keyStorePassword = new String(password);
        }
    }
}
项目:ocpjp    文件:Echo.java   
public static void main( String[] args ) {
    String str = " ";
    String[] splited = str.split( " " );
    System.out.println( "-> " + splited.length );

    Console console = System.console();
    /*
     * Se a JVM é invocada indiretamente pela IDE, ou se a JVM é invocada a
     * partir de um processo de background, então o chamada de método
     * System.console () irá falhar e retornar nulo.
     */
    if ( console == null ) {
        System.out.println(
                "Executando app de uma ide... objeto console nao recuperado" );
    }
    else {
        console.printf( console.readLine() );
    }
}
项目:ocpjp    文件:SpecialCharHandling.java   
public static void main( String[] args ) {
        double d = -19.080808;
        System.out.println( "-> " + String.valueOf( d ) );

// string tem 2 caracteres Scandinavos
        String scandString = "å, ä, and ö";
// tentando exibir caracteres scandinavos diretamente com println
        System.out.println(
                "Printing scands directly with println: " + scandString );
// agora com um objeto console
        Console console = System.console();
        if ( console != null ) {
            console.printf(
                    "Printing scands thro' console's printf method: " + scandString );
        }
    }
项目:TheMatrixProject    文件:IadCreator.java   
/**
 * Prompts the user for the password on the console
 * 
 * @param user
 *            the username
 * 
 * @return the password
 * 
 * @throws Exception
 */
private static String readPasswordFromConsole(String user) throws Exception {
    Console c = System.console();
    String password = "";

    if (c == null) {
        System.err.println("No console.");
        System.out.println(String.format("You are logging in as: " + user + "\n"));
        System.out.print(String.format("Enter the password of that user account: "));

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        password = br.readLine();
        System.out.println("");
    }
    else {
        c.format("You are logging in as: " + user + "\n");
        char[] passwordChar = c.readPassword("Enter the password of that user account: ");
        password = new String(passwordChar);
        System.out.println("");
    }

    return new String(password);
}
项目:documents4j    文件:StandaloneClient.java   
private static DocumentType[] configureConversion(Console console, Map<DocumentType, Set<DocumentType>> supportedConversions) {
    console.printf("The connected converter supports the following conversion formats:%n");
    Map<Integer, DocumentType[]> conversionsByIndex = new HashMap<Integer, DocumentType[]>();
    int index = 0;
    for (Map.Entry<DocumentType, Set<DocumentType>> entry : supportedConversions.entrySet()) {
        for (DocumentType targetType : entry.getValue()) {
            conversionsByIndex.put(index, new DocumentType[]{entry.getKey(), targetType});
            console.printf("  | [%d]: '%s' -> '%s'%n", index++, entry.getKey(), targetType);
        }
    }
    do {
        console.printf("Enter the number of the conversion you want to perform: ");
        try {
            int choice = Integer.parseInt(console.readLine());
            DocumentType[] conversion = conversionsByIndex.get(choice);
            if (conversion != null) {
                console.printf("Converting '%s' to '%s'. You can change this setup by entering '\\f'.%n", conversion[0], conversion[1]);
                return conversion;
            }
            console.printf("The number you provided is not among the legal choices%n");
        } catch (RuntimeException e) {
            console.printf("You did not provide a number%n");
        }
    } while (true);
}
项目:JavaCommon    文件:ConsoleDemo.java   
public static void main(String[] args) {
    Console console = System.console();
    if (console != null) {
        String user = new String(console.readLine("Enter User:", new Object[0]));
        String pwd = new String(console.readPassword("Enter Password:", new Object[0]));
        console.printf("User name is:%s", new Object[] { user });
        console.printf("Password is:%s", new Object[] { pwd });
    } else {
        System.out.println("No Console!");
    }
}
项目:obevo    文件:CredentialReader.java   
/**
 * @return
 */
private Credential getCredentialFromConsole(Credential credential) {
    Console cons = System.console();

    if (credential.getUsername() == null) {
        LOG.info("Enter your kerberos (or, DB user name if DB is not DACT enabled): ");
        credential.setUsername(cons.readLine());
    }

    if (!credential.isAuthenticationMethodProvided()) {
        char[] passwd = cons.readPassword("%s", "Password:");
        if (passwd != null) {
            credential.setPassword(new String(passwd));
        }
    }
    return credential;
}
项目:strongbox    文件:MFAToken.java   
public static Supplier<MFAToken> defaultMFATokenSupplier() {
    return () -> {
        Console console = System.console();

        String token = null;
        if (console != null) {
            char[] secretValue = console.readPassword("Enter MFA code: ");

            if (secretValue != null) {
                token = new String(secretValue);
            }
        } else {
            // probably running in an IDE; fallback to plaintext
            System.out.print("Enter MFA code: ");
            Scanner scanner = new Scanner(System.in);
            token = scanner.nextLine();
        }

        if (token == null || token.isEmpty()) {
            throw new InvalidInputException("A non-empty MFA code must be entered");
        }
        return new MFAToken(token);
    };
}
项目:openjdk-jdk10    文件:PasteAndMeasurementsUITest.java   
public void testPrevNextSnippet() throws Exception {
    System.setProperty(ANSI_SUPPORTED_PROPERTY, "true");
    Field cons = System.class.getDeclaredField("cons");
    cons.setAccessible(true);
    Constructor console = Console.class.getDeclaredConstructor();
    console.setAccessible(true);
    cons.set(null, console.newInstance());
    doRunTest((inputSink, out) -> {
        inputSink.write("void test1() {\nSystem.err.println(1);\n}\n" + LOC +
                        "void test2() {\nSystem.err.println(1);\n}\n" + LOC + LOC + LOC + LOC + LOC);
        waitOutput(out,       "\u001b\\[6nvoid test1\\(\\) \\{\n" +
                        "\u0006\u001b\\[6nSystem.err.println\\(1\\);\n" +
                        "\u0006\u001b\\[6n\\}\n" +
                        "\\|  created method test1\\(\\)\n" +
                        "\u0005\u001b\\[6nvoid test2\\(\\) \\{\n" +
                        "\u0006\u001b\\[6nSystem.err.println\\(1\\);\n" +
                        "\u0006\u001b\\[6n\\}\n" +
                        "\\|  created method test2\\(\\)\n" +
                        "\u0005\u001b\\[6n");
    });
}
项目:fresco_floodlight    文件:AuthTool.java   
protected void init(String[] args) {
    try {
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        System.err.println(e.getMessage());
        parser.printUsage(System.err);
        System.exit(1);
    }
    if (help) {
        parser.printUsage(System.err);
        System.exit(1);
    }
    if (!AuthScheme.NO_AUTH.equals(authScheme)) {
        if (keyStorePath == null) {
            System.err.println("keyStorePath is required when " + 
                               "authScheme is " + authScheme);
            parser.printUsage(System.err);
            System.exit(1);
        }
        if (keyStorePassword == null) {
            Console con = System.console();
            char[] password = con.readPassword("Enter key store password: ");
            keyStorePassword = new String(password);
        }
    }
}
项目:argon2-java    文件:Main.java   
public static void main(String[] args) throws IOException {

        Argon2 argon2 = Argon2ArgumentFactory.parseArguments(args);
        char[] password;
        final Console console = System.console();

        if(console != null)
            password = console.readPassword();
        else{
            password = new Scanner(System.in).next().toCharArray();
            /* UNSAFE - only for testing purposes
            like piping input into argon2 - echo password | java -jar argon2.jar saltsalt
             */
        }

        argon2.setPassword(password)
            .hash();

        argon2.printSummary();
    }
项目:iTAP-controller    文件:AuthTool.java   
protected void init(String[] args) {
    try {
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        System.err.println(e.getMessage());
        parser.printUsage(System.err);
        System.exit(1);
    }
    if (help) {
        parser.printUsage(System.err);
        System.exit(1);
    }
    if (!AuthScheme.NO_AUTH.equals(authScheme)) {
        if (keyStorePath == null) {
            System.err.println("keyStorePath is required when " + 
                               "authScheme is " + authScheme);
            parser.printUsage(System.err);
            System.exit(1);
        }
        if (keyStorePassword == null) {
            Console con = System.console();
            char[] password = con.readPassword("Enter key store password: ");
            keyStorePassword = new String(password);
        }
    }
}
项目:SDN-Multicast    文件:AuthTool.java   
protected void init(String[] args) {
    try {
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        System.err.println(e.getMessage());
        parser.printUsage(System.err);
        System.exit(1);
    }
    if (help) {
        parser.printUsage(System.err);
        System.exit(1);
    }
    if (!AuthScheme.NO_AUTH.equals(authScheme)) {
        if (keyStorePath == null) {
            System.err.println("keyStorePath is required when " + 
                               "authScheme is " + authScheme);
            parser.printUsage(System.err);
            System.exit(1);
        }
        if (keyStorePassword == null) {
            Console con = System.console();
            char[] password = con.readPassword("Enter key store password: ");
            keyStorePassword = new String(password);
        }
    }
}
项目:MCS-Master    文件:DatabaseInstallation.java   
private MongoDBConfig mongodbInstall() {
    MongoDBConfig mongoDBConfig;
    String ip;
    String port;

    do {
        Console console = System.console();
        log.info("Please enter the ip for MongoDB");
        ip = console.readLine();

        log.info("Please enter the port");
        port = console.readLine();

        mongoDBConfig = new MongoDBConfig();
        mongoDBConfig.setIp(ip);
        mongoDBConfig.setPort(port);
        log.info("Please wait");
    } while (!MongoDBConnectionTest.connectionTest(mongoDBConfig));
    return mongoDBConfig;
}
项目:bdglue    文件:SchemaDef.java   
/**
 *  Get a JDBC connection to the database.
 *  
 * @return the connection to the database
 * @throws ClassNotFoundException if the JDBC driver specified can't be found
 * @throws SQLException if a JDBC error occurs
 */
public Connection getDBConnection() throws ClassNotFoundException, SQLException {
    String driver = properties.getProperty(SchemaDefPropertyValues.JDBC_DRIVER, 
                                           "**NOT_SET**");
    String url = properties.getProperty(SchemaDefPropertyValues.JDBC_URL, 
                                        "**NOT_SET**");
    String userName = properties.getProperty(SchemaDefPropertyValues.JDBC_USER, 
                                               "**NOT_SET**");
    String password = properties.getProperty(SchemaDefPropertyValues.JDBC_PASSWORD, 
                                             "**NOT_SET**");

    Connection connection;


    if (password.equalsIgnoreCase("prompt")) {
        Console cons;
        char[] passwd;
        if ((cons = System.console()) != null && 
            (passwd = cons.readPassword("%n**********%n[%s] ", 
                                        "Enter JDBC Password:")) != null) {
            password = new String(passwd);
        }
        else {
            LOG.error("Failed to read passord from the command line");
        }
    }

    // load the class for the JDBC driver
    Class.forName(driver);

    // get the database connection
    connection = DriverManager.getConnection(url, userName, password);

    return connection;
}
项目:arscheduler    文件:AuthTool.java   
protected void init(String[] args) {
    try {
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        System.err.println(e.getMessage());
        parser.printUsage(System.err);
        System.exit(1);
    }
    if (help) {
        parser.printUsage(System.err);
        System.exit(1);
    }
    if (!AuthScheme.NO_AUTH.equals(authScheme)) {
        if (keyStorePath == null) {
            System.err.println("keyStorePath is required when " + 
                               "authScheme is " + authScheme);
            parser.printUsage(System.err);
            System.exit(1);
        }
        if (keyStorePassword == null) {
            Console con = System.console();
            char[] password = con.readPassword("Enter key store password: ");
            keyStorePassword = new String(password);
        }
    }
}
项目:JavaCurseAPI    文件:AuthTokenGenerator.java   
public static void main(String[] args) throws Exception {
    String path = System.getenv("LR");
    if (path == null || path.isEmpty()) {
        throw new RuntimeException("Bad value in environment variable");
    }

    File file = new File(path);
    file.getParentFile().mkdirs();
    Console console = System.console();

    // read username and password
    String user = console.readLine("Username: ");
    char[] passwd = console.readPassword("Password: ");

    // experiment with UserEndpoints.CredentialProvider
    MyCredentials credentials = new MyCredentials(user, passwd);
    RestUserEndpoints endpoints = new RestUserEndpoints();
    // add HttpLoggingInterceptor, log as much ask possible
    endpoints.addInterceptor(new HttpLoggingInterceptor(new MyLogger()).setLevel(HttpLoggingInterceptor.Level.BODY));
    endpoints.setupEndpoints();
    LoginResponse loginResponse = endpoints.doLogin(credentials);
    // this should be done to minimize password leakage but other parts of library must be changed to support char arrays
    Arrays.fill(passwd, '0');

    // finally save LoginResponse to disk
    String login = JsonFactory.GSON.toJson(loginResponse);
    PrintWriter writer = new PrintWriter(file);
    writer.print(login);
    writer.close();

    // just close JVM. Otherwise it will wait okio daemon timeouts
    System.exit(0);
}
项目:QD    文件:ConsoleLoginHandlerFactory.java   
@Override
public void run() {
    try {
        CONSOLE_LOCK.lockInterruptibly();
    } catch (InterruptedException e) {
        return; // don't need to login anymore -- promise was cancelled
    }
    try {
        String user = factoryUser;
        String password = factoryPassword;
        Console console = System.console();
        if (console == null) {
            Scanner scanner = new Scanner(System.in);
            System.out.println(reason);
            if (user.isEmpty()) {
                System.out.print(USER);
                user = scanner.nextLine();
            }
            if (password.isEmpty()) {
                System.out.print(PASSWORD);
                password = scanner.nextLine();
            }
        } else {
            console.format("%s%n", reason);
            if (user.isEmpty())
                user = console.readLine(USER);
            if (password.isEmpty())
                password = String.valueOf(console.readPassword(PASSWORD));
        }
        done(AuthToken.createBasicToken(user, password));
    } finally {
        CONSOLE_LOCK.unlock();
    }
}
项目:gemfirexd-oss    文件:GfxdServerLauncher.java   
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));
  }
}
项目:gemfirexd-oss    文件:Jdk6Helper.java   
/**
 * @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);
  }
}
项目:QoS-floodlight    文件:AuthTool.java   
protected void init(String[] args) {
    try {
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        System.err.println(e.getMessage());
        parser.printUsage(System.err);
        System.exit(1);
    }
    if (help) {
        parser.printUsage(System.err);
        System.exit(1);
    }
    if (!AuthScheme.NO_AUTH.equals(authScheme)) {
        if (keyStorePath == null) {
            System.err.println("keyStorePath is required when " + 
                               "authScheme is " + authScheme);
            parser.printUsage(System.err);
            System.exit(1);
        }
        if (keyStorePassword == null) {
            Console con = System.console();
            char[] password = con.readPassword("Enter key store password: ");
            keyStorePassword = new String(password);
        }
    }
}
项目:baratine    文件:ShellCommand.java   
private String readCommand(Console console, String prompt)
{
  String command = readLine(console, prompt);

  if (command == null) {
    return null;
  }

  while (command.endsWith("\\")) {
    command = command.substring(0, command.length() - 1);

    String line = readLine(console, "> ");

    if (line == null) {
      return null;
    }

    command += line;
  }

  return command;
}
项目:baratine    文件:ShellCommandOld.java   
private String readCommand(Console console, String prompt)
{
  String command = readLine(console, prompt);

  if (command == null) {
    return null;
  }

  while (command.endsWith("\\")) {
    command = command.substring(0, command.length() - 1);

    String line = readLine(console, "> ");

    if (line == null) {
      return null;
    }

    command += line;
  }

  return command;
}
项目:TACACS    文件:UserInterface.java   
/**
 * Creates an instance that prompts the console user to enter data after prompts.
 * @prompt A String prompt to be displayed for the user on the console.
 * @noEcho A boolean indicating if the user-entered text should be hidden from the console; usually for passwords.
 */
public static final UserInterface getConsoleInstance()
{
    return new UserInterface()
    {
        @Override public String getUserInput(String prompt, boolean noEcho, TAC_PLUS.AUTHEN.STATUS getWhat)
        {
            Console console = System.console();
            if (console == null) { System.out.println("No console available!"); return null; }
            System.out.println();
            System.out.print(prompt);
            String input = noEcho? new String(console.readPassword()) : console.readLine();
            if (getWhat == TAC_PLUS.AUTHEN.STATUS.GETUSER) { this.username = input; }
            return input;
        }
    };
}
项目:floodlight1.2-delay    文件:AuthTool.java   
protected void init(String[] args) {
    try {
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        System.err.println(e.getMessage());
        parser.printUsage(System.err);
        System.exit(1);
    }
    if (help) {
        parser.printUsage(System.err);
        System.exit(1);
    }
    if (!AuthScheme.NO_AUTH.equals(authScheme)) {
        if (keyStorePath == null) {
            System.err.println("keyStorePath is required when " + 
                               "authScheme is " + authScheme);
            parser.printUsage(System.err);
            System.exit(1);
        }
        if (keyStorePassword == null) {
            Console con = System.console();
            char[] password = con.readPassword("Enter key store password: ");
            keyStorePassword = new String(password);
        }
    }
}
项目:autoenroller    文件:Spire.java   
private String getPassword() {
    if(properties.getProperty("password") != null) {
        return properties.getProperty("password");
    } else {
        System.out.println("Password:");
        String password;
        Console console = System.console();
        if(console != null) {
            password = new String(console.readPassword());
        } else {
            password = new Scanner(System.in).nextLine();
        }
        System.out.println("Save password? (y/n)");
        if(new Scanner(System.in).nextLine().equals("y")) {
            properties.setProperty("password", password);
            storeProperties(properties, propertiesFile);
        }
        return password;
    }
}
项目:jql    文件:Shell.java   
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!");
}
项目:tmc-cli    文件:TerminalIo.java   
@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);
}
项目:Skool    文件:ChangePassword.java   
public void promptPassword() throws ConfigurationException {

        Console console = System.console();
        if (console == null) {
            System.out.println("Couldn't get Console instance");
            System.exit(1);
        }

        char passwordArray[] = console.readPassword("Enter the password: ");

        String passwordStr = String.valueOf(passwordArray);

        while(passwordStr.isEmpty()){
            System.out.println("Password cannot be blank ");
            passwordArray = console.readPassword("Enter the password: ");
            passwordStr = String.valueOf(passwordArray);
        }


        ChangePassword chgPassword = new ChangePassword();
        chgPassword.setPassword(passwordStr);

    }
项目:code-similarity    文件:ReadPassword.java   
public static void main(String[] args) {
    Console cons;
    if ((cons = System.console()) != null) {
        char[] passwd = null;
        try {
            passwd = cons.readPassword("Password:");
            // In real life you would send the password into authentication code
            System.out.println("Your password was: " + new String(passwd));
        } finally {
            // Shred this in-memory copy for security reasons
            if (passwd != null) {
                java.util.Arrays.fill(passwd, ' ');
            }
        }
    } else {
        throw new RuntimeException("No console, can't get password");
    }
}
项目:alda-client-java    文件:Util.java   
public static boolean promptForConfirmation(String prompt) {
  Console console = System.console();
  if (System.console() != null) {
    Boolean confirm = null;
    while (confirm == null) {
      String response = console.readLine(prompt + " (y/n) ");
      if (response.toLowerCase().startsWith("y")) {
        confirm = true;
      } else if (response.toLowerCase().startsWith("n")) {
        confirm = false;
      }
    }
    return confirm.booleanValue();
  } else {
    System.out.println(prompt + "\n");
    System.out.println("Unable to get a response because you are " +
                       "redirecting input.\nI'm just gonna assume the " +
                       "answer is no.\n\n" +
                       "To auto-respond yes, use the -y/--yes option.");
    return false;
  }
}
项目:fast-failover-demo    文件:AuthTool.java   
protected void init(String[] args) {
    try {
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        System.err.println(e.getMessage());
        parser.printUsage(System.err);
        System.exit(1);
    }
    if (help) {
        parser.printUsage(System.err);
        System.exit(1);
    }
    if (!AuthScheme.NO_AUTH.equals(authScheme)) {
        if (keyStorePath == null) {
            System.err.println("keyStorePath is required when " + 
                               "authScheme is " + authScheme);
            parser.printUsage(System.err);
            System.exit(1);
        }
        if (keyStorePassword == null) {
            Console con = System.console();
            char[] password = con.readPassword("Enter key store password: ");
            keyStorePassword = new String(password);
        }
    }
}
项目:sparrow    文件:Application.java   
public static void main(String[] args) throws IOException {
    ApplicationContext context = new AnnotationConfigApplicationContext(AppContext.class);

       logger.info("Entering application.");

    Console console = System.console();
       if (console == null) {
           logger.error("No console.");
           System.exit(1);
       }

       String name = console.readLine("Please enter your name: ");
       String emailAddress = console.readLine("Please enter your email address: ");

       logger.info(String.format("User %s entered email address: %s", name, emailAddress));

       UserService userService = context.getBean(UserService.class);
    userService.createUser(name, emailAddress);     

       logger.info("Exiting application.");
}
项目:bunkr    文件:CLIPasswordPrompt.java   
@Override
public byte[] getPassword()
{
    Console console = System.console();
    if (console == null)
    {
        System.err.println(
                "Couldn't get Console instance. You might not be in a pseudo terminal or may be " +
                "redirecting stdout or stdin in some way.\n\n" +

                "Please use the '--password-file' cli option instead in this case."
        );
        System.exit(1);
    }
    return new String(console.readPassword(this.prompt)).getBytes();
}
项目:BroadSQL-3.6.0    文件:ConsoleCmdLineGUI.java   
public String readPassword() {
    String password = null;
    Console cons;
    char[] passwd;
    try {
        if ((cons = System.console()) != null && (passwd = cons.readPassword("[%s]", "Enter password")) != null) {
            /*
            for (int i = 0; i < passwd.length; i++) {
                if (password == null) {
                    password = "";
                }
                password = password + Character.toString(passwd[i]);
            }*/
            password = String.valueOf(passwd);
        }
    } catch (IllegalFormatException ife) {
        error(new BroadSQLException(ife));
    }
    return (password);
}