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:com.eucalyptus.reporting.dw.commands.CommandSupport.java

private void setupPersistenceContext() {
    final Properties properties = new Properties();
    try {/*ww w  . j  av  a2 s .  co m*/
        properties.load(CommandSupport.class.getClassLoader()
                .getResourceAsStream(RESOURCE_DATA_WAREHOUSE_PERSISTENCE_PROPERTIES));
    } catch (IOException e) {
        throw Exceptions.toUndeclared(e);
    }

    String dbPassword = System.getenv("EUCADW_DB_PASS");
    dbPassword = arguments.getArgument("db-pass", dbPassword);
    if (dbPassword == null && System.console() != null) {
        char[] password = System.console().readPassword("Database password: ");
        dbPassword = password != null ? new String(password) : "";
    }
    if (dbPassword == null) {
        throw new ConfigurationException("Database password not provided.");
    }

    databaseConnectionInfo = new DatabaseConnectionInfo(arguments.getArgument("db-host", "localhost"),
            arguments.getArgument("db-port", "5432"), arguments.getArgument("db-name", "eucalyptus_reporting"),
            arguments.getArgument("db-user", "eucalyptus"), dbPassword);

    if (arguments.hasArgument("db-ssl")) {
        DataWarehouseSSLSocketFactory.initialize(arguments.getArgument("db-ssl-provider", null),
                arguments.getArgument("db-ssl-protocol", DEFAULT_PROTOCOL),
                arguments.getArgument("db-ssl-ciphers", DEFAULT_CIPHER_STRINGS),
                arguments.getArgument("db-ssl-fingerprint", null),
                !arguments.hasArgument("db-ssl-skip-verify"));
    }

    properties.setProperty("jdbc-0.proxool.driver-url",
            String.format("jdbc:postgresql://%s:%s/%s%s", databaseConnectionInfo.getHost(),
                    databaseConnectionInfo.getPort(), databaseConnectionInfo.getName(),
                    arguments.hasArgument("db-ssl")
                            ? "?ssl=true&sslfactory=com.eucalyptus.reporting.dw.DataWarehouseSSLSocketFactory"
                            : ""));
    properties.setProperty("jdbc-0.user", databaseConnectionInfo.getUser());
    properties.setProperty("jdbc-0.password", databaseConnectionInfo.getPass());

    try {
        PropertyConfigurator.configure(properties);
    } catch (ProxoolException e) {
        throw Exceptions.toUndeclared(e);
    }

    Ejb3Configuration config = new Ejb3Configuration();
    config.setProperties(properties);
    for (Class<?> eventClass : ExportUtils.getPersistentClasses()) {
        config.addAnnotatedClass(eventClass);
    }
    PersistenceContexts.registerPersistenceContext("eucalyptus_reporting", config);
}

From source file:org.rioproject.impl.util.DownloadManager.java

