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:at.alladin.rmbt.qos.testserver.util.TestServerConsole.java

public TestServerConsole() {
    super(System.out, true);
    keyListener = new Thread(new Runnable() {

        @Override//from   w w w .java  2 s.c  o  m
        public void run() {
            if (System.console() != null) {
                while (true) {
                    try {
                        String command = System.console().readLine();
                        if (!isCommandLine) {
                            isCommandLine = true;
                            printLine();
                            printCommand(
                                    "\n\nEntered command mode!\n\nTo switch to debug output type 'exit' and press enter."
                                            + "\nType 'help' for some information on command mode.");
                        } else {
                            String[] commands = command.split("[ ]");

                            switch (commands[0]) {
                            case COMMAND_EXIT_COMMAND_PROMPT:
                                printlnCommand("\nStopped command mode.\n\n");
                                isCommandLine = false;
                                break;

                            case COMMAND_SHOW:
                                if (commands.length > 1) {
                                    switch (commands[1]) {
                                    case SUBCOMMAND_SHOW_CLIENTS:
                                        printLine();
                                        printlnCommand("\n");
                                        printlnCommand("\nActive clients: " + TestServer.clientHandlerSet.size()
                                                + "\n");
                                        for (ClientHandler client : TestServer.clientHandlerSet) {
                                            printlnCommand(" - " + client.getName());
                                            printlnCommand("\t UdpIncomingResults: ");
                                            for (Entry<Integer, UdpTestCandidate> udpIn : client
                                                    .getClientUdpInDataMap().entrySet()) {
                                                printlnCommand("\t\t " + udpIn.toString());
                                            }
                                            printlnCommand("\t UdpOutgoingResults: ");
                                            for (Entry<Integer, UdpTestCandidate> udpOut : client
                                                    .getClientUdpOutDataMap().entrySet()) {
                                                printlnCommand("\t\t " + udpOut.toString());
                                            }
                                        }
                                        printLine();
                                        break;
                                    case SUBCOMMAND_SHOW_INFO:
                                        printLine();
                                        printlnCommand("\n" + TestServer.TEST_SERVER_VERSION_NAME);
                                        printlnCommand("\nCurrent server settings: "
                                                + TestServer.serverPreferences.toString());
                                        printlnCommand(
                                                "\nQoSTestServer is listening on the following addresses:");
                                        for (ServerSocket ss : TestServer.serverSocketList) {
                                            printlnCommand("\t- " + ss.toString());
                                        }
                                        printLine();
                                        break;
                                    case SUBCOMMAND_SHOW_OPENED_TCP_PORTS:
                                        boolean showTcp = true;
                                        if (TestServer.tcpServerMap.size() > 500) {
                                            showTcp = (commands.length > 2
                                                    && commands[2].equals(SUBCOMMAND_FORCE));
                                        }

                                        printlnCommand("\nFound " + TestServer.tcpServerMap.values().size()
                                                + " active TCP sockets.");

                                        if (showTcp) {
                                            printlnCommand("\n\nList of all TCP sockets:\n");
                                            for (Entry<Integer, List<TcpMultiClientServer>> e : TestServer.tcpServerMap
                                                    .entrySet()) {
                                                for (TcpMultiClientServer i : e.getValue()) {
                                                    printlnCommand(
                                                            "Port " + e.getKey() + " -> " + i.toString());
                                                }
                                            }
                                        } else {
                                            printlnCommand(
                                                    "\n\nAre you sure you want to display them all? To ignore this warning type: 'show tcp force'.");
                                        }
                                        break;
                                    case SUBCOMMAND_SHOW_OPENED_UDP_PORTS:
                                        printlnCommand("Available udp sub options: "
                                                + "\nshow udp [#####] \t- where ##### is a port number between 0 and 65535"
                                                + "\nshow udp data \t\t- shows UDP servers with active ClientData awaiting incoming packets"
                                                + "\nshow udp nodata \t- shows UDP servers without active ClientData\n\n");
                                        if (commands.length > 2) {
                                            if ("data".equals(commands[2])) {
                                                printlnCommand(
                                                        "\nMultiClient UDP Server containing ClientData:");
                                                for (List<AbstractUdpServer<?>> udpServerList : TestServer.udpServerMap
                                                        .values()) {
                                                    for (AbstractUdpServer<?> udpServer : udpServerList) {
                                                        if (!udpServer.getIncomingMap().isEmpty()) {
                                                            printlnCommand("\nUDP Server Info: "
                                                                    + udpServer.toString());
                                                        }
                                                    }
                                                }
                                            } else if ("nodata".equals(commands[2])) {
                                                printlnCommand("\nMultiClient UDP Server wihtout ClientData:");
                                                for (List<AbstractUdpServer<?>> udpServerList : TestServer.udpServerMap
                                                        .values()) {
                                                    for (AbstractUdpServer<?> udpServer : udpServerList) {
                                                        if (udpServer.getIncomingMap().isEmpty()) {
                                                            printlnCommand("\nUDP Server Info: "
                                                                    + udpServer.toString());
                                                        }
                                                    }
                                                }
                                            } else {
                                                try {
                                                    List<AbstractUdpServer<?>> udpServerList = TestServer.udpServerMap
                                                            .get(Integer.valueOf(commands[2]));
                                                    for (AbstractUdpServer<?> udpServer : udpServerList) {
                                                        printlnCommand("\nMultiClient UDP Server Info:\n"
                                                                + udpServer.toString());
                                                    }
                                                } catch (Exception e) {
                                                    e.printStackTrace();
                                                }
                                            }
                                        } else {
                                            printlnCommand("\nActive UDP ports: "
                                                    + TestServer.serverPreferences.getUdpPortSet());
                                        }
                                        break;
                                    default:
                                        printlnCommand("\n" + HINT_SHOW);
                                        break;
                                    }
                                } else {
                                    printlnCommand("\n" + HINT_SHOW);
                                }
                                break;

                            case COMMAND_SETTINGS:
                                if (commands.length > 1) {
                                    switch (commands[1]) {

                                    case SUBCOMMAND_SETTINGS_SET_VERBOSE:
                                        if (commands.length > 2) {
                                            int verboseLevel = Integer.parseInt(commands[2]);
                                            verboseLevel = verboseLevel < 0 ? 0
                                                    : (verboseLevel > 2 ? 2 : verboseLevel);

                                            printlnCommand("\nSetting verbose level to: " + verboseLevel);
                                            TestServer.serverPreferences.setVerboseLevel(verboseLevel);
                                        } else {
                                            printlnCommand("\nVerbose level missing!");
                                        }
                                        break;

                                    default:
                                        printCommand("\nSET what? Available options: [verbose].");
                                    }
                                }
                                printlnCommand("\nCurrent server settings: "
                                        + TestServer.serverPreferences.toString());
                                break;

                            case COMMAND_SHUTDOWN:
                                isCommandLine = false;
                                printLine();
                                TestServer.shutdown();
                                System.exit(0);
                                break;
                            case COMMAND_HELP:
                                printHelp();
                                break;

                            case DEBUG_COMMAND_LIST_SERVICES:
                                synchronized (TestServer.serviceManager.getServiceMap()) {
                                    Iterator<Entry<String, FutureService>> entries = TestServer.serviceManager
                                            .getServiceMap().entrySet().iterator();
                                    printlnCommand("\n" + TestServer.serviceManager.getServiceMap().size()
                                            + " services found:\n");
                                    int i = 0;
                                    while (entries.hasNext()) {
                                        Entry<String, FutureService> e = entries.next();
                                        printlnCommand("\t" + (++i) + ") " + e.getKey() + ":\n\t\t"
                                                + e.getValue().getService().toString());
                                    }
                                }
                                break;

                            default:
                                printCommand("\nUnknown command. Enter 'help' for more information.");
                                printHelp();
                            }
                        }

                        if (isCommandLine) {
                            printCommand(PROMPT);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        break; //exit loop
                    }
                }
            }
        }
    });
}

From source file:org.signserver.admin.cli.defaultimpl.RemoveKeyCommand.java

@Override
public int execute(String... args)
        throws IllegalCommandArgumentsException, CommandFailureException, UnexpectedCommandFailureException {
    try {/*w w  w .j av  a  2s .  c om*/
        // Parse the command line
        parseCommandLine(new GnuParser().parse(OPTIONS, args));
    } catch (ParseException ex) {
        throw new IllegalArgumentException(ex.getLocalizedMessage(), ex);
    }
    validateOptions();

    if (args.length < 1) {
        throw new IllegalCommandArgumentsException(USAGE);
    }

    try {
        int signerId = getWorkerId(args[0]);
        checkThatWorkerIsProcessable(signerId);

        final boolean proceed;
        if (noAsk) {
            proceed = true;
        } else {
            getOutputStream().println("WARNING: Will attempt to permantently remove the following key:");
            getOutputStream().println(alias);
            getOutputStream().println();
            getOutputStream().println("Note: the key might be used by multiple workers.");
            getOutputStream().println("Are you sure you want to try to destroy the key? [YES/no] ");
            final String answer = System.console().readLine();
            proceed = "YES".equals(answer);
        }

        if (proceed) {
            final boolean result = getWorkerSession().removeKey(signerId, alias);
            getOutputStream().println("Key removal returned: " + result);
            return result ? CommandLineInterface.RETURN_SUCCESS : CommandLineInterface.RETURN_ERROR;
        } else {
            getOutputStream().println("Aborted");
            return CommandLineInterface.RETURN_INVALID_ARGUMENTS;
        }

    } catch (CryptoTokenOfflineException ex) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Crypto token offline: " + ex.getMessage(), ex);
        }
        getErrorStream().println(ex.getMessage());
        return CommandLineInterface.RETURN_ERROR;
    } catch (SignServerException ex) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Error: " + ex.getMessage(), ex);
        }
        getErrorStream().println(ex.getMessage());
        return CommandLineInterface.RETURN_ERROR;
    } catch (InvalidWorkerIdException ex) {
        getErrorStream().println(ex.getMessage());
        return CommandLineInterface.RETURN_ERROR;
    } catch (Exception e) {
        throw new UnexpectedCommandFailureException(e);
    }
}

