Example usage for java.lang System console

List of usage examples for java.lang System console

Introduction

In this page you can find the example usage for java.lang System console.

Prototype

public static Console console() 

Source Link

Document

Returns the unique java.io.Console Console object associated with the current Java virtual machine, if any.

Usage

From source file:com.keybox.common.db.DBInitServlet.java

/**
 * task init method that created DB and generated public/private keys
 *
 * @param config task config/*from ww w  . j  av  a 2  s . c o m*/
 * @throws ServletException
 */
public void init(ServletConfig config) throws ServletException {

    super.init(config);

    Connection connection = null;
    Statement statement = null;
    //check if reset ssh application key is set
    boolean resetSSHKey = "true".equals(AppConfig.getProperty("resetApplicationSSHKey"));

    //if DB password is empty generate a random
    if (StringUtils.isEmpty(AppConfig.getProperty("dbPassword"))) {
        String dbPassword = null;
        String dbPasswordConfirm = null;
        //prompt for password and confirmation
        while (dbPassword == null || !dbPassword.equals(dbPasswordConfirm)) {
            dbPassword = new String(System.console().readPassword("Please enter database password: "));
            dbPasswordConfirm = new String(System.console().readPassword("Please confirm database password: "));
            if (!dbPassword.equals(dbPasswordConfirm)) {
                System.out.println("Passwords do not match");
            }
        }
        //set password
        if (StringUtils.isNotEmpty(dbPassword)) {
            AppConfig.encryptProperty("dbPassword", dbPassword);
            //if password not set generate a random
        } else {
            System.out.println("Generating random database password");
            AppConfig.encryptProperty("dbPassword", RandomStringUtils.randomAscii(32));
        }
        //else encrypt password if plain-text
    } else if (!AppConfig.isPropertyEncrypted("dbPassword")) {
        AppConfig.encryptProperty("dbPassword", AppConfig.getProperty("dbPassword"));
    }

    try {
        connection = DBUtils.getConn();
        statement = connection.createStatement();

        ResultSet rs = statement.executeQuery(
                "select * from information_schema.tables where upper(table_name) = 'USERS' and table_schema='PUBLIC'");
        if (!rs.next()) {
            resetSSHKey = true;

            //create DB objects
            statement.executeUpdate(
                    "create table if not exists users (id INTEGER PRIMARY KEY AUTO_INCREMENT, first_nm varchar, last_nm varchar, email varchar, username varchar not null, password varchar, auth_token varchar, enabled boolean not null default true, auth_type varchar not null default '"
                            + Auth.AUTH_BASIC + "', user_type varchar not null default '" + Auth.ADMINISTRATOR
                            + "', salt varchar, otp_secret varchar)");
            statement.executeUpdate(
                    "create table if not exists user_theme (user_id INTEGER PRIMARY KEY, bg varchar(7), fg varchar(7), d1 varchar(7), d2 varchar(7), d3 varchar(7), d4 varchar(7), d5 varchar(7), d6 varchar(7), d7 varchar(7), d8 varchar(7), b1 varchar(7), b2 varchar(7), b3 varchar(7), b4 varchar(7), b5 varchar(7), b6 varchar(7), b7 varchar(7), b8 varchar(7), foreign key (user_id) references users(id) on delete cascade) ");
            statement.executeUpdate(
                    "create table if not exists system (id INTEGER PRIMARY KEY AUTO_INCREMENT, display_nm varchar not null, user varchar not null, host varchar not null, port INTEGER not null, authorized_keys varchar not null, status_cd varchar not null default 'INITIAL')");
            statement.executeUpdate(
                    "create table if not exists profiles (id INTEGER PRIMARY KEY AUTO_INCREMENT, nm varchar not null, desc varchar not null)");
            statement.executeUpdate(
                    "create table if not exists system_map (profile_id INTEGER, system_id INTEGER, foreign key (profile_id) references profiles(id) on delete cascade , foreign key (system_id) references system(id) on delete cascade, primary key (profile_id, system_id))");
            statement.executeUpdate(
                    "create table if not exists user_map (user_id INTEGER, profile_id INTEGER, foreign key (user_id) references users(id) on delete cascade, foreign key (profile_id) references profiles(id) on delete cascade, primary key (user_id, profile_id))");
            statement.executeUpdate(
                    "create table if not exists application_key (id INTEGER PRIMARY KEY AUTO_INCREMENT, public_key varchar not null, private_key varchar not null, passphrase varchar)");

            statement.executeUpdate(
                    "create table if not exists status (id INTEGER, user_id INTEGER, status_cd varchar not null default 'INITIAL', foreign key (id) references system(id) on delete cascade, foreign key (user_id) references users(id) on delete cascade, primary key(id, user_id))");
            statement.executeUpdate(
                    "create table if not exists scripts (id INTEGER PRIMARY KEY AUTO_INCREMENT, user_id INTEGER, display_nm varchar not null, script varchar not null, foreign key (user_id) references users(id) on delete cascade)");

            statement.executeUpdate(
                    "create table if not exists public_keys (id INTEGER PRIMARY KEY AUTO_INCREMENT, key_nm varchar not null, type varchar, fingerprint varchar, public_key varchar, enabled boolean not null default true, create_dt timestamp not null default CURRENT_TIMESTAMP(),  user_id INTEGER, profile_id INTEGER, foreign key (profile_id) references profiles(id) on delete cascade, foreign key (user_id) references users(id) on delete cascade)");

            statement.executeUpdate(
                    "create table if not exists session_log (id BIGINT PRIMARY KEY AUTO_INCREMENT, user_id INTEGER, session_tm timestamp default CURRENT_TIMESTAMP, foreign key (user_id) references users(id) on delete cascade )");
            statement.executeUpdate(
                    "create table if not exists terminal_log (session_id BIGINT, instance_id INTEGER, system_id INTEGER, output varchar not null, log_tm timestamp default CURRENT_TIMESTAMP, foreign key (session_id) references session_log(id) on delete cascade, foreign key (system_id) references system(id) on delete cascade)");

            //insert default admin user
            String salt = EncryptionUtil.generateSalt();
            PreparedStatement pStmt = connection.prepareStatement(
                    "insert into users (username, password, user_type, salt) values(?,?,?,?)");
            pStmt.setString(1, "admin");
            pStmt.setString(2, EncryptionUtil.hash("changeme" + salt));
            pStmt.setString(3, Auth.MANAGER);
            pStmt.setString(4, salt);
            pStmt.execute();
            DBUtils.closeStmt(pStmt);

        }
        DBUtils.closeRs(rs);

        //if reset ssh application key then generate new key
        if (resetSSHKey) {

            //delete old key entry
            PreparedStatement pStmt = connection.prepareStatement("delete from application_key");
            pStmt.execute();
            DBUtils.closeStmt(pStmt);

            //generate new key and insert passphrase
            System.out.println("Setting KeyBox SSH public/private key pair");

            //generate application pub/pvt key and get values
            String passphrase = SSHUtil.keyGen();
            String publicKey = SSHUtil.getPublicKey();
            String privateKey = SSHUtil.getPrivateKey();

            //insert new keys
            pStmt = connection.prepareStatement(
                    "insert into application_key (public_key, private_key, passphrase) values(?,?,?)");
            pStmt.setString(1, publicKey);
            pStmt.setString(2, EncryptionUtil.encrypt(privateKey));
            pStmt.setString(3, EncryptionUtil.encrypt(passphrase));
            pStmt.execute();
            DBUtils.closeStmt(pStmt);

            System.out.println("KeyBox Generated Global Public Key:");
            System.out.println(publicKey);

            //set config to default
            AppConfig.updateProperty("publicKey", "");
            AppConfig.updateProperty("privateKey", "");
            AppConfig.updateProperty("defaultSSHPassphrase", "${randomPassphrase}");

            //set to false
            AppConfig.updateProperty("resetApplicationSSHKey", "false");

        }

        //delete ssh keys
        SSHUtil.deletePvtGenSSHKey();

    } catch (Exception ex) {
        log.error(ex.toString(), ex);
    } finally {
        DBUtils.closeStmt(statement);
        DBUtils.closeConn(connection);
    }

    RefreshAuthKeyUtil.startRefreshAllSystemsTimerTask();
}