private DownloadRecord doDownload(StagedData dAttrs, boolean postInstall) throws IOException {
    String installRoot;//from  w  w w .  j  a v a  2s  . c om
    int extractedSize = 0;
    long extractTime = 0;
    boolean unarchived = false;
    boolean createdTargetPath = false;

    if (dAttrs == null)
        throw new IllegalArgumentException("dAttrs is null");

    URL location = dAttrs.getLocationURL();
    String extension = dAttrs.getInstallRoot();
    boolean unarchive = dAttrs.unarchive();
    if (extension.indexOf("/") != -1)
        installRoot = extension.replace('/', File.separatorChar);
    else
        installRoot = extension.replace('\\', File.separatorChar);
    File targetPath = new File(FileUtils.makeFileName(installPath, installRoot));
    if (!targetPath.exists()) {
        if (targetPath.mkdirs()) {
            logger.trace("Created {}", targetPath.getPath());
        }
        if (!targetPath.exists())
            throw new IOException("Failed to create: " + installPath);
        createdTargetPath = true;
    }
    if (!targetPath.canWrite())
        throw new IOException("Can not write to : " + installPath);
    String source = location.toExternalForm();
    int index = source.lastIndexOf("/");
    if (index == -1)
        throw new IllegalArgumentException("Don't know how to install : " + source);
    String software = source.substring(index + 1);
    String target = FileUtils.getFilePath(targetPath);
    File targetFile = new File(FileUtils.makeFileName(target, software));
    if (targetFile.exists()) {
        if (!dAttrs.overwrite()) {
            logger.warn("{} exists, stagedData attributes indicate to not overwrite file",
                    FileUtils.getFilePath(targetFile));
            return null;
        } else {
            if (showDownloadTo)
                logger.info("Overwriting {} with {}", FileUtils.getFilePath(targetFile), location);
        }
    } else {
        if (showDownloadTo)
            logger.info("Downloading {} to {}", location, FileUtils.getFilePath(targetFile));
    }
    long t0 = System.currentTimeMillis();
    URLConnection con = location.openConnection();
    int downloadedSize = writeFileFromInputStream(con.getInputStream(), targetFile, con.getContentLength(),
            System.console() != null);
    long t1 = System.currentTimeMillis();
    long downloadTime = t1 - t0;
    long downloadSecs = downloadTime / 1000;
    Date downloadDate = new Date();
    ExtractResults results;
    logger.info("Wrote {}K in {} seconds", (downloadedSize / 1024), (downloadSecs < 1 ? "< 1" : downloadSecs));
    String extractedToPath = null;
    if (unarchive) {
        t0 = System.currentTimeMillis();
        results = extract(targetPath, targetFile);
        t1 = System.currentTimeMillis();
        extractedSize = results.extractedSize;
        if (postInstall)
            postInstallExtractList = results.postInstallExtractList;
        extractTime = t1 - t0;
        unarchived = true;
        extractedToPath = results.extractedToPath;
        if (extractedToPath == null) {
            extractedToPath = FileUtils.getFilePath(targetPath);
        }
    }
    downloadRecord = new DownloadRecord(location, target, software, downloadDate, downloadedSize, extractedSize,
            extractedToPath, unarchived, downloadTime, extractTime);
    downloadRecord.setCreatedParentDirectory(createdTargetPath);
    return (downloadRecord);
}

From source file:io.github.felsenhower.stine_calendar_bot.main.CallLevelWrapper.java

/**
 * Gets the password from stdin//from  ww  w. java 2s .  c  o  m
 * 
 * @param query
 *            the query to the user
 * @param errorMsg
 *            the message to display when the input gets somehow redirected
 *            and System.console() becomes null.
 * @return the entered password
 */
private static String readPassword(String query, String errorMsg) {
    final String result;
    if (System.console() != null) {
        System.err.print(query);
        result = new String(System.console().readPassword());
    } else {
        System.err.println(errorMsg);
        System.err.print(query);
        Scanner scanner = new Scanner(System.in);
        result = scanner.nextLine();
        scanner.close();
    }
    System.err.println();
    return result;
}

From source file:com.liferay.jenkins.tools.JenkinsStatus.java