From source file:org.forgerock.openidm.shell.impl.RemoteCommandScope.java

private void processOptions(final String userPass, final String idmUrl, final String idmPort) {
    String username = "";
    String password = "";

    if (StringUtils.isNotBlank(userPass)) {
        int passwordIdx = userPass.indexOf(":") + 1;

        if (passwordIdx > 0) {
            username = userPass.substring(0, passwordIdx - 1);
            password = userPass.substring(passwordIdx);
        } else {//from   w ww .j  a  v  a2s. c o m
            username = userPass;
            password = new String(System.console().readPassword("Password:"));
        }

        resource.setUsername(username);
        resource.setPassword(password);
    }

    if (StringUtils.isNotBlank(idmUrl)) {
        resource.setBaseUri(idmUrl.endsWith("/") ? idmUrl : idmUrl + "/");
    }

    if (StringUtils.isNotBlank(idmPort)) {
        if (NumberUtils.isDigits(idmPort)) {
            resource.setPort(Integer.decode(idmPort));
        } else {
            throw new IllegalArgumentException("Port must be a number");
        }
    }
}

From source file:org.jboss.windup.bootstrap.Bootstrap.java

public static String promptForListItem(String message, Collection<String> items, String defaultValue) {
    while (true) {
        List<String> sorted = new ArrayList<>(items);
        Collections.sort(sorted);

        System.out.println();// w  ww .java2 s .  c o  m
        System.out.println(message);
        for (String item : sorted) {
            System.out.println("\t" + item);
        }

        String promptMessage = "Please enter the item you would like to choose[" + defaultValue + "]: ";
        String item = System.console().readLine(promptMessage).trim();
        if (StringUtils.isNotBlank(item))
            return item;
        else if (StringUtils.isNotBlank(defaultValue))
            return defaultValue;
        else
            System.out.println("A selection is required. Please select one of the available items.");
    }
}

