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.overlord.sramp.wagon.SrampWagon.java

/**
 * Prompts the user to enter a username for authentication credentials.
 *///from w ww  .  ja  v  a2  s  . c o m
private String promptForUsername() {
    Console console = System.console();
    if (console != null) {
        return console.readLine(Messages.i18n.format("USERNAME_PROMPT")); //$NON-NLS-1$
    } else {
        System.err.println(Messages.i18n.format("NO_CONSOLE_ERROR_1")); //$NON-NLS-1$
        return null;
    }
}

From source file:org.apache.syncope.client.cli.commands.install.InstallSetup.java

public void setup() throws FileNotFoundException, IllegalAccessException {
    installResultManager.printWelcome();

    System.out.println(// w  w w .j  av a2 s .c  om
            "Path to config files of Syncope CLI client will be: " + InstallConfigFileTemplate.dirPath());

    if (!FileSystemUtils.exists(InstallConfigFileTemplate.dirPath())) {
        throw new FileNotFoundException(
                "Directory: " + InstallConfigFileTemplate.dirPath() + " does not exists!");
    }

    if (!FileSystemUtils.canWrite(InstallConfigFileTemplate.dirPath())) {
        throw new IllegalAccessException("Permission denied on " + InstallConfigFileTemplate.dirPath());
    }
    System.out.println("- File system permission checked");
    System.out.println("");

    try (Scanner scanIn = new Scanner(System.in)) {
        System.out.print("Syncope server schema [http/https]: ");
        String syncopeServerSchemaFromSystemIn = scanIn.nextLine();
        boolean schemaFound = false;
        while (!schemaFound) {
            if (("http".equalsIgnoreCase(syncopeServerSchemaFromSystemIn))
                    || ("https".equalsIgnoreCase(syncopeServerSchemaFromSystemIn))) {
                syncopeServerSchema = syncopeServerSchemaFromSystemIn;
                schemaFound = true;
            } else {
                System.out.println("Please use one of below values: ");
                System.out.println("   - http");
                System.out.println("   - https");
                syncopeServerSchemaFromSystemIn = scanIn.nextLine();
            }
        }

        System.out.print("Syncope server hostname [e.g. " + syncopeServerHostname + "]: ");
        String syncopeServerHostnameFromSystemIn = scanIn.nextLine();
        boolean syncopeServerHostnameFound = false;
        while (!syncopeServerHostnameFound) {
            if (StringUtils.isNotBlank(syncopeServerHostnameFromSystemIn)) {
                syncopeServerHostname = syncopeServerHostnameFromSystemIn;
                syncopeServerHostnameFound = true;
            } else {
                System.out.print("Syncope server hostname [e.g. " + syncopeServerHostname + "]: ");
                syncopeServerHostnameFromSystemIn = scanIn.nextLine();
            }
        }

        System.out.print("Syncope server port [e.g. " + syncopeServerPort + "]: ");
        String syncopeServerPortFromSystemIn = scanIn.nextLine();
        boolean syncopeServerPortFound = false;
        while (!syncopeServerPortFound) {
            if (StringUtils.isNotBlank(syncopeServerPortFromSystemIn)) {
                syncopeServerPort = syncopeServerPortFromSystemIn;
                syncopeServerPortFound = true;
            } else if (!StringUtils.isNumeric(syncopeServerPortFromSystemIn)) {
                System.err.println(syncopeServerPortFromSystemIn + " is not a numeric string, try again");
                syncopeServerPortFromSystemIn = scanIn.nextLine();
            } else {
                System.out.print("Syncope server port [e.g. " + syncopeServerPort + "]: ");
                syncopeServerPortFromSystemIn = scanIn.nextLine();
            }
        }

        System.out.print("Syncope server rest context [e.g. " + syncopeServerRestContext + "]: ");
        String syncopeServerRestContextFromSystemIn = scanIn.nextLine();
        boolean syncopeServerRestContextFound = false;
        while (!syncopeServerRestContextFound) {
            if (StringUtils.isNotBlank(syncopeServerRestContextFromSystemIn)) {
                syncopeServerRestContext = syncopeServerRestContextFromSystemIn;
                syncopeServerRestContextFound = true;
            } else {
                System.out.print("Syncope server port [e.g. " + syncopeServerRestContext + "]: ");
                syncopeServerRestContextFromSystemIn = scanIn.nextLine();
            }
        }

        System.out.print("Syncope admin user: ");
        String syncopeAdminUserFromSystemIn = scanIn.nextLine();
        boolean syncopeAdminUserFound = false;
        while (!syncopeAdminUserFound) {
            if (StringUtils.isNotBlank(syncopeAdminUserFromSystemIn)) {
                syncopeAdminUser = syncopeAdminUserFromSystemIn;
                syncopeAdminUserFound = true;
            } else {
                System.out.print("Syncope admin user: ");
                syncopeAdminUserFromSystemIn = scanIn.nextLine();
            }
        }

        char[] syncopeAdminPasswordFromSystemConsole = System.console()
                .readPassword("Syncope admin password: ");
        boolean syncopeAdminPasswordFound = false;
        while (!syncopeAdminPasswordFound) {
            if (syncopeAdminPasswordFromSystemConsole != null
                    && syncopeAdminPasswordFromSystemConsole.length > 0) {
                syncopeAdminPassword = new String(syncopeAdminPasswordFromSystemConsole);
                syncopeAdminPasswordFound = true;
            } else {
                syncopeAdminPasswordFromSystemConsole = System.console()
                        .readPassword("Syncope admin password: ");
            }
        }
    }

    final JasyptUtils jasyptUtils = JasyptUtils.get();
    try {

        final String contentCliPropertiesFile = InstallConfigFileTemplate.cliPropertiesFile(syncopeServerSchema,
                syncopeServerHostname, syncopeServerPort, syncopeServerRestContext, syncopeAdminUser,
                jasyptUtils.encrypt(syncopeAdminPassword));
        FileSystemUtils.createFileWith(InstallConfigFileTemplate.configurationFilePath(),
                contentCliPropertiesFile);
    } catch (final IOException ex) {
        System.out.println(ex.getMessage());
    }

    try {
        final SyncopeService syncopeService = SyncopeServices.get(SyncopeService.class);
        final String syncopeVersion = syncopeService.platform().getVersion();
        installResultManager.installationSuccessful(syncopeVersion);
    } catch (final ProcessingException ex) {
        LOG.error("Error installing CLI", ex);
        installResultManager.manageProcessingException(ex);
    } catch (final Exception e) {
        LOG.error("Error installing CLI", e);
        installResultManager.manageException(e);
    }
}