private void processArgs(String[] args) throws Exception {
    CommandLineParser parser = new DefaultParser();

    Options options = new Options();

    options.addOption("m", "dry-run", false, "Does not fetch remote resources");
    options.addOption("c", "building", true, "Filter build by build state");
    options.addOption("d", "debug", false, "Set logging level to debug");
    options.addOption("f", "file", true, "Path to Jenkins servers list");
    options.addOption("h", "aliases", true, "Path to aliases file");
    options.addOption("i", "info", false, "Set logging level to info");
    options.addOption("n", "name", true, "Filter job by exact name");
    options.addOption("r", "result", true, "Filter build by result");
    options.addOption("u", "user", true, "Username used in authentication");

    options.addOption(Option.builder().longOpt("list-jobs").desc("List matching jobs").build());
    options.addOption(Option.builder().longOpt("name-contains").hasArg()
            .desc("Filter job by name containing specified string").build());
    options.addOption(Option.builder().longOpt("name-regex").hasArg()
            .desc("Filter job by name matching specified regular expression").build());
    options.addOption(Option.builder("p").longOpt("parameters").hasArgs().desc("Filter build by parameters")
            .valueSeparator(',').build());
    options.addOption(//  w ww. ja v a  2s . com
            Option.builder("b").longOpt("before").hasArgs().desc("Filter build before specified time").build());
    options.addOption(
            Option.builder("a").longOpt("after").hasArgs().desc("Filter builds after specified time").build());
    options.addOption(Option.builder("s").longOpt("between").hasArgs()
            .desc("Filter builds between two specified UNIX timestamps").build());
    options.addOption(Option.builder("e").longOpt("equals").hasArgs()
            .desc("Filter builds with specific duration").build());
    options.addOption(
            Option.builder("l").longOpt("less").hasArgs().desc("Filter builds less than the duration").build());
    options.addOption(Option.builder("g").longOpt("greater").hasArgs()
            .desc("Filter builds greater than the duration").build());
    options.addOption(Option.builder().longOpt("console-contains").hasArgs()
            .desc("Filter build by matching console text").build());

    CommandLine line = parser.parse(options, args);

    if (line.hasOption("dry-run")) {
        dryRun = true;
    }

    if (line.hasOption("list-jobs")) {
        listJobs = true;
    }

    if (line.hasOption("info")) {
        Logger rootLogger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
        rootLogger.setLevel(Level.INFO);

        showBuildInfo = true;
    }

    if (line.hasOption("debug")) {
        Logger rootLogger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
        rootLogger.setLevel(Level.DEBUG);

        showBuildInfo = true;
    }

    if (line.hasOption("file")) {
        logger.debug("Loading file {}", line.getOptionValue("f"));

        serversListFile = new File(line.getOptionValue("f"));
    }

    if (line.hasOption("aliases")) {
        logger.debug("Loading file {}", line.getOptionValue("h"));

        aliasesFile = new File(line.getOptionValue("h"));
    }

    if (line.hasOption("user")) {
        Console console = System.console();

        if (console == null) {
            throw new IllegalStateException("Unable to get Console instance");
        }

        String username = line.getOptionValue("u");
        String password = new String(console.readPassword("Enter password for " + username + " :"));

        if (aliasesFile.isFile()) {
            jsonGetter = new RemoteJsonGetter(username, password, REQUEST_TIMEOUT, aliasesFile);
        } else {
            jsonGetter = new RemoteJsonGetter(username, password, REQUEST_TIMEOUT);
        }
    } else if (aliasesFile.isFile()) {
        jsonGetter = new LocalJsonGetter(REQUEST_TIMEOUT, aliasesFile);
    }

    if (line.hasOption("name")) {
        jobMatchers.add(new NameEqualsMatcher(line.getOptionValue("name")));
    }

    if (line.hasOption("name-contains")) {
        jobMatchers.add(new NameContainsMatcher(line.getOptionValue("name-contains")));
    }

    if (line.hasOption("name-regex")) {
        jobMatchers.add(new NameRegexMatcher(line.getOptionValue("name-regex")));
    }

    if (line.hasOption("building")) {
        buildMatchers.add(new BuildingMatcher(line.getOptionValue("c")));
    }

    if (line.hasOption("parameters")) {
        buildMatchers.add(new ParametersMatcher(line.getOptionValues("p")));
    }

    if (line.hasOption("result")) {
        buildMatchers.add(new ResultMatcher(line.getOptionValue("r")));
    }

    if (line.hasOption("before")) {
        buildMatchers.add(new BeforeTimestampMatcher(line.getOptionValues("b")));
    }

    if (line.hasOption("after")) {
        buildMatchers.add(new AfterTimestampMatcher(line.getOptionValues("a")));
    }

    if (line.hasOption("between")) {
        buildMatchers.add(new BetweenTimestampsMatcher(line.getOptionValues("s")));
    }

    if (line.hasOption("greater")) {
        buildMatchers.add(new GreaterThanDurationMatcher(line.getOptionValues("g")));
    }

    else if (line.hasOption("less")) {
        buildMatchers.add(new LessThanDurationMatcher(line.getOptionValues("l")));
    }

    if (line.hasOption("console-contains")) {
        buildMatchers.add(new ConsoleContainsMatcher(jsonGetter, line.getOptionValues("console-contains")));
    }
}