From source file:org.ow2.proactive.scheduler.authentication.ManageUsers.java

public static void manageUsers(String... args) throws ManageUsersException {
    SecurityManagerConfigurator.configureSecurityManager(
            CreateCredentials.class.getResource("/all-permissions.security.policy").toString());

    Console console = System.console();
    /**// www  . j  a va 2  s . c  o  m
     * default values
     */
    String pubKeyPath = null;
    PublicKey pubKey = null;
    UserInfo userInfo = new UserInfo();
    String loginFilePath = getLoginFilePath();
    String groupFilePath = getGroupFilePath();
    String sourceLoginFilePath = null;
    String sourceGroupFilePath = null;
    Action action = null;

    Options options = new Options();

    CommandLine cmd = getCommandLine(args, loginFilePath, groupFilePath, options);

    if (cmd.hasOption(HELP_OPTION_NAME) || cmd.getOptions().length == 0) {
        displayHelp(options);
        return;
    }

    action = Action.getAction(cmd);

    if (cmd.hasOption(LOGIN_OPTION_NAME)) {
        userInfo.setLogin(cmd.getOptionValue(LOGIN_OPTION_NAME));
    }
    if (cmd.hasOption(PWD_OPTION_NAME)) {
        userInfo.setPassword(cmd.getOptionValue(PWD_OPTION_NAME));
    }
    if (cmd.hasOption(GROUPS_OPTION_NAME)) {
        String groupString = cmd.getOptionValue(GROUPS_OPTION_NAME);
        userInfo.setGroups(Arrays.asList(groupString.split(",")));
    }

    if (cmd.hasOption(LOGINFILE_OPTION_NAME)) {
        loginFilePath = cmd.getOptionValue(LOGINFILE_OPTION_NAME);
    }
    if (cmd.hasOption(GROUPFILE_OPTION_NAME)) {
        groupFilePath = cmd.getOptionValue(GROUPFILE_OPTION_NAME);
    }
    if (cmd.hasOption(KEYFILE_OPTION_NAME)) {
        pubKeyPath = cmd.getOptionValue(KEYFILE_OPTION_NAME);
    }

    if (cmd.hasOption(SOURCE_LOGINFILE_OPTION_NAME)) {
        if (action == Action.DELETE) {
            exitWithErrorMessage("Cannot use action delete with source login file.", null, null);
        }
        if (!cmd.hasOption(SOURCE_GROUPFILE_OPTION_NAME) && action == Action.CREATE) {
            exitWithErrorMessage(
                    "Source group file must be provided when creating users with source login file.", null,
                    null);
        }
        sourceLoginFilePath = cmd.getOptionValue(SOURCE_LOGINFILE_OPTION_NAME);
        userInfo = null;
    }
    if (cmd.hasOption(SOURCE_GROUPFILE_OPTION_NAME)) {
        if (action == Action.DELETE) {
            exitWithErrorMessage("Cannot use action delete with source group file.", null, null);
        }
        if (!cmd.hasOption(SOURCE_LOGINFILE_OPTION_NAME) && action == Action.CREATE) {
            exitWithErrorMessage(
                    "Source login file must be provided when creating users with source group file.", null,
                    null);
        }
        sourceGroupFilePath = cmd.getOptionValue(SOURCE_GROUPFILE_OPTION_NAME);
        userInfo = null;
    }

    if (pubKeyPath == null) {
        pubKeyPath = getPublicKeyFilePath();
    }

    try {
        pubKey = Credentials.getPublicKey(pubKeyPath);
    } catch (KeyException e) {
        exitWithErrorMessage("Could not retrieve public key from '" + pubKeyPath, null, e);
    }
    boolean nonInteractive = checkInteractivity(userInfo, sourceLoginFilePath, sourceGroupFilePath, action);

    if (!nonInteractive) {
        askInteractively(console, userInfo, action);
    }

    updateAccounts(pubKey, userInfo, loginFilePath, groupFilePath, action, sourceLoginFilePath,
            sourceGroupFilePath);
}