From source file:org.overlord.sramp.shell.FileShellCommandReader.java

/**
 * @see org.overlord.sramp.shell.ShellCommandReader#promptForInput(java.lang.String)
 *///www  . j a  v  a 2 s. c o m
@Override
public String promptForInput(String prompt) {
    Console console = System.console();
    if (console != null) {
        return console.readLine(prompt);
    } else {
        throw new RuntimeException(Messages.i18n.format("FileShellCommandReader.NoConsole")); //$NON-NLS-1$
    }
}

From source file:net.mybox.mybox.ClientSetup.java

/**
 * Get the initial input from the user// ww w .  j av  a  2  s .  c om
 */
private void gatherInput() {

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    String input = null;

    System.out.print("Configuration directory [" + configDir + "]: ");
    try {
        input = br.readLine();
    } catch (Exception e) {
    }
    if (!input.isEmpty())
        configDir = input;

    System.out.print("Data directory [" + account.directory + "]: ");
    try {
        input = br.readLine();
    } catch (Exception e) {
    }
    if (!input.isEmpty())
        account.directory = input;

    System.out.print("Server name [" + account.serverName + "]: ");
    try {
        input = br.readLine();
    } catch (Exception e) {
    }
    if (!input.isEmpty())
        account.serverName = input;

    System.out.print("Server port [" + account.serverPort + "]: ");
    try {
        input = br.readLine();
    } catch (Exception e) {
    }

    if (!input.isEmpty()) {
        account.serverPort = Integer.parseInt(input); //catch
    }

    Socket socket = null;
    try {
        socket = new Socket(account.serverName, account.serverPort);
    } catch (IOException e) {
        Client.printErrorExit("Unable to contact server");
    }

    System.out.print("Email [" + account.email + "]: ");
    try {
        input = br.readLine();
    } catch (Exception e) {
    }
    if (!input.isEmpty())
        account.email = input;

    Console console = System.console();

    if (console != null)
        input = new String(console.readPassword("Password [" + password + "]: "));
    else
        System.err.println("Unable to get password since not in console");

    //System.out.println("pw input : " + input);

    if (!input.isEmpty())
        password = input;
}

