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.ballerinalang.containers.docker.cmd.DockerCmd.java

/**
 * Prompt user to continue Docker image building.
 *
 * @param imageName    Name of the image to be built.
 * @param imageVersion Version of the image to be built
 * @return True if confirmed, false if aborted or exceeded attempts.
 *//*from   www. j  a  v a 2  s  . co  m*/
private boolean canProceed(String imageName, String imageVersion) {
    Console console = System.console();
    String choice;
    String dockerHostToPrint = (dockerHost != null) ? dockerHost : DEFAULT_DOCKER_HOST;

    int attempts = 3;
    do {
        choice = console.readLine("Build docker image [" + imageName + ":" + imageVersion + "] in docker host ["
                + dockerHostToPrint + "]? (y/n): ");

        if (choice.equalsIgnoreCase("y")) {
            return true;
        }

        if (choice.equalsIgnoreCase("n")) {
            return false;
        }

    } while (--attempts > 0);

    return false;
}

From source file:wptools.lib.Misc.java

/**
 * Read a post body from someplace appropriate.
 * @param cmdLine  Parsed command line//from   w ww  . j a  va  2  s  .  co  m
 * @return         String containing read text
 */
public static String readBody(CommandLine cmdLine) {
    String fileName = cmdLine.getOptionValue("content");
    if (fileName == null) {
        if (System.console() == null)
            return readBodyFromFile(new InputStreamReader(System.in));
        else
            return readBodyFromTty();
    } else {
        try (FileReader fr = new FileReader(fileName)) {
            return readBodyFromFile(fr);
        } catch (IOException e) {
            Misc.die(e.getMessage());
        }
    }
    return null; // stupid Java
}

From source file:net.timbusproject.extractors.debiansoftwareextractor.CLI.java

private void printResult(JSONObject result, String append) throws ParseException, IOException, JSONException {
    if (cmd.hasOption('o') || cmd.hasOption("universe")) {
        File file = (File) (cmd.hasOption('o') ? cmd.getParsedOptionValue("o")
                : new File(result.optString("machineId", "extraction") + ".json"));
        if (append != null && !append.isEmpty())
            file = new File(file.getName().contains(".")
                    ? file.getAbsolutePath().replaceAll("(\\.[^\\.]+)$", '-' + append + "$1")
                    : file.getAbsolutePath() + append);
        overwrite: if (file.exists()) {
            getLoggerStdOut().write("File already exists. Overwrite? [y/N] ".getBytes());
            String s = System.console().readLine().trim();
            if (s.equalsIgnoreCase("y"))
                break overwrite;
            return;
        }/* ww  w  .  j  av a2s.  co  m*/
        Writer writer = new BufferedWriter(new FileWriter(file));
        if (!cmd.hasOption("universe") && cmd.hasOption('p'))
            writer.write(result.toString(2));
        else
            result.write(writer);
        writer.flush();
        writer.close();
        log.info("Saved to file: " + file.getAbsolutePath());
    } else {
        if (cmd.hasOption('p'))
            getLoggerStdOut().write(result.toString(2).getBytes());
        else
            result.write(new BufferedWriter(new OutputStreamWriter(getLoggerStdOut())));
        getLoggerStdOut().write('\n');
        getLoggerStdOut().flush();
    }
}

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

/**
 * Gets the password./* w w w  .  j a va2 s.c  om*/
 *
 * @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:org.tolven.assembler.admin.AdminAssembler.java

protected String getCommandLineRealm(CommandLine commandLine) {
    String realm = null;//w  w  w .ja v a  2  s  . co  m
    if (commandLine.getOptionValue(CMD_LINE_TOLVEN_REALM_OPTION) != null) {
        realm = commandLine.getOptionValue(CMD_LINE_TOLVEN_REALM_OPTION);
    }
    if (realm == null) {
        if (System.getenv(ENV_TOLVEN_REALM) == null) {
            System.out.print("Realm: ");
            realm = System.console().readLine();
        } else {
            realm = System.getenv(ENV_TOLVEN_REALM);
        }
    }
    return realm;
}

From source file:com.chigix.autosftp.Application.java

