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:org.wso2.carbon.identity.agent.userstore.security.DefaultSecretCallbackHandler.java

/**
 * {@inheritDoc}//w w  w.j  a va 2s  . 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 org.wso2.carbon.identity.agent.outbound.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);
    }
}

From source file:net.jmhertlein.alphonseirc.MSTDeskEngRunner.java

private static void loadConfig() {
    boolean read = false;
    File f = CONFIG_FILE;// ww w. j  a  va 2s  .  com
    if (!f.exists()) {
        read = true;
        try {
            f.getParentFile().mkdirs();
            f.createNewFile();
            java.nio.file.Files.setPosixFilePermissions(Paths.get(f.toURI()),
                    PosixFilePermissions.fromString("rw-------"));
        } catch (IOException ex) {
            Logger.getLogger(MSTDeskEngRunner.class.getName()).log(Level.SEVERE, null, ex);
            System.err.println("Error writing empty config.yml!");
        }
    }

    Map<String, Object> config;

    if (read) {
        Console console = System.console();
        console.printf("Nick: \n->");
        nick = console.readLine();
        console.printf("\nPassword: \n-|");
        pass = new String(console.readPassword());
        console.printf("\nServer: \n->");
        server = console.readLine();
        console.printf("\nChannels: (ex: #java,#linux,#gnome)\n->");
        channels = Arrays.asList(console.readLine().split(","));
        System.out.println("Fetching max XKCD...");
        maxXKCD = fetchMaxXKCD();
        System.out.println("Fetched.");
        cachedUTC = System.currentTimeMillis();

        dadLeaveTimes = new HashMap<>();
        noVoiceNicks = new HashSet<>();

        writeConfig();
        System.out.println("Wrote config to file: " + CONFIG_FILE.getAbsolutePath());

    } else {
        try (FileInputStream fis = new FileInputStream(f)) {
            Yaml y = new Yaml();
            config = y.loadAs(fis, Map.class);
        } catch (IOException ex) {
            Logger.getLogger(MSTDeskEngRunner.class.getName()).log(Level.SEVERE, null, ex);
            System.err.println("Error parsing config!");
            return;
        }

        nick = (String) config.get("nick");
        pass = (String) config.get("password");
        server = (String) config.get("server");
        channels = (List<String>) config.get("channels");
        maxXKCD = (Integer) config.get("cachedMaxXKCD");
        cachedUTC = (Long) config.get("cachedUTC");
        noVoiceNicks = (Set<String>) config.get("noVoiceNicks");
        masters = (Set<String>) config.get("masters");
        if (masters == null) {
            masters = new HashSet<>();
            masters.add("Everdras");
        }

        if (noVoiceNicks == null)
            noVoiceNicks = new HashSet<>();

        noVoiceNicks.stream().forEach((s) -> System.out.println("Loaded novoice nick: " + s));
        masters.stream().forEach((s) -> System.out.println("Loaded master nick: " + s));

        if (checkXKCDUpdate())
            writeConfig();
        else
            System.out.println("Loaded cached XKCD.");

        Map<String, Object> serialDadLeaveTimes = (Map<String, Object>) config.get("dadLeaveTimes");
        dadLeaveTimes = new HashMap<>();
        if (serialDadLeaveTimes != null)
            serialDadLeaveTimes.keySet().stream().forEach((time) -> {
                dadLeaveTimes.put(LocalDate.parse(time),
                        LocalTime.parse((String) serialDadLeaveTimes.get(time)));
            });

    }
}

From source file:org.miloss.fgsms.tools.DatabaseExport.java

private static String getStringPw() {
    System.out.print("Password = ");
    return new String(System.console().readPassword());
}

From source file:org.apache.gobblin.runtime.crypto.DecryptCli.java

private static String getPasswordFromConsole() {
    System.out.print("Please enter the keystore password: ");
    return new String(System.console().readPassword());
}

From source file:de.pniehus.odal.App.java

/**S
 * Parses the command line arguments//from  w  w  w.java  2 s.co  m
 * 
 * @param args
 * @param filters
 * @return
 */