From source file:de.ncoder.studipsync.ui.StandardUIAdapter.java

public static UIAdapter getDefaultUIAdapter() {
    if (System.console() != null) {
        CMD.init();/*from  ww w . ja va2s. co  m*/
        return CMD;
    } else {
        SWING.init();
        return SWING;
    }
}

From source file:org.apache.hadoop.gateway.services.security.impl.CMFMasterService.java

protected void promptUser() {
    Console c = System.console();
    if (c == null) {
        System.err.println("No console.");
        System.exit(1);//from   w ww. j a  v a2  s  .c  o  m
    }

    boolean noMatch;
    do {
        char[] newPassword1 = c.readPassword("Enter master secret: ");
        char[] newPassword2 = c.readPassword("Enter master secret again: ");
        noMatch = !Arrays.equals(newPassword1, newPassword2);
        if (noMatch) {
            c.format("Passwords don't match. Try again.%n");
        } else {
            this.master = Arrays.copyOf(newPassword1, newPassword1.length);
        }
        Arrays.fill(newPassword1, ' ');
        Arrays.fill(newPassword2, ' ');
    } while (noMatch);
}

From source file:org.overlord.sramp.shell.FileShellCommandReader.java

/**
 * @see org.overlord.sramp.shell.ShellCommandReader#promptForPassword(java.lang.String)
 *//*ww w  . ja v a  2s  .co m*/
@Override
public String promptForPassword(String prompt) {
    Console console = System.console();
    if (console != null) {
        return new String(console.readPassword(prompt));
    } else {
        throw new RuntimeException(Messages.i18n.format("FileShellCommandReader.NoConsole")); //$NON-NLS-1$
    }
}

From source file:org.wildfly.security.tool.Command.java

/**
 * Prompt for interactive user input with possible confirmation of input data.
 * When data are not confirmed tool exits with {@link #INPUT_DATA_NOT_CONFIRMED} exit code
 *
 * @param echo echo the characters typed
 * @param prompt text to display before the input
 * @param confirm confirm data after the first input
 * @param confirmPrompt confirmation text
 * @return data as user inputs it/*from   ww w.j a  v  a 2 s  .c o  m*/
 * @throws Exception
 */