From source file:co.cask.cdap.security.tools.AccessTokenClient.java

/**
 * Parse the command line arguments.//w w w  .j  av a 2s  .  co  m
 */
void parseArguments(String[] args) {
    CommandLineParser parser = new BasicParser();
    CommandLine commandLine = null;
    try {
        commandLine = parser.parse(options, args);
    } catch (org.apache.commons.cli.ParseException e) {
        System.err.println("Could not parse arguments correctly.");
        usage(true);
    }

    if (commandLine.hasOption(ConfigurableOptions.HELP)) {
        usage(false);
        help = true;
        return;
    }

    useSsl = commandLine.hasOption(ConfigurableOptions.SSL);
    disableCertCheck = commandLine.hasOption(ConfigurableOptions.DISABLE_CERT_CHECK);

    host = commandLine.getOptionValue(ConfigurableOptions.HOST, "localhost");

    if (commandLine.hasOption(ConfigurableOptions.PORT)) {
        try {
            port = Integer.parseInt(commandLine.getOptionValue(ConfigurableOptions.PORT));
        } catch (NumberFormatException e) {
            usage("--port must be an integer value");
        }
    } else {
        port = (useSsl) ? SSL_PORT : NO_SSL_PORT;
    }

    username = commandLine.getOptionValue(ConfigurableOptions.USER_NAME, System.getProperty("user.name"));

    if (username == null) {
        usage("Specify --username to login as a user.");
    }

    password = commandLine.getOptionValue(ConfigurableOptions.PASSWORD);

    if (password == null) {
        Console console = System.console();
        password = String.valueOf(console.readPassword(String.format("Password for %s: ", username)));
    }

    if (commandLine.hasOption(ConfigurableOptions.FILE)) {
        filePath = commandLine.getOptionValue(ConfigurableOptions.FILE);
    } else {
        usage("Specify --file to save to file");
    }

    if (commandLine.getArgs().length > 0) {
        usage(true);
    }
}

From source file:org.ejbca.ui.cli.infrastructure.parameter.ParameterHandler.java

/**
 * This method takes the parameters given by the command line and returns them as a map keyed to the flags
 * //w  ww.jav a 2  s  .  c  om
 * @param arguments the parameters as given by the command line
 * @return a map of parameters and their values, null if command cannot run.
 */