From source file:com.jkoolcloud.jesl.simulator.TNT4JSimulator.java

public static void main(String[] args) {
    boolean isTTY = (System.console() != null);
    long startTime = System.currentTimeMillis();

    try {/*  w ww  .jav a  2  s  .  c  o m*/
        SAXParserFactory parserFactory = SAXParserFactory.newInstance();
        SAXParser theParser = parserFactory.newSAXParser();
        TNT4JSimulatorParserHandler xmlHandler = new TNT4JSimulatorParserHandler();

        processArgs(xmlHandler, args);

        TrackerConfig simConfig = DefaultConfigFactory.getInstance().getConfig(TNT4JSimulator.class.getName());
        logger = TrackingLogger.getInstance(simConfig.build());
        if (logger.isSet(OpLevel.TRACE))
            traceLevel = OpLevel.TRACE;
        else if (logger.isSet(OpLevel.DEBUG))
            traceLevel = OpLevel.DEBUG;

        if (runType == SimulatorRunType.RUN_SIM) {
            if (StringUtils.isEmpty(simFileName)) {
                simFileName = "tnt4j-sim.xml";
                String fileName = readFromConsole("Simulation file [" + simFileName + "]: ");

                if (!StringUtils.isEmpty(fileName))
                    simFileName = fileName;
            }

            StringBuffer simDef = new StringBuffer();
            BufferedReader simLoader = new BufferedReader(new FileReader(simFileName));
            String line;
            while ((line = simLoader.readLine()) != null)
                simDef.append(line).append("\n");
            simLoader.close();

            info("jKool Activity Simulator Run starting: file=" + simFileName + ", iterations=" + numIterations
                    + ", ttl.sec=" + ttl);
            startTime = System.currentTimeMillis();

            if (isTTY && numIterations > 1)
                System.out.print("Iteration: ");
            int itTrcWidth = 0;
            for (iteration = 1; iteration <= numIterations; iteration++) {
                itTrcWidth = printProgress("Executing Iteration", iteration, itTrcWidth);

                theParser.parse(new InputSource(new StringReader(simDef.toString())), xmlHandler);

                if (!Utils.isEmpty(jkFileName)) {
                    PrintWriter gwFile = new PrintWriter(new FileOutputStream(jkFileName, true));
                    gwFile.println("");
                    gwFile.close();
                }
            }
            if (numIterations > 1)
                System.out.println("");

            info("jKool Activity Simulator Run finished, elapsed time = "
                    + DurationFormatUtils.formatDurationHMS(System.currentTimeMillis() - startTime));
            printMetrics(xmlHandler.getSinkStats(), "Total Sink Statistics");
        } else if (runType == SimulatorRunType.REPLAY_SIM) {
            info("jKool Activity Simulator Replay starting: file=" + jkFileName + ", iterations="
                    + numIterations);
            connect();
            startTime = System.currentTimeMillis();

            // Determine number of lines in file
            BufferedReader gwFile = new BufferedReader(new java.io.FileReader(jkFileName));
            for (numIterations = 0; gwFile.readLine() != null; numIterations++)
                ;
            gwFile.close();

            // Reopen the file and
            gwFile = new BufferedReader(new java.io.FileReader(jkFileName));
            if (isTTY && numIterations > 1)
                System.out.print("Processing Line: ");
            int itTrcWidth = 0;
            String gwMsg;
            iteration = 0;
            while ((gwMsg = gwFile.readLine()) != null) {
                iteration++;
                if (isTTY)
                    itTrcWidth = printProgress("Processing Line", iteration, itTrcWidth);
                gwConn.write(gwMsg);
            }
            if (isTTY && numIterations > 1)
                System.out.println("");
            long endTime = System.currentTimeMillis();

            info("jKool Activity Simulator Replay finished, elasped.time = "
                    + DurationFormatUtils.formatDurationHMS(endTime - startTime));
        }
    } catch (Exception e) {
        if (e instanceof SAXParseException) {
            SAXParseException spe = (SAXParseException) e;
            error("Error at line: " + spe.getLineNumber() + ", column: " + spe.getColumnNumber(), e);
        } else {
            error("Error running simulator", e);
        }
    } finally {
        try {
            Thread.sleep(1000L);
        } catch (Exception e) {
        }
        TNT4JSimulator.disconnect();
    }

    System.exit(0);
}