protected String prompt(boolean echo, String prompt, boolean confirm, String confirmPrompt) throws Exception {
    Console console = System.console();
    if (echo || console == null) {
        if (console == null && redirectionValues == null) {
            try (BufferedReader in = new BufferedReader(new InputStreamReader(System.in))) {
                redirectionValues = new ArrayList<>();
                String value;
                while ((value = in.readLine()) != null) {
                    redirectionValues.add(value);
                }
            } catch (IOException e) {
                setStatus(GENERAL_CONFIGURATION_ERROR);
                throw new Exception(e);
            }
        }
        String first = console != null ? console.readLine(prompt)
                : (redirectionValues.size() == 0 ? null : redirectionValues.remove(0));
        if (first != null && confirm) {
            String second = console != null ? console.readLine(confirmPrompt)
                    : (redirectionValues.size() == 0 ? null : redirectionValues.remove(0));
            if (first.equals(second)) {
                return first;
            } else {
                System.err.println(ElytronToolMessages.msg.inputDataNotConfirmed());
                System.exit(INPUT_DATA_NOT_CONFIRMED);
                return null;
            }
        } else {
            return first;
        }
    } else {
        char[] inVisible = console.readPassword(prompt != null ? prompt : "Password:");
        if (inVisible != null && confirm) {
            char[] inVisible2 = console
                    .readPassword(confirmPrompt != null ? confirmPrompt : "Confirm password:");
            if (Arrays.equals(inVisible, inVisible2)) {
                return new String(inVisible);
            } else {
                System.err.println(ElytronToolMessages.msg.inputDataNotConfirmed());
                System.exit(INPUT_DATA_NOT_CONFIRMED);
                return null;
            }
        }
        if (inVisible != null) {
            return new String(inVisible);
        }
        return null;
    }
}

From source file:org.apache.hadoop.gateway.services.security.impl.DefaultMasterService.java

private void promptUser() {
    Console c = System.console();
    if (c == null) {
        System.err.println("No console.");
        System.exit(1);//from  w ww . j  av a  2  s .  c  o m
    }

    boolean noMatch;
    do {
        char[] newPassword1 = c.readPassword("Enter master secret: ");
        char[] newPassword2 = c.readPassword("Enter master secret again: ");
        noMatch = !Arrays.equals(newPassword1, newPassword2);
        if (noMatch) {
            c.format("Passwords don't match. Try again.%n");
        } else {
            this.master = Arrays.copyOf(newPassword1, newPassword1.length);
        }
        Arrays.fill(newPassword1, ' ');
        Arrays.fill(newPassword2, ' ');
    } while (noMatch);
}

From source file:info.novatec.testit.livingdoc.server.rpc.runner.CommandLineRemoteRunner.java

private static String scanCredentials() {
    return String.valueOf(System.console().readPassword("Enter password: "));

}

From source file:org.wso2.carbon.identity.agent.onprem.userstore.security.DefaultSecretCallbackHandler.java

/**
 * {@inheritDoc}//from ww  w  .java 2 s . c o m
 */
public void handleSingleSecretCallback(SingleSecretCallback singleSecretCallback) {

    if (keyStorePassWord == null && privateKeyPassWord == null) {

        String textFileName;
        String passwords[];

        String productHome = System.getProperty(CommonConstants.CARBON_HOME);

        String osName = System.getProperty("os.name");
        if (!osName.toLowerCase().contains("win")) {
            textFileName = "password";
        } else {
            textFileName = "password.txt";
        }
        keyDataFile = new File(productHome + File.separator + textFileName);
        if (keyDataFile.exists()) {
            passwords = readPassword(keyDataFile);
            privateKeyPassWord = keyStorePassWord = passwords[0];
            if (!deleteConfigFile()) {
                handleException("Error deleting Password config File");
            }
        } else {
            Console console;
            char[] password;
            if ((console = System.console()) != null && (password = console.readPassword("[%s]",
                    "Enter KeyStore and Private Key Password :")) != null) {
                keyStorePassWord = String.valueOf(password);
                privateKeyPassWord = keyStorePassWord;
            }
        }
    }
    if (singleSecretCallback.getId().equals("identity.key.password")) {
        singleSecretCallback.setSecret(privateKeyPassWord);
    } else {
        singleSecretCallback.setSecret(keyStorePassWord);
    }
}