private static void sshOpen() throws JSchException {
    if (isOpened) {
        return;//from   w  w  w .j ava  2  s  .co  m
    }
    isOpened = true;
    Session currentSession = sshSession;
    final Properties sshConfig = new Properties();
    sshConfig.put("StrictHostKeyChecking", "no");
    for (int i = 0; i < 3; i++) {
        currentSession.setConfig(sshConfig);
        try {
            currentSession.connect();
        } catch (JSchException ex) {
            if (ex.getCause() instanceof ConnectException) {
                System.err.println("ssh: connect to host " + currentSession.getHost() + " port "
                        + currentSession.getPort() + ": " + ex.getCause().getMessage());
                System.exit(1);
            }
            if (ex.getMessage().equals("Auth fail")) {
                Console console = System.console();
                if (console == null) {
                    System.err.println(
                            "Couldn't get console instance, Please consider involving identity_file in command line.");
                    System.exit(1);
                }
                currentSession.disconnect();
                char passwordArray[] = console.readPassword("richard@192.168.2.103's password: ");
                Session newSession = new JSch().getSession(sshSession.getUserName(), sshSession.getHost(),
                        sshSession.getPort());
                newSession.setConfig(sshConfig);
                newSession.setPassword(new String(passwordArray));
                currentSession = newSession;
                continue;
            }
            Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
            return;
        }
        break;
    }
    sshSession = currentSession;
    Channel channel = sshSession.openChannel("sftp");
    channel.connect();
    sftpChannel = (ChannelSftp) channel;
    sftpChannel.setPty(false);
    if (remotePath == null) {
        try {
            remotePath = Paths.get(sftpChannel.pwd());
        } catch (SftpException ex) {
            Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
            return;
        }
    }
}

From source file:AccessControl.java