From source file:craterdog.marketplace.DigitalMarketplaceCli.java

public DigitalMarketplaceCli(URI digitalMarketplaceUri) {
    this.digitalMarketplaceUri = digitalMarketplaceUri;
    digitalMarketplaceClient = new DigitalMarketplaceClient(digitalMarketplaceUri);
    notary = new V1NotarizationProvider();
    identificationProvider = new V1IdentificationProvider();
    tokenizationProvider = new V1TokenizationProvider();
    accountingProvider = new V1AccountingProvider();
    console = System.console();
    if (console != null) {
        reader = new BufferedReader(console.reader());
        writer = console.writer();//from   w  w w .  j  a  v a  2s . c  o  m
    } else {
        reader = new BufferedReader(new InputStreamReader(System.in));
        writer = new PrintWriter(new OutputStreamWriter(System.out), true); // autoflush
    }
}

From source file:com.okta.tools.awscli.java

private static String oktaAuthntication() throws ClientProtocolException, JSONException, IOException {
    CloseableHttpResponse responseAuthenticate = null;
    int requestStatus = 0;

    //Redo sequence if response from AWS doesn't return 200 Status
    while (requestStatus != 200) {

        // Prompt for user credentials
        System.out.print("Username: ");
        Scanner scanner = new Scanner(System.in);

        String oktaUsername = scanner.next();

        Console console = System.console();
        String oktaPassword = null;
        if (console != null) {
            oktaPassword = new String(console.readPassword("Password: "));
        } else { // hack to be able to debug in an IDE
            System.out.print("Password: ");
            oktaPassword = scanner.next();
        }//  w w w  . j  a v  a 2s .c  o m

        responseAuthenticate = authnticateCredentials(oktaUsername, oktaPassword);
        requestStatus = responseAuthenticate.getStatusLine().getStatusCode();
        authnFailHandler(requestStatus, responseAuthenticate);
    }

    //Retrieve and parse the Okta response for session token
    BufferedReader br = new BufferedReader(
            new InputStreamReader((responseAuthenticate.getEntity().getContent())));

    String outputAuthenticate = br.readLine();
    JSONObject jsonObjResponse = new JSONObject(outputAuthenticate);

    responseAuthenticate.close();

    if (jsonObjResponse.getString("status").equals("MFA_REQUIRED")) {
        return mfa(jsonObjResponse);
    } else {
        return jsonObjResponse.getString("sessionToken");
    }
}

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