public ParameterContainer parseParameters(String... arguments) {
    ParameterContainer result = new ParameterContainer();
    List<String> argumentList = new ArrayList<String>();
    boolean verbose = false;
    for (int i = 0; i < arguments.length; i++) {
        String argument = arguments[i];
        //Glue together any quotes that may be mismatched due to spaces
        if ((argument.startsWith("'") && !argument.endsWith("'"))
                || (argument.startsWith("\"") && !argument.endsWith("\""))) {
            final String quoteType = argument.substring(0, 1);
            for (int j = i + 1; j < arguments.length; j++) {
                if (arguments[j].startsWith(quoteType)) {
                    log.error("ERROR: Unclosed quote: " + argument);
                    return null;
                } else if (arguments[j].endsWith(quoteType)) {
                    argument += " " + arguments[j];
                    i = j;
                    break;
                } else {
                    argument += " " + arguments[j];
                }
            }
        }
        if (argument.equals(VERBOSE_KEY)) {
            verbose = true;
        } else {
            argumentList.add(argument);
        }
        if (log.isDebugEnabled()) {
            log.debug("ARGUMENT: " + argument);
        }
    }

    List<String> unknownArguments = new ArrayList<String>();
    List<Parameter> missingArguments = new ArrayList<Parameter>();
    LinkedList<String> standaloneParametersDefensiveCopy = new LinkedList<String>(standaloneParameters);
    //Get a list of all parameters
    for (int i = 0; i < argumentList.size(); i++) {
        boolean isStandalone = false;
        String parameterString = argumentList.get(i);
        //Handle the case where the command line may have split up an argument with a a space that's in quotes

        //Handle the case of -argument=value, but ignore if in quotes
        if (parameterString.matches("^-.*=.*")) {
            //If so, split the switch and value up.
            int valueIndex = parameterString.indexOf("=") + 1;
            argumentList.add(i + 1, (valueIndex >= parameterString.length() ? ""
                    : parameterString.substring(valueIndex, parameterString.length())));
            parameterString = parameterString.substring(0, valueIndex - 1);
        }
        if (result.containsKey(parameterString)) {
            log.info("ERROR: Multiple parameters of type " + parameterString + " encountered.");
            return null;
        }
        Parameter parameter = parameterMap.get(parameterString);
        String value;
        if (parameter == null) {
            //Presume that it might be a standalone argument
            if (standaloneParametersDefensiveCopy.size() > 0 && !parameterString.startsWith("-")) {
                value = parameterString;
                parameterString = standaloneParametersDefensiveCopy.removeFirst();
                isStandalone = true;
            } else {
                unknownArguments.add(parameterString);
                continue;
            }
        } else {
            if (parameter.getParameterMode() == ParameterMode.ARGUMENT) {
                //Check that the following argument exists and isn't a switch (ignoring negative numbers)
                if ((i + 1) >= argumentList.size() || argumentList.get(i + 1).matches("^-[A-z]+$")) {
                    log.info("ERROR: Missing argument.");
                    log.info(TAB + parameterString + " is an argument and requires a parameter following it.");
                    continue;
                } else {
                    value = argumentList.get(i + 1);
                    i++;
                }
            } else if (parameter.getParameterMode() == ParameterMode.FLAG) {
                value = "";
            } else if (parameter.getParameterMode() == ParameterMode.INPUT) {
                log.info("Enter value for " + parameterString + ": ");
                value = System.console().readLine();
            } else if (parameter.getParameterMode() == ParameterMode.PASSWORD) {
                log.info("Enter password for parameter (" + parameterString + "): ");
                value = new String(System.console().readPassword());
            } else {
                throw new IllegalStateException(
                        parameter.getParameterMode().name() + " was an unknown parameter type.");
            }
        }
        if (verbose) {
            if (!StringUtils.isEmpty(value)
                    && (parameter == null || (parameter.getParameterMode() != ParameterMode.PASSWORD
                            && parameter.getParameterMode() != ParameterMode.FLAG))) {
                log.error("SETTING: " + parameterString + " as " + value);
            }
        }

        //Lastly, strip any quotes 
        if ((value.startsWith("'") && value.endsWith("'"))
                || (value.startsWith("\"") && value.endsWith("\""))) {
            value = value.substring(1, value.length() - 1);
        }

        result.put(parameterString, value, isStandalone);
    }

    if (result.containsKey(HELP_KEY)) {
        //Do not validate if help was requested
        return result;
    }

    //Check for mandatory parameters
    for (final String mandatoryParameter : mandatoryParameters) {
        if (!result.containsKey(mandatoryParameter)) {
            missingArguments.add(parameterMap.get(mandatoryParameter));
        }
    }
    if (unknownArguments.size() == 0 && missingArguments.size() == 0) {
        return result;
    } else {
        StringBuilder sb = new StringBuilder();
        sb.append("ERROR: Incorrect parameter usage.");
        if (unknownArguments.size() > 0) {
            sb.append("\n");
            sb.append(tab(1) + "The following arguments are unknown:\n");
            for (String unknownParameter : unknownArguments) {
                sb.append(tab(2) + unknownParameter + "\n");
            }
        }
        if (missingArguments.size() > 0) {
            sb.append("\n");
            sb.append(tab(1) + "The following mandatory arguments are missing or poorly formed:\n");
            int longestKeyWord = 0;
            for (Parameter missingParameter : missingArguments) {
                if (missingParameter.getKeyWord().length() > longestKeyWord) {
                    longestKeyWord = missingParameter.getKeyWord().length();
                }
            }
            String indent = tab(longestKeyWord / TAB.length() + 2);
            for (Parameter missingParameter : missingArguments) {
                sb.append(tab(2) + missingParameter.getKeyWord()
                        + indent.substring(missingParameter.getKeyWord().length()));
                List<String> lines = CommandBase.splitStringIntoLines(missingParameter.getInstruction(),
                        120 - indent.length());
                if (lines.size() > 0) {
                    sb.append(lines.get(0) + "\n");
                    for (int i = 1; i < lines.size(); i++) {
                        sb.append(tab(2) + indent + lines.get(i) + "\n");
                    }
                }

            }
        }
        sb.append(CR + "Run command with \"" + HELP_KEY + "\" to see full manual page.");
        log.info(sb);
        return null;
    }
}

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