public static void main(String args[]) throws Exception {

    // init JANSI
    // (using jansi for color console output)
    AnsiConsole.systemInstall();//from  ww  w.  j  av  a 2  s .com

    // display welcome message
    AnsiConsole.out().println(Ansi.ansi().fg(Ansi.Color.CYAN).a(Ansi.Attribute.INTENSITY_BOLD)
            .a("-----------------------------------------------\n").a("\n")
            .a("Welcome to JavaOne 2013 - [[ CON7968 ]]\n").a("\n")
            .a("  Let's Get Physical: I/O Programming with\n").a("  Java on the Raspberry Pi with Pi4J\n")
            .a("\n").a("-----------------------------------------------\n")
            .a("<--Pi4J--> Security Access Example ... started.\n")
            .a("-----------------------------------------------\n").reset());

    // ******************************************************************
    // INIT & CONFIGURE LED MESSAGE READER
    // ******************************************************************

    // open the default serial port provided on the GPIO header
    // (this is where our LED reader is connected)
    serial.open(Serial.DEFAULT_COM_PORT, 2400); // 2400 BAUD, N, 8, 1

    // configure the LED message display
    // (setup pages of display text)
    configureMessage(LOADING, "<FD><CL>LOADING...");
    configureMessage(SYSTEM_READY, "<FD>SYSTEM READY");
    configureMessage(DOORBELL, "<FD><CQ>DOORBELL<FO>");
    configureMessage(DOOR_OPENED, "<FD><CK>OPENED");
    configureMessage(DOOR_CLOSED, "<FD><CE>CLOSED");
    configureMessage(APPROVED, "<FD><CL>APPROVED");
    configureMessage(DENIED, "<FD><CH>DENIED");
    configureMessage(SECURITY, "<FD><CC><SE>* SECURITY *<FO>");
    configureMessage(EMPTY, "<FD><CC> ");

    // create and register the serial data listener
    serial.addListener(new SerialDataListener() {
        @Override
        public void dataReceived(SerialDataEvent event) {
            // print out the data received to the console
            //System.out.print(event.getData());
        }
    });

    // ******************************************************************
    // INIT & START WEB SERVER  (using Jetty Web Server <embedded>)
    // ******************************************************************

    // create new jetty web server
    Server server = new Server(80);

    // create a resource handler to serve up the static html files
    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setDirectoriesListed(true);
    resourceHandler.setWelcomeFiles(new String[] { "index.html" });
    resourceHandler.setResourceBase("html");

    // create a websocket handler to allow communication from the web pages
    WebSocketHandler websocketHandler = new WebSocketHandler() {
        @Override
        public void configure(WebSocketServletFactory factory) {
            factory.register(AccessControlWebSocket.class);
        }
    };

    // create a handler collection and include all the handlers
    HandlerCollection handlerCollection = new HandlerCollection();
    handlerCollection.setHandlers(new Handler[] { websocketHandler, resourceHandler, new DefaultHandler() });
    server.setHandler(handlerCollection);

    // start the jetty web server
    server.start();

    // ******************************************************************
    // DEFINE COMPONENT LISTENERS & EVENT LOGIC
    // ******************************************************************

    // create door sensor listener
    doorSensor.addListener(new SensorListener() {
        @Override
        public void onStateChange(SensorStateChangeEvent event) {

            // display console message
            Ansi message = Ansi.ansi().fg(Ansi.Color.WHITE).a("Door sensor event: ");
            if (event.getNewState() == SensorState.OPEN) {
                message.fg(Ansi.Color.GREEN).a("--DOOR OPENED--");

                // check for a security violation
                // (this can occur if the lock solenoid is not currently engaged;
                //  this may mean that the door was forcefully opened)
                if (lockRelay.isOpen()) {
                    // set security violation to 'door-breach'
                    setSecurityViolation(SecurityViolation.DoorBreach);
                } else {
                    displayMessage(DOOR_OPENED);
                }
            } else {
                message.fg(Ansi.Color.YELLOW).a("--DOOR CLOSED--");
                displayMessage(DOOR_CLOSED);
            }
            AnsiConsole.out().println(message.reset());
        }
    });

    // create doorbell switch listener
    doorbellSwitch.addListener(new SwitchListener() {
        public void onStateChange(SwitchStateChangeEvent event) {
            if (event.getNewState() == SwitchState.ON) {

                // display console message
                AnsiConsole.out()
                        .println(Ansi.ansi().fgBright(Ansi.Color.CYAN).a("DOORBELL event triggered").reset());

                displayMessage(DOORBELL);
            }
        }
    });

    // create tamper switch listener
    tamperSwitch.addListener(new SwitchListener() {
        public void onStateChange(SwitchStateChangeEvent event) {
            // set security violation to 'tamper'
            setSecurityViolation(SecurityViolation.Tamper);
        }
    });

    // create a door lock solenoid relay listener to monitor lock/unlock events
    lockRelay.addListener(new RelayListener() {
        @Override
        public void onStateChange(RelayStateChangeEvent event) {
            // display console message
            Ansi message = Ansi.ansi().fg(Ansi.Color.WHITE).a("Door locking solenoid:    ");
            if (event.getNewState() == RelayState.CLOSED) {
                message.fg(Ansi.Color.GREEN).a("--UNLOCKED--");
            } else {
                message.fg(Ansi.Color.RED).a("--LOCKED--");
            }
            AnsiConsole.out().println(message.reset());
        }
    });

    // create keypad unlock sensor listener
    keypadUnlockSensor.addListener(new SensorListener() {
        @Override
        public void onStateChange(SensorStateChangeEvent event) {
            if (event.getNewState() == SensorState.CLOSED) {

                // first check for any security violation;
                // if a security violation exists, then we will not unlock the
                // door until the security violation has been reset/restored
                if (securityViolation != SecurityViolation.None) {

                    // display console message
                    AnsiConsole.out().println(Ansi.ansi().fg(Ansi.Color.WHITE).a("Unlock request received:  ")
                            .fgBright(Ansi.Color.RED).a("--ACCESS DENIED--").reset());

                    // display access denied message
                    displayMessage(DENIED);

                    AnsiConsole.out()
                            .println(Ansi.ansi().fgBright(Ansi.Color.YELLOW)
                                    .a("A security violation has been detected; the door will ")
                                    .a("not be unlocked until the violation is reset.").reset());

                    // send notification email to update access log
                    sendEmail(IFTTT_TAG_ACCESS_LOG, "ACCESS DENIED");
                }

                // if no security violation exists, then its safe to unlock the door
                else {
                    // display console message
                    AnsiConsole.out().println(Ansi.ansi().fg(Ansi.Color.WHITE).a("Unlock request received:  ")
                            .fgBright(Ansi.Color.GREEN).a("--ACCESS GRANTED--").reset());

                    // display access approved message
                    displayMessage(APPROVED);

                    // determine if the door is open or shut
                    // (if the door is already open, then there is
                    //  no need to engage the lock solenoid relay)
                    if (doorSensor.isOpen()) {
                        // display console message
                        AnsiConsole.out().println(Ansi.ansi().fg(Ansi.Color.YELLOW)
                                .a("Unlock bypassed; the door is already open.").reset());
                    } else {
                        // unlock the physical door by latching the
                        // solenoid relay for a few seconds
                        lockRelay.pulse(3000);
                    }

                    // send notification email to update access log
                    sendEmail(IFTTT_TAG_ACCESS_LOG, "ACCESS GRANTED");
                }
            }
        }
    });

    // create override switch listener
    overrideSwitch.addListener(new SwitchListener() {
        public void onStateChange(SwitchStateChangeEvent event) {
            if (event.getNewState() == SwitchState.ON) {

                // check for security violation
                if (securityViolation != SecurityViolation.None) {

                    // display console message
                    AnsiConsole.out().println(Ansi.ansi().fgBright(Ansi.Color.WHITE)
                            .a("Override switch requesting --RESET--").reset());

                    // check for tamper switch security violations
                    if (tamperSwitch.isOn()) {
                        // display console message
                        AnsiConsole.out()
                                .println(Ansi.ansi().fgBright(Ansi.Color.YELLOW)
                                        .a("Unable to RESET security violation; ")
                                        .a("TAMPER switch is still reporting trouble.\n")
                                        .a("Tamper trouble must be resolved to reset.").reset());
                        return;
                    }

                    // check for drop open security violations
                    if (doorSensor.isOpen()) {
                        // display console message
                        AnsiConsole.out()
                                .println(Ansi.ansi().fgBright(Ansi.Color.YELLOW)
                                        .a("Unable to RESET security violation; DOOR is still open.\n")
                                        .a("Door must be closed to reset.").reset());
                        return;
                    }

                    // reset security violation
                    setSecurityViolation(SecurityViolation.Reset);
                } else {
                    AnsiConsole.out().println(Ansi.ansi().fg(Ansi.Color.WHITE)
                            .a("Override switch requesting --UNLOCK--").reset());
                    unlock();
                }
            }
        }
    });

    // ******************************************************************
    // PROGRAM INIT LOGIC
    // ******************************************************************

    // display console message
    AnsiConsole.out().println(Ansi.ansi().fg(Ansi.Color.WHITE).a("SYSTEM READY").reset());

    // post read message to LED reader sign
    serial.write("<ID01><RPB>\r\n");

    // check for tamper switch security violations
    if (tamperSwitch.isOn()) {
        // set security violation to 'tamper'
        setSecurityViolation(SecurityViolation.Tamper);
    }

    // ******************************************************************
    // PROGRAM TERMINATION
    // ******************************************************************

    // wait for user input to terminate program
    AnsiConsole.out()
            .println(Ansi.ansi().fg(Ansi.Color.BLACK).bg(Ansi.Color.CYAN).a("PRESS [ENTER] TO EXIT").reset());
    System.console().readLine();

    // make sure the security LED is off
    securityLed.blink(0);
    securityLed.off();

    // shutdown jetty web server
    server.stop();

    // shutdown GPIO controller
    gpio.shutdown();

    // clear the display
    displayMessage(EMPTY);
    Thread.sleep(1000);

    // shutdown the serial controller
    serial.shutdown();
}