public void process() throws InterruptedException, JSchException, JSONException, IOException, ParseException {
    Pattern remotePattern = Pattern
            .compile("(\\w[\\w\\-\\.]+\\$?){1,32}@([\\p{Alnum}\\.]+)(?::(22$|[0-9]{4,5}))?");
    Level logLevel = cmd.hasOption("debug") ? Level.DEBUG : cmd.hasOption("quiet") ? Level.WARN : Level.INFO;
    ((ch.qos.logback.classic.Logger) log).setLevel(logLevel);
    if (cmd.hasOption("universe") && cmd.hasOption('p'))
        log.warn("Formatted output disabled on universe extraction.");
    Engine.Scope scope = cmd.hasOption("universe") ? Engine.Scope.UNIVERSE : Engine.Scope.INSTALLED_PACKAGES;
    if (cmd.hasOption('l')) {
        printResult(finalizeResult(new Engine(logLevel).run(scope)));
    } else if (cmd.hasOption('r')) {
        boolean nl = false;
        for (String remote : cmd.getOptionValues('r')) {
            if (nl)
                log.info("");
            if (!remote.matches(remotePattern.pattern())) {
                log.warn("Invalid remote (skipping): " + remote);
                nl = true;//from   www  .j  ava2 s  . c o  m
                continue;
            }
            Matcher matcher = remotePattern.matcher(remote);
            matcher.find();
            SSHManager sshManager;
            if (matcher.group(3) != null)
                sshManager = new SSHManager(matcher.group(1), matcher.group(2),
                        Integer.parseInt(matcher.group(3)));
            else
                sshManager = new SSHManager(matcher.group(1), matcher.group(2));
            getLoggerStdOut().write(("Enter password for " + matcher.group(1) + "@" + matcher.group(2)
                    + (matcher.group(3) != null ? ":" + matcher.group(3) : "") + ": ").getBytes());
            sshManager.setPassword(new String(System.console().readPassword()));
            printResult(finalizeResult(new Engine(sshManager, logLevel).run(scope)),
                    cmd.getOptionValues('r').length > 1
                            ? matcher.group(2) + (matcher.group(3) != null ? '-' + matcher.group(3) : "")
                            : "");
            nl = true;
        }
    }
}

From source file:org.overlord.sramp.wagon.SrampWagon.java

/**
 * Prompts the user to enter a password for authentication credentials.
 *///  ww  w.  ja va  2s.  c om
private String promptForPassword() {
    Console console = System.console();
    if (console != null) {
        return new String(console.readPassword(Messages.i18n.format("PASSWORD_PROMPT"))); //$NON-NLS-1$
    } else {
        System.err.println(Messages.i18n.format("NO_CONSOLE_ERROR_2")); //$NON-NLS-1$
        return null;
    }
}

From source file:com.docdoku.cli.helpers.FileHelper.java

public static boolean confirmOverwrite(String fileName) {
    Console c = System.console();
    String response = c.readLine(
            "The file '" + fileName + "' has been modified locally, do you want to overwrite it [y/N]?");
    return "y".equalsIgnoreCase(response);
}

From source file:org.tolven.assembler.admin.AdminAssembler.java

protected String getCommandLineUser(CommandLine commandLine) {
    String user = null;/* ww  w  . j  a  v a 2  s .  co  m*/
    if (commandLine.getOptionValue(CMD_LINE_TOLVEN_USER_OPTION) != null) {
        user = commandLine.getOptionValue(CMD_LINE_TOLVEN_USER_OPTION);
    }
    if (user == null) {
        if (System.getenv(ENV_TOLVEN_USER) == null) {
            System.out.print("User Id: ");
            user = System.console().readLine();
        } else {
            user = System.getenv(ENV_TOLVEN_USER);
        }
    }
    return user;
}