Example usage for java.io Console readLine

List of usage examples for java.io Console readLine

Introduction

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

Prototype

public String readLine(String fmt, Object... args) 

Source Link

Document

Provides a formatted prompt, then reads a single line of text from the console.

Usage

From source file:org.marketcetera.util.auth.ConsoleSetterString.java

@Override
public void setValue(Console console) {
    String value = console.readLine("%s", getPrompt().getText()); //$NON-NLS-1$
    if ((value != null) && !StringUtils.EMPTY.equals(value)) {
        getHolder().setValue(value);/*ww w.ja  va  2  s . c om*/
    }
}

From source file:org.rhq.enterprise.server.installer.Installer.java

private String ask(Console console, String prompt) {
    String response = "";
    do {//from  w  w w  .  ja v  a  2s.c o m
        response = String.valueOf(console.readLine("%s", prompt).trim());
    } while (response.isEmpty());

    return response;
}

From source file:org.dataconservancy.packaging.tool.cli.PackageGenerationApp.java

private File getOutputFile(PackageGenerationParameters params, Package pkg) {
    String name = pkg.getPackageName();
    String loc = params.getParam(GeneralParameterNames.PACKAGE_LOCATION, 0);

    File outfile = new File(loc, name);

    if (outfile.exists() && !overwriteIfExists) {
        Console c = System.console();
        String answer = "";

        if (c != null) {
            answer = c.readLine("File %s exists.  Do you wish to overwrite? (y/N) ", outfile);
        }/*from w w w.  j a v a2s . c om*/

        // if they don't want to overwrite the output, find a file to write to by appending
        // a number to it
        if (answer.isEmpty() || !answer.toLowerCase().startsWith("y")) {
            int lastDot = name.lastIndexOf(".");
            int secondDot = name.lastIndexOf(".", lastDot - 1);

            String namePart;
            String extPart;

            if (secondDot != -1 && lastDot - secondDot <= 4) {
                namePart = name.substring(0, secondDot);
                extPart = name.substring(secondDot);
            } else {
                namePart = name.substring(0, lastDot);
                extPart = name.substring(lastDot);
            }

            int i = 1;
            do {
                outfile = new File(loc, namePart + "(" + i + ")" + extPart);
                i += 1;
            } while (outfile.exists());
        }
    }

    return outfile;
}

From source file:org.rhq.server.control.RHQControl.java

private void promptForProperty(PropertiesFileUpdate pfu, Properties props, String propertiesFileName,
        String propertyName, boolean obfuscate, boolean encode, boolean hideInput) throws Exception {

    String propertyValue = props.getProperty(propertyName);
    if (StringUtil.isBlank(propertyValue)) {

        // prompt for the property value
        Console console = System.console();
        console.format("\nThe [%s] property is required but not set in [%s].\n", propertyName,
                propertiesFileName);//from   w  ww  .ja v a 2s .c om
        console.format("Do you want to set [%s] value now?\n", propertyName);
        String response = "";
        while (!(response.startsWith("n") || response.startsWith("y"))) {
            response = String.valueOf(console.readLine("%s", "yes|no: ")).toLowerCase();
        }
        if (response.startsWith("n")) {
            throw new RHQControlException("Please update the [" + propertiesFileName + "] file as required.");
        }

        do {
            propertyValue = "";
            while (StringUtil.isBlank(propertyValue)) {
                if (!hideInput) {
                    propertyValue = String.valueOf(console.readLine("%s",
                            propertyName + (((obfuscate || encode) ? " (enter as plain text): " : ": "))));
                } else {
                    propertyValue = String.valueOf(console.readPassword("%s",
                            propertyName + (((obfuscate || encode) ? " (enter as plain text): " : ": "))));
                }
            }

            if (!hideInput) {
                console.format("Is [" + propertyValue + "] correct?\n");
                response = "";
                while (!(response.startsWith("n") || response.startsWith("y"))) {
                    response = String.valueOf(console.readLine("%s", "yes|no: ")).toLowerCase();
                }
            } else {
                console.format("Confirm:\n");
                String confirmValue = String.valueOf(console.readPassword("%s",
                        propertyName + (((obfuscate || encode) ? " (enter as plain text): " : ": "))));
                response = (propertyValue.equals(confirmValue) ? "yes" : "no");
            }
        } while (response.startsWith("n"));

        propertyValue = obfuscate ? Obfuscator.encode(propertyValue) : propertyValue;
        propertyValue = encode
                ? CryptoUtil.createPasswordHash("MD5", CryptoUtil.BASE64_ENCODING, null, null, propertyValue)
                : propertyValue;
        props.setProperty(propertyName, propertyValue);
        pfu.update(props);
    }
}