From source file:org.apache.tomcat.vault.VaultTool.java

private int execute() throws Exception {

    if (cmdLine.hasOption(HELP_PARAM)) {
        // Just print the usage. Printing summary is not required here.
        skipSummary = true;// www . j  av  a 2s  .com
        printUsage();
        return 100;
    }

    // If using the CRYPT feature without specifying a keystore, you don't need the vault
    if (cmdLine.hasOption(CRYPT) && !cmdLine.hasOption((KEYSTORE_PARAM))) {
        // Regardless of the return here, we do not need to print summary for this command option.
        // Also, if we forget setting skipSummary, the nonInteractiveSession will cause an NPE since there is no vault.
        skipSummary = true;
        if (cmdLine.getArgs().length == 2) {
            // Check to see if they tried to specify a VAULT value without a keystore :)
            if (cmdLine.getArgs()[0].startsWith("VAULT::")) {
                System.out.println("You have specified a value stored in the vault, but have not supplied the "
                        + "required vault options.");
                System.out.println(
                        "Please retry with a plain text value, or with the appropriate vault options.");
                return 100;
            }

            BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
            textEncryptor.setPassword(cmdLine.getArgs()[0]);
            System.out.println("Encrypted value: CRYPT::" + textEncryptor.encrypt(cmdLine.getArgs()[1]));
            return 0;
        } else {
            System.out.println("Arguments: encryption password, value to encrypt");
            return 100;
        }
    }

    String keystoreURL = cmdLine.getOptionValue(KEYSTORE_PARAM, "vault.keystore");
    String keystorePassword = cmdLine.getOptionValue(KEYSTORE_PASSWORD_PARAM, "");
    if (!cmdLine.hasOption(KEYSTORE_PASSWORD_PARAM)) {
        keystorePassword = new String(System.console().readPassword("Enter keystore password: "));
    }

    String encryptionDirectory = cmdLine.getOptionValue(ENC_DIR_PARAM, "vault");
    String salt = cmdLine.getOptionValue(SALT_PARAM, "12345678");
    int iterationCount = Integer.parseInt(cmdLine.getOptionValue(ITERATION_PARAM, "23"));

    nonInteractiveSession = new VaultSession(keystoreURL, keystorePassword, encryptionDirectory, salt,
            iterationCount);

    nonInteractiveSession.startVaultSession(cmdLine.getOptionValue(ALIAS_PARAM, "vault"));

    String vaultBlock = cmdLine.getOptionValue(VAULT_BLOCK_PARAM, "vb");
    String attributeName = cmdLine.getOptionValue(ATTRIBUTE_PARAM, "password");

    if (cmdLine.hasOption(CHECK_SEC_ATTR_EXISTS_PARAM)) {
        // check password
        if (nonInteractiveSession.checkSecuredAttribute(vaultBlock, attributeName)) {
            System.out.println("Secured attribute already exists.");
            return 0;
        } else {
            System.out.println("Secured attribute does not exist.");
            return 5;
        }
    } else if (cmdLine.hasOption(SEC_ATTR_VALUE_PARAM)) {
        // add password
        String password = cmdLine.getOptionValue(SEC_ATTR_VALUE_PARAM, "password");
        nonInteractiveSession.addSecuredAttribute(vaultBlock, attributeName, password.toCharArray());
        return 0;
    } else if (cmdLine.hasOption(REMOVE_SEC_ATTR)) {
        nonInteractiveSession.removeSecuredAttribute(vaultBlock, attributeName);
        return 0;
    } else if (cmdLine.hasOption(GENERATE_CONFIG_FILE)) {
        PrintStream ps = new PrintStream(cmdLine.getOptionValue(GENERATE_CONFIG_FILE, "vault.properties"));
        try {
            nonInteractiveSession.outputConfig(ps);
        } finally {
            ps.close();
        }
        return 0;
    } else if (cmdLine.hasOption(CRYPT)) {
        // Regardless of the return here, we do not need to print summary for this command option
        skipSummary = true;
        // We need the encryption password and a value to encrypt
        if (cmdLine.getArgs().length == 2) {
            nonInteractiveSession.encryptValueWithCRYPT(cmdLine.getArgs()[0], cmdLine.getArgs()[1]);
            return 0;
        } else {
            System.out.println("Arguments: encryption password, value to encrypt");
            return 100;
        }
    }
    // Printing summary is not required here
    skipSummary = true;
    return 100;
}

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  ww w . j a  v 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 };
}