From source file:us.ihmc.codecs.loader.OpenH264Downloader.java

private static void acceptLicenseConsole() {
    System.out.println("OpenH264 Video Codec provided by Cisco Systems, Inc.");
    System.out.println(getLicenseText());
    System.out.println("Do you accept the OpenH264 License? [Y/N]");

    String in = System.console().readLine();

    if (!in.toLowerCase().equals("y")) {
        System.err.println("License not accepted");
        System.exit(-1);/*from   w w  w.  ja  va 2 s . com*/
    }
}

From source file:net.sourceforge.pmd.ant.Formatter.java

private static String getConsoleEncoding() {
    Console console = System.console();
    // in case of pipe or redirect, no interactive console.
    if (console != null) {
        try {/*from www . j  a  v a 2s  . c  o  m*/
            Field f = Console.class.getDeclaredField("cs");
            f.setAccessible(true);
            Object res = f.get(console);
            if (res instanceof Charset) {
                return ((Charset) res).name();
            }
        } catch (ReflectiveOperationException ignored) {
            // fall-through
        }
        return getNativeConsoleEncoding();
    }
    return null;
}

From source file:org.ejbca.ui.cli.ca.CaExportCACommand.java

@Override
public CommandResult execute(ParameterContainer parameters) {

    String kspwd = parameters.get(KEYSTORE_PASSWORD_KEY);
    String caName = parameters.get(CA_NAME_KEY);
    String p12file = parameters.get(FILE_KEY);

    String signatureKeyAlias = parameters.get(SIGNATURE_ALIAS_KEY);
    String encryptionKeyAlias = parameters.get(ENCRYPTION_ALIAS_KEY);
    if ((signatureKeyAlias == null && encryptionKeyAlias != null
            && parameters.isStandalone(ENCRYPTION_ALIAS_KEY))
            || (signatureKeyAlias != null && encryptionKeyAlias == null
                    && parameters.isStandalone(SIGNATURE_ALIAS_KEY))) {
        //only one of the values was set and implicitly, kinda scary. Let's warn about that. 
        log.error(/*  w  w w  .  j  a v  a  2s  .  com*/
                "Do not set only one of SignatureKeyAlias or EncryptionKeyAlias implicitely (without a switch).");
        return CommandResult.FUNCTIONAL_FAILURE;
    }
    if (signatureKeyAlias == null) {
        log.info("Setting SignatureKeyAlias to " + SIGNATURE_ALIAS_DEFAULT);
        signatureKeyAlias = SIGNATURE_ALIAS_DEFAULT;
    }
    if (encryptionKeyAlias == null) {
        log.info("Setting EncryptionKeyAlias to " + ENCRYPTION_ALIAS_DEFAULT);
        encryptionKeyAlias = ENCRYPTION_ALIAS_DEFAULT;
    }

    if (kspwd == null) {
        log.info("Enter keystore password: ");
        // Read the password, but mask it so we don't display it on the console
        kspwd = String.valueOf(System.console().readPassword());
    } else {
        log.info("Keystore password was supplied on the command line.");
    }
    if (StringUtils.isEmpty(kspwd)) {
        // Can not export CA keystore with empty password. 
        log.error("Export a token without password protection is not allowed.");
        return CommandResult.FUNCTIONAL_FAILURE;
    }
    byte[] keyStoreBytes = EjbRemoteHelper.INSTANCE.getRemoteSession(CAAdminSessionRemote.class)
            .exportCAKeyStore(getAuthenticationToken(), caName, kspwd, kspwd, signatureKeyAlias,
                    encryptionKeyAlias);
    try {
        FileOutputStream fos = new FileOutputStream(p12file);
        fos.write(keyStoreBytes);
        fos.close();
    } catch (FileNotFoundException e) {
        log.error(e.getMessage());
        return CommandResult.FUNCTIONAL_FAILURE;
    } catch (IOException e) {
        throw new IllegalStateException("Could not write to file for unknown reason", e);
    }
    return CommandResult.SUCCESS;

}