From source file:org.rhq.enterprise.server.installer.Installer.java

private WhatToDo[] processArguments(String[] args) throws Exception {
    String sopts = "-:HD:h:p:e:bflt";
    LongOpt[] lopts = { new LongOpt("help", LongOpt.NO_ARGUMENT, null, 'H'),
            new LongOpt("host", LongOpt.REQUIRED_ARGUMENT, null, 'h'),
            new LongOpt("port", LongOpt.REQUIRED_ARGUMENT, null, 'p'),
            new LongOpt("encodevalue", LongOpt.NO_ARGUMENT, null, 'e'),
            new LongOpt("setupdb", LongOpt.NO_ARGUMENT, null, 'b'),
            new LongOpt("listservers", LongOpt.NO_ARGUMENT, null, 'l'),
            new LongOpt("force", LongOpt.NO_ARGUMENT, null, 'f'),
            new LongOpt("test", LongOpt.NO_ARGUMENT, null, 't') };

    boolean test = false;
    boolean listservers = false;
    boolean setupdb = false;
    String valueToEncode = null;/*from   w ww. jav a 2 s  .c o  m*/
    String associatedProperty = null;

    Getopt getopt = new Getopt("installer", args, sopts, lopts);
    int code;

    while ((code = getopt.getopt()) != -1) {
        switch (code) {
        case ':':
        case '?': {
            // for now both of these should exit
            LOG.error("Invalid option");
            return new WhatToDo[] { WhatToDo.DISPLAY_USAGE };
        }

        case 1: {
            // this will catch non-option arguments (which we don't currently support)
            LOG.error("Unknown option: " + getopt.getOptarg());
            return new WhatToDo[] { WhatToDo.DISPLAY_USAGE };
        }

        case 'H': {
            return new WhatToDo[] { WhatToDo.DISPLAY_USAGE };
        }

        case 'D': {
            // set a system property
            String sysprop = getopt.getOptarg();
            int i = sysprop.indexOf("=");
            String name;
            String value;

            if (i == -1) {
                name = sysprop;
                value = "true";
            } else {
                name = sysprop.substring(0, i);
                value = sysprop.substring(i + 1, sysprop.length());
            }

            System.setProperty(name, value);
            LOG.info("System property set: " + name + "=" + value);

            break;
        }

        case 'h': {
            String hostString = getopt.getOptarg();
            if (hostString == null) {
                throw new IllegalArgumentException("Missing host value");
            }
            this.installerConfig.setManagementHost(hostString);
            break;
        }

        case 'p': {
            String portString = getopt.getOptarg();
            if (portString == null) {
                throw new IllegalArgumentException("Missing port value");
            }
            this.installerConfig.setManagementPort(Integer.parseInt(portString));
            break;
        }

        case 'e': {
            // Prompt for the property and value to be encoded.
            // Don't use a command line option because the plain text password
            // could get captured in command history.
            Console console = System.console();
            if (null != console) {
                associatedProperty = "rhq.autoinstall.server.admin.password";
                if (!confirm(console, "Property " + associatedProperty)) {
                    associatedProperty = "rhq.server.database.password";
                    if (!confirm(console, "Property " + associatedProperty)) {
                        associatedProperty = ask(console, "Property: ");
                    }
                }

                String prompt = "Value: ";
                if (associatedProperty != null && associatedProperty.toLowerCase().contains("password")) {
                    prompt = "Password: ";
                }

                valueToEncode = String.valueOf(console.readLine("%s", prompt));
            } else {
                LOG.error("NO CONSOLE!");
            }

            break;
        }

        case 'b': {
            setupdb = true;
            break; // don't return, in case we need to allow more args
        }

        case 'f': {
            this.installerConfig.setForceInstall(true);
            break; // don't return, in case we need to allow more args
        }

        case 'l': {
            listservers = true;
            break; // don't return, we need to allow more args to be processed, like -p or -h
        }

        case 't': {
            test = true;
            break; // don't return, we need to allow more args to be processed, like -p or -h
        }
        }
    }

    // if value encoding was asked, that's all we do on the execution
    if (valueToEncode != null) {
        String encodedValue;
        if ("rhq.autoinstall.server.admin.password".equals(associatedProperty)) {
            encodedValue = CryptoUtil.createPasswordHash("MD5", CryptoUtil.BASE64_ENCODING, null, null,
                    valueToEncode);
        } else {
            encodedValue = new InstallerServiceImpl(installerConfig)
                    .obfuscatePassword(String.valueOf(valueToEncode));
        }

        System.out.println("     ");
        System.out.println("     ");

        if ("rhq.server.database.password".equals(associatedProperty)
                || "rhq.autoinstall.server.admin.password".equals(associatedProperty)
                || "rhq.storage.password".equals(associatedProperty)) {
            System.out.println("Encoded password for rhq-server.properties:");
            System.out.println("     " + associatedProperty + "=" + encodedValue);
            System.out.println("     ");
        } else {
            String prompt = "value";
            if (associatedProperty != null && associatedProperty.toLowerCase().contains("password")) {
                prompt = "password";
            }

            System.out.println("!!! WARNING !!!");
            System.out.println(
                    "Both standalone-full.xml and rhq-server.properties need to be updated if a property from rhq-server.properties is used in standalone-full.xml");
            System.out.println("!!! WARNING !!!");
            System.out.println("     ");
            System.out.println("Encoded " + prompt + " for rhq-server.properties:");
            System.out.println("     " + associatedProperty + "=RESTRICTED::" + encodedValue);
            System.out.println("     ");
            System.out.println(
                    "Encoded " + prompt + " for standalone-full.xml with selected " + prompt + " as default:");
            System.out.println("     ${VAULT::restricted::" + associatedProperty + "::" + encodedValue + "}");
            System.out.println("     ");
            System.out.println("Encoded " + prompt + " for standalone-full.xml without default:");
            System.out.println("     ${VAULT::restricted::" + associatedProperty + ":: }");
            System.out.println("     ");
            System.out.println("Encoded " + prompt + " for agent-configuration.xml:");
            System.out.println("     <entry key=\"" + associatedProperty + "\" value=\"RESTRICTED::"
                    + encodedValue + "\" />");
            System.out.println("     ");
        }

        System.out.println("Please consult the documentation for additional help.");
        System.out.println("     ");

        return new WhatToDo[] { WhatToDo.DO_NOTHING };
    }

    if (test || setupdb || listservers) {
        ArrayList<WhatToDo> whatToDo = new ArrayList<WhatToDo>();
        if (test) {
            whatToDo.add(WhatToDo.TEST);
        }
        if (setupdb) {
            whatToDo.add(WhatToDo.SETUPDB);
        }
        if (listservers) {
            whatToDo.add(WhatToDo.LIST_SERVERS);
        }
        return whatToDo.toArray(new WhatToDo[whatToDo.size()]);
    }

    return new WhatToDo[] { WhatToDo.INSTALL };
}

From source file:org.nuxeo.launcher.connect.ConnectBroker.java

/**
 * Prompt user for yes/no answer//from www . jav a  2  s .co m
 *
 * @param message The message to display
 * @param defaultValue The default answer if there's no console or if "Enter" key is pressed.
 * @param objects Parameters to use in the message (like in {@link String#format(String, Object...)})
 * @return {@code "true"} if answer is in {@link #POSITIVE_ANSWERS}, else return {@code "false"}
 */
protected String readConsole(String message, String defaultValue, Object... objects) {
    String answer;
    Console console = System.console();
    if (console == null || StringUtils.isEmpty(answer = console.readLine(message, objects))) {
        answer = defaultValue;
    }
    answer = answer.trim().toLowerCase();
    return parseAnswer(answer);
}