public static Profile parseArgs(String[] args, List<Filter> filters) {
    boolean windowsConsole = false;

    Profile profile = new Profile(filters);

    Options options = new Options();
    Options helpOptions = new Options();

    Option profileOption = Option.builder("p").longOpt("profile").hasArg().argName("profile name")
            .desc("Loads or generates the profile with the given name").build();

    if (System.getProperty("os.name").toLowerCase().contains("windows")) {
        Console console = System.console();
        if (console != null) {
            windowsConsole = true;
            profileOption.setRequired(true);
        }
    }

    options.addOption(profileOption);
    options.addOption(Option.builder("url").hasArg().argName("url")
            .desc("Sets the url of the open directory which will be parsed and downloaded").build());
    options.addOption(Option.builder("a").longOpt("select-all").desc(
            "Downloads all available files (except the ones removed by filters), overrules the corresponding setting if a profile is used")
            .build());
    options.addOption(Option.builder("o").longOpt("outputDir").hasArg().argName("directory path").desc(
            "Sets the output directory to the given directory, overrules the corresponding setting if a profile is used")
            .build());
    options.addOption(Option.builder("w").longOpt("windows-mode")
            .desc("Enables the windows console mode on non-windows systems. Requires -url and -p to be used.")
            .build());
    Option helpOption = Option.builder("h").longOpt("help").desc("Displays this help dialog").build();

    helpOptions.addOption(helpOption);
    options.addOption(helpOption);

    CommandLineParser cliParser = new DefaultParser();

    try {
        CommandLine cmd = cliParser.parse(helpOptions, args, true);

        if (cmd.getOptions().length == 0) {
            cmd = cliParser.parse(options, args);

            if (cmd.hasOption("w")) {
                windowsConsole = true;
                if (!cmd.hasOption("p")) {
                    System.out.println("ERROR: The profile option is required for windows mode!");
                    printHelp(filters, options);
                }
            }

            if (cmd.hasOption("p")) {
                String profileName = cmd.getOptionValue("p");
                File profileFile = new File(profileName + ".odal");
                if (profileFile.exists()) {
                    try {
                        profile = Profile.loadProfile(profileName);
                        profile.setUserProfile(true);
                    } catch (IOException e) {
                        System.out.println("An error occured while loading the specified profile!");
                    }
                } else {
                    try {
                        Profile.saveProfile(profileName, profile);
                        System.out.println("The profile " + profileFile.getName() + " has been created!");
                        System.exit(0);
                    } catch (IOException e) {
                        System.out.println("An error occured during the creation of the profile "
                                + profileFile.getName() + " : " + e.getMessage());
                        System.out.println("Terminating.");
                        System.exit(1);
                    }
                }

            }

            if (cmd.hasOption("a")) {
                profile.setSelectAll(true);
            }

            if (cmd.hasOption("o")) {
                File out = new File(cmd.getOptionValue("o"));
                if (out.isDirectory() || out.canWrite()) {
                    profile.setOutputPath(out.getAbsolutePath());
                } else {
                    System.out.println(out.getAbsolutePath() + " is not a directory or not writeable!");
                    System.out.println("Terminating.");
                    System.exit(1);
                }
            }

            if (cmd.hasOption("url")) {
                profile.setUrl(cmd.getOptionValue("url"));
            } else if (windowsConsole) {
                System.out.println("ERROR: The -url argument is required for console use on windows systems.");
                printHelp(filters, options);
                System.exit(1);
            }

        } else {
            printHelp(filters, options);
            System.exit(0);
        }
    } catch (ParseException e) {
        System.out.println("\nUnable to parse command line arguments: " + e.getLocalizedMessage() + "\n");
        printHelp(filters, options);
        System.exit(1);
    }

    if (windowsConsole) {
        profile.setWindowsConsoleMode(true);
    }

    return profile;
}

From source file:com.aerospike.test.util.Args.java