protected char[] getCommandLinePassword(CommandLine commandLine) {
    char[] password = null;
    if (commandLine.getOptionValue(CMD_LINE_TOLVEN_PASSWORD_OPTION) != null) {
        password = commandLine.getOptionValue(CMD_LINE_TOLVEN_PASSWORD_OPTION).toCharArray();
    }/*w w  w. j av  a 2s .  c  o  m*/
    if (password == null) {
        if (System.getenv(ENV_TOLVEN_PASSWORD) == null) {
            System.out.print("Password: ");
            password = System.console().readPassword();
        } else {
            password = System.getenv(ENV_TOLVEN_PASSWORD).toCharArray();
        }
    }
    return password;
}

From source file:gobblin.crypto.JCEKSKeystoreCredentialStoreCli.java

public static char[] getPasswordFromConsole() {
    System.out.print("Please enter the keystore password: ");
    return System.console().readPassword();
}

From source file:org.apache.juddi.samples.JuddiAdminService.java

void viewRemoteNodes(String authtoken) throws ConfigurationException, TransportException, RemoteException {

    List<Node> uddiNodeList = clerkManager.getClientConfig().getUDDINodeList();
    System.out.println();//w w  w . ja v a2s.  c  o  m
    System.out.println("Select a node (from *this config)");
    for (int i = 0; i < uddiNodeList.size(); i++) {
        System.out.print(i + 1);
        System.out.println(") " + uddiNodeList.get(i).getName() + uddiNodeList.get(i).getDescription());
    }
    System.out.println("Node #: ");
    int index = Integer.parseInt(System.console().readLine()) - 1;
    String node = uddiNodeList.get(index).getName();
    Transport transport = clerkManager.getTransport(node);

    JUDDIApiPortType juddiApiService = transport.getJUDDIApiService();

    NodeList allNodes = juddiApiService.getAllNodes(authtoken);
    if (allNodes == null || allNodes.getNode().isEmpty()) {
        System.out.println("No nodes registered!");
    } else {
        for (int i = 0; i < allNodes.getNode().size(); i++) {
            System.out
                    .println("_______________________________________________________________________________");
            System.out.println("Name :" + allNodes.getNode().get(i).getName());
            System.out.println("Inquiry :" + allNodes.getNode().get(i).getInquiryUrl());
            System.out.println("Publish :" + allNodes.getNode().get(i).getPublishUrl());
            System.out.println("Securit :" + allNodes.getNode().get(i).getSecurityUrl());
            System.out.println("Replication :" + allNodes.getNode().get(i).getReplicationUrl());
            System.out.println("Subscription :" + allNodes.getNode().get(i).getSubscriptionUrl());
            System.out.println("Custody Xfer :" + allNodes.getNode().get(i).getCustodyTransferUrl());

        }
    }

}

From source file:org.jboss.windup.plugin.WindupMojo.java

/**
 * Install core addons if none are installed; then start.
 *///from  ww  w  .  jav a2 s  .com
public void start(boolean exitAfter, boolean batchMode, Furnace furnace)
        throws InterruptedException, ExecutionException {
    if (exitAfter)
        return;

    if (!batchMode) {
        List<AddonId> addonIds = getEnabledAddonIds(furnace);
        if (addonIds.isEmpty()) {
            String result = System.console()
                    .readLine("There are no addons installed; install core addons now? [Y,n] ");
            if (!"n".equalsIgnoreCase(result.trim())) {
                install("core", batchMode, furnace);
            }
        }
    }

}