From source file:org.jboss.windup.bootstrap.Bootstrap.java

public static boolean prompt(String message, boolean defaultValue, boolean batchMode) {
    if (batchMode) {
        return defaultValue;
    } else {//from  ww  w . ja  v a2s  .  co m
        String defaultMessage = defaultValue ? " [Y,n] " : " [y,N] ";
        String line = System.console().readLine(message + defaultMessage).trim();
        if ("y".equalsIgnoreCase(line))
            return true;
        if ("n".equalsIgnoreCase(line))
            return false;
        return defaultValue;
    }
}

From source file:net.alegen.datpass.cli.input.ProfileCommand.java

@Override
public void execute() {
    try {//from   www .  j a  va  2 s .  c om
        Configurator configurator = Settings.getConfigurator();
        CommandLineParser parser = new PosixParser();
        String[] arrayArgs = new String[this.args.size()];
        this.args.toArray(arrayArgs);
        CommandLine line = parser.parse(this.options, arrayArgs);
        if (line.getOptions().length == 0) {
            Profile profile = Generator.getInstance().getCurrentProfile();
            if (profile == null)
                System.out.println("No profile is currently in use.");
            else
                System.out.println("Current profile: " + profile.getValue(FieldManager.NAME_FIELD));
        } else if (line.hasOption(OPTION_LIST)) {
            Map<String, Boolean> profiles = configurator.listProfiles();
            if (profiles.size() > 0) {
                System.out.println("Available profiles:");
                for (Map.Entry<String, Boolean> entry : profiles.entrySet()) {
                    if (entry.getValue())
                        System.out.println("* " + entry.getKey() + "\t[encrypted]");
                    else
                        System.out.println("* " + entry.getKey());
                }
            } else
                System.out.println("There are no available profiles.");
        } else if (line.hasOption(OPTION_CREATE)) {
            Profile profile = new Profile();
            for (FieldManager.Field field : FieldManager.getInstance()) {
                boolean valid = false;
                while (!valid) {
                    String question = field.getDescription();
                    if (field.getDefaultValue() != null || field.isMandatory()) {
                        question += " ( ";
                        if (field.getDefaultValue() != null && !field.getDefaultValue().isEmpty()) {
                            if (field.isMandatory()) {
                                question += "default: " + field.getDefaultValue() + ", mandatory";
                            } else {
                                question += "default: " + field.getDefaultValue();
                            }
                        } else {
                            question += "mandatory";
                        }
                        question += " )";
                    }
                    question += ": ";
                    System.out.print(question);
                    String answer = System.console().readLine();
                    if (answer.isEmpty()) {
                        if (field.isMandatory()) {
                            if (field.getDefaultValue() != null && !field.getDefaultValue().isEmpty()) {
                                profile.setValue(field, field.getDefaultValue());
                                System.out.println("Field set to default value.");
                                valid = true;
                            } else
                                System.out.println(
                                        "This field is mandatory and a default value is not available.\nPlease provide a value for it.");
                        } else
                            valid = true;
                    } else {
                        profile.setValue(field, answer);
                        valid = true;
                    }
                }
            }
            if (line.hasOption(OPTION_ENCRYPTED)) {
                String password1 = "password1";
                String password2 = "password2";
                while (!password1.equals(password2)) {
                    System.out.print("Password: ");
                    password1 = String.valueOf(System.console().readPassword());
                    System.out.print("Retype password: ");
                    password2 = String.valueOf(System.console().readPassword());
                    if (!password1.equals(password2))
                        System.out.println("The two passwords do not match. Please try again.");
                }
                configurator.saveProfile(profile, password1);
                configurator.saveConfig();
            } else {
                configurator.saveProfile(profile);
                configurator.saveConfig();
            }
        } else if (line.hasOption(OPTION_UNLOCK)) {
            String name = line.getOptionValue(OPTION_UNLOCK);
            boolean isEncrypted = false;
            Map<String, Boolean> profiles = configurator.listProfiles();
            for (Map.Entry<String, Boolean> entry : profiles.entrySet())
                if (entry.getKey().equals(name)) {
                    isEncrypted = entry.getValue();
                    break;
                }
            Profile profile = null;
            if (isEncrypted) {
                System.out.print("Password: ");
                String password = String.valueOf(System.console().readPassword());
                profile = configurator.loadProfile(name, password);
            } else
                profile = configurator.loadProfile(name, "");
            Generator.getInstance().setCurrentProfile(profile);
        } else if (line.hasOption(OPTION_REMOVE)) {
            String name = line.getOptionValue(OPTION_REMOVE);
            configurator.removeProfile(name);
            configurator.saveConfig();
        }
    } catch (ParseException e) {

    } catch (Configurator.ConfigurationException e) {

    } catch (Profile.InvalidProfileException e) {

    }
}