public Args() {
    host = "127.0.0.1";
    port = 3000;//from   w  ww.j av  a  2 s  .c  om
    namespace = "test";
    set = "test";

    String argString = System.getProperty("args");

    if (argString == null) {
        return;
    }

    try {
        String[] args = argString.split(" ");

        Options options = new Options();
        options.addOption("h", "host", true, "Server hostname (default: localhost)");
        options.addOption("p", "port", true, "Server port (default: 3000)");
        options.addOption("U", "user", true, "User name");
        options.addOption("P", "password", true, "Password");
        options.addOption("n", "namespace", true, "Namespace (default: test)");
        options.addOption("s", "set", true, "Set name. Use 'empty' for empty set (default: demoset)");
        options.addOption("d", "debug", false, "Run in debug mode.");
        options.addOption("u", "usage", false, "Print usage.");

        CommandLineParser parser = new PosixParser();
        CommandLine cl = parser.parse(options, args, false);

        if (cl.hasOption("u")) {
            logUsage(options);
            throw new AerospikeException("Terminate after displaying usage");
        }

        host = cl.getOptionValue("h", host);
        String portString = cl.getOptionValue("p", "3000");
        port = Integer.parseInt(portString);
        namespace = cl.getOptionValue("n", namespace);
        set = cl.getOptionValue("s", "test");

        if (set.equals("empty")) {
            set = "";
        }

        user = cl.getOptionValue("U");
        password = cl.getOptionValue("P");

        if (user != null && password == null) {
            java.io.Console console = System.console();

            if (console != null) {
                char[] pass = console.readPassword("Enter password:");

                if (pass != null) {
                    password = new String(pass);
                }
            }
        }

        if (cl.hasOption("d")) {
            Log.setLevel(Level.DEBUG);
        }
    } catch (Exception ex) {
        throw new AerospikeException("Failed to parse args: " + argString);
    }
}

From source file:org.marketcetera.ors.security.ORSAdminCLI.java

/**
 * Reads the password from the console if one is available.
 *
 * @param message the password prompt to display to the user
 * /* w w w  . j a va 2 s .  c o  m*/
 * @return the password, null, if no console is available or
 * if end of stream is reached.
 */
protected char[] readPasswordFromConsole(String message) {
    Console console = System.console();
    if (console == null) {
        return null;
    } else {
        return console.readPassword(message);
    }
}

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

protected void displayWarning(boolean persisting) {
    Console c = System.console();
    if (c == null) {
        System.err.println("No console.");
        System.exit(1);/*from   w  w  w. j  a v  a 2 s.c  o  m*/
    }
    if (persisting) {
        c.printf(
                "***************************************************************************************************\n");
        c.printf(
                "You have indicated that you would like to persist the master secret for this service instance.\n");
        c.printf("Be aware that this is less secure than manually entering the secret on startup.\n");
        c.printf("The persisted file will be encrypted and primarily protected through OS permissions.\n");
        c.printf(
                "***************************************************************************************************\n");
    } else {
        c.printf(
                "***************************************************************************************************\n");
        c.printf(
                "Be aware that you will need to enter your master secret for future starts exactly as you do here.\n");
        c.printf("This secret is needed to access protected resources for the service process.\n");
        c.printf("The master secret must be protected, kept secret and not stored in clear text anywhere.\n");
        c.printf(
                "***************************************************************************************************\n");
    }
}

From source file:edu.vt.middleware.ldap.cli.AbstractCli.java

/**
 * Initialize a connection factory with command line options.
 *
 * @param  line  parsed command line arguments
 *
 * @return  connection factory that has been initialized
 *
 * @throws  Exception  if a connection config cannot be created
 *///w  w w.ja va 2s .  c o m
protected ConnectionFactory initConnectionFactory(final CommandLine line) throws Exception {
    final DefaultConnectionFactory factory = new DefaultConnectionFactory();
    final DefaultConnectionFactoryPropertySource cfSource = new DefaultConnectionFactoryPropertySource(factory,
            getPropertiesFromOptions(PropertyDomain.LDAP.value(), line));
    cfSource.initialize();
    if (factory.getConnectionConfig().getBindDn() != null
            && factory.getConnectionConfig().getBindCredential() == null) {
        // prompt the user to enter a password
        final char[] pass = System.console().readPassword("[Enter password for %s]: ",
                factory.getConnectionConfig().getBindDn());
        factory.getConnectionConfig().setBindCredential(new Credential(pass));
    }
    return factory;
}

From source file:org.apache.hadoop.gateway.hdfs.web.KnoxUrlConnectionFactory.java

private char[] promptForPassword(String prompt) {
    char[] password = null;
    Console console = System.console();
    if (console == null) {
        password = console.readPassword(prompt);
    }//from  ww  w. j  a  v a 2s  . com
    return password;
}