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:edu.umd.cs.submit.CommandLineSubmit.java

/**
 * @param submitUserFile//w ww  .j  av  a  2s .c  o m
 * @param courseKey
 * @param projectNumber
 * @param authenticationType
 * @param baseURL
 * @throws IOException
 * @throws UnsupportedEncodingException
 * @throws URISyntaxException
 * @throws HttpException
 */
public static void createSubmitUser(File submitUserFile, String courseKey, String projectNumber,
        String authenticationType, String baseURL)
        throws IOException, UnsupportedEncodingException, URISyntaxException, HttpException {
    PrintWriter newUserProjectFile;
    if (authenticationType.equals("openid")) {
        String[] result = getSubmitUserForOpenId(courseKey, projectNumber, baseURL);
        String classAccount = result[0];
        String onetimePassword = result[1];
        newUserProjectFile = new PrintWriter(new FileWriter(submitUserFile));
        newUserProjectFile.println("classAccount=" + classAccount);
        newUserProjectFile.println("oneTimePassword=" + onetimePassword);
    } else {
        String loginName, password;

        Console console = System.console();

        System.out.println("Please enter your LDAP username and password");
        System.out.print("LDAP username: ");
        loginName = console.readLine();
        System.out.println("Password: ");
        password = new String(console.readPassword());
        System.out.println("Thanks!");
        System.out.println("Preparing for submission. Please wait...");

        String url = baseURL + "/eclipse/NegotiateOneTimePassword";
        PostMethod post = new PostMethod(url);

        post.addParameter("loginName", loginName);
        post.addParameter("password", password);

        post.addParameter("courseKey", courseKey);
        post.addParameter("projectNumber", projectNumber);

        HttpClient client = new HttpClient();
        client.setConnectionTimeout(HTTP_TIMEOUT);

        // System.out.println("Preparing to execute method");
        int status = client.executeMethod(post);
        // System.out.println("Post finished with status: " +status);

        if (status != HttpStatus.SC_OK) {
            throw new HttpException(
                    "Unable to negotiate one-time password with the server: " + post.getResponseBodyAsString());
        }

        InputStream inputStream = post.getResponseBodyAsStream();
        BufferedReader userStream = new BufferedReader(new InputStreamReader(inputStream));
        newUserProjectFile = new PrintWriter(new FileWriter(submitUserFile));
        while (true) {
            String line = userStream.readLine();
            if (line == null)
                break;
            // System.out.println(line);
            newUserProjectFile.println(line);
        }
        userStream.close();
    }
    newUserProjectFile.close();
    if (!submitUserFile.canRead()) {
        System.out.println("Can't generate or access " + submitUserFile);
        System.exit(1);
    }
}

From source file:net.pms.util.ProcessUtil.java

public static ArrayList<String> getUMSCommand() {
    ArrayList<String> reboot = new ArrayList<>();
    reboot.add(StringUtil.quoteArg(System.getProperty("java.home") + File.separator + "bin" + File.separator
            + ((Platform.isWindows() && System.console() == null) ? "javaw" : "java")));
    for (String jvmArg : ManagementFactory.getRuntimeMXBean().getInputArguments()) {
        reboot.add(StringUtil.quoteArg(jvmArg));
    }//from   w w w . java  2s  . c o  m
    reboot.add("-cp");
    reboot.add(ManagementFactory.getRuntimeMXBean().getClassPath());
    // Could also use generic main discovery instead:
    // see http://stackoverflow.com/questions/41894/0-program-name-in-java-discover-main-class
    reboot.add(PMS.class.getName());
    return reboot;
}

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

void registerLocalNodeToRemoteNode(String authtoken, Node cfg, Node publishTo) throws Exception {

    Transport transport = clerkManager.getTransport(publishTo.getName());

    UDDISecurityPortType security2 = transport.getUDDISecurityService();
    System.out.print("username: ");
    String uname = System.console().readLine();
    char passwordArray[] = System.console().readPassword("password: ");
    GetAuthToken getAuthTokenRoot = new GetAuthToken();
    getAuthTokenRoot.setUserID(uname);/*w w w  .  j a va 2 s  . c om*/
    getAuthTokenRoot.setCred(new String(passwordArray));
    authtoken = security2.getAuthToken(getAuthTokenRoot).getAuthInfo();
    System.out.println("Success!");

    JUDDIApiPortType juddiApiService = transport.getJUDDIApiService();
    SaveNode sn = new SaveNode();
    sn.setAuthInfo(authtoken);
    sn.getNode().add(cfg);
    NodeDetail saveNode = juddiApiService.saveNode(sn);
    JAXB.marshal(saveNode, System.out);
    System.out.println("Success.");

}

From source file:com.hp.mqm.clt.CliParser.java

public Settings parse(String[] args) {
    Settings settings = new Settings();
    CommandLineParser parser = new DefaultParser();
    try {//from   w  ww. j  ava  2 s.  c o m
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("h")) {
            printHelp();
            System.exit(ReturnCode.SUCCESS.getReturnCode());
        }

        if (cmd.hasOption("v")) {
            printVersion();
            System.exit(ReturnCode.SUCCESS.getReturnCode());
        }

        if (!areCmdArgsValid(cmd)) {
            printHelp();
            System.exit(ReturnCode.FAILURE.getReturnCode());
        }

        if (!addInputFilesToSettings(cmd, settings)) {
            printHelp();
            System.exit(ReturnCode.FAILURE.getReturnCode());
        }

        // load config
        String filename = null;
        if (cmd.hasOption("c")) {
            filename = cmd.getOptionValue("c");
        }
        try {
            settings.load(filename);
        } catch (NumberFormatException e) {
            System.out.println("Can not convert string from properties file to integer: " + e.getMessage());
            System.exit(ReturnCode.FAILURE.getReturnCode());
        } catch (IllegalArgumentException e) {
            // Inform user that loading was not successful
            // Configuration must be specified in arguments in this case
            System.out.println(e.getMessage());
        } catch (IOException e) {
            System.out.println("Can not read from properties file: " + filename);
            System.exit(ReturnCode.FAILURE.getReturnCode());
        }

        if (cmd.hasOption("i")) {
            settings.setInternal(true);
        }

        if (cmd.hasOption("e")) {
            settings.setSkipErrors(true);
        }

        if (cmd.hasOption("o")) {
            settings.setOutputFile(cmd.getOptionValue("o"));
        }

        if (cmd.hasOption("s")) {
            settings.setServer(cmd.getOptionValue("s"));
        }

        if (cmd.hasOption("d")) {
            settings.setSharedspace(((Long) cmd.getParsedOptionValue("d")).intValue());
        }

        if (cmd.hasOption("w")) {
            settings.setWorkspace(((Long) cmd.getParsedOptionValue("w")).intValue());
        }

        if (cmd.hasOption("u")) {
            settings.setUser(cmd.getOptionValue("u"));
        }

        if (settings.getOutputFile() == null) {
            if (cmd.hasOption("p")) {
                settings.setPassword(cmd.getOptionValue("p"));
            } else if (cmd.hasOption("password-file")) {
                try {
                    settings.setPassword(
                            FileUtils.readFileToString(new File(cmd.getOptionValue("password-file"))));
                } catch (IOException e) {
                    System.out
                            .println("Can not read the password file: " + cmd.getOptionValue("password-file"));
                    System.exit(ReturnCode.FAILURE.getReturnCode());
                }
            } else {
                System.out.println("Please enter your password if it's required and hit enter: ");
                settings.setPassword(new String(System.console().readPassword()));
            }
        }

        if (cmd.hasOption("proxy-host")) {
            settings.setProxyHost(cmd.getOptionValue("proxy-host"));
        }

        if (cmd.hasOption("proxy-port")) {
            settings.setProxyPort(((Long) cmd.getParsedOptionValue("proxy-port")).intValue());
        }

        if (cmd.hasOption("proxy-user")) {
            settings.setProxyUser(cmd.getOptionValue("proxy-user"));
        }

        if (settings.getOutputFile() == null && StringUtils.isNotEmpty(settings.getProxyUser())) {
            if (cmd.hasOption("proxy-password")) {
                settings.setProxyPassword(cmd.getOptionValue("proxy-password"));
            } else if (cmd.hasOption("proxy-password-file")) {
                try {
                    settings.setProxyPassword(
                            FileUtils.readFileToString(new File(cmd.getOptionValue("proxy-password-file"))));
                } catch (IOException e) {
                    System.out.println(
                            "Can not read the password file: " + cmd.getOptionValue("proxy-password-file"));
                    System.exit(ReturnCode.FAILURE.getReturnCode());
                }
            } else {
                System.out.println("Please enter your proxy password if it's required and hit enter: ");
                settings.setProxyPassword(new String(System.console().readPassword()));
            }
        }

        if (cmd.hasOption("check-result")) {
            settings.setCheckResult(true);
        }

        if (cmd.hasOption("check-result-timeout")) {
            settings.setCheckResultTimeout(
                    ((Long) cmd.getParsedOptionValue("check-status-timeout")).intValue());
        }

        if (cmd.hasOption("t")) {
            settings.setTags(Arrays.asList(cmd.getOptionValues("t")));
        }

        if (cmd.hasOption("f")) {
            settings.setFields(Arrays.asList(cmd.getOptionValues("f")));
        }

        if (cmd.hasOption("r")) {
            settings.setRelease(((Long) cmd.getParsedOptionValue("r")).intValue());
        }

        if (cmd.hasOption("started")) {
            settings.setStarted((Long) cmd.getParsedOptionValue("started"));
        }

        if (cmd.hasOption("a")) {
            settings.setProductAreas(cmd.getOptionValues("a"));
        }

        if (cmd.hasOption("b")) {
            settings.setBacklogItems(cmd.getOptionValues("b"));
        }

        if (!areSettingsValid(settings)) {
            System.exit(ReturnCode.FAILURE.getReturnCode());
        }

    } catch (ParseException e) {
        printHelp();
        System.exit(ReturnCode.FAILURE.getReturnCode());
    }
    return settings;
}

From source file:com.google.feedserver.tools.FeedServerClientTool.java

protected Console getConsole() {
    Console console = System.console();
    if (console == null) {
        throw new NullPointerException("no console");
    } else {//  ww  w .  ja va  2s . com
        return console;
    }
}

From source file:com.netscape.cmstools.cli.MainCLI.java

public String promptForPassword(String prompt) throws IOException {
    char[] password = null;
    Console console = System.console();
    System.out.print(prompt);/*ww  w .  j  av a2 s.c  om*/
    password = console.readPassword();
    return new String(password);
}

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

public boolean install(String addonCoordinates, boolean batchMode, Furnace furnace) {
    Version runtimeAPIVersion = AddonRepositoryImpl.getRuntimeAPIVersion();
    try {/*from   w ww.ja  v  a 2 s . c  o m*/
        AddonDependencyResolver resolver = new MavenAddonDependencyResolver();
        AddonManagerImpl addonManager = new AddonManagerImpl(furnace, resolver);

        AddonId addon;
        // This allows windup --install maven
        if (addonCoordinates.contains(",")) {
            if (addonCoordinates.contains(":")) {
                addon = AddonId.fromCoordinates(addonCoordinates);
            } else {
                addon = AddonId.fromCoordinates(FORGE_ADDON_GROUP_ID + addonCoordinates);
            }
        } else {
            AddonId[] versions;
            String coordinate;
            if (addonCoordinates.contains(":")) {
                coordinate = addonCoordinates;
                versions = resolver.resolveVersions(addonCoordinates).get();
            } else {
                coordinate = FORGE_ADDON_GROUP_ID + addonCoordinates;
                versions = resolver.resolveVersions(coordinate).get();
            }

            if (versions.length == 0) {
                throw new IllegalArgumentException("No Artifact version found for " + coordinate);
            } else {
                AddonId selected = null;
                for (int i = versions.length - 1; selected == null && i >= 0; i--) {
                    String apiVersion = resolver.resolveAPIVersion(versions[i]).get();
                    if (apiVersion != null
                            && Versions.isApiCompatible(runtimeAPIVersion, new SingleVersion(apiVersion))) {
                        selected = versions[i];
                    }
                }
                if (selected == null) {
                    throw new IllegalArgumentException("No compatible addon API version found for " + coordinate
                            + " for API " + runtimeAPIVersion);
                }

                addon = selected;
            }
        }

        AddonActionRequest request = addonManager.install(addon);
        System.out.println(request);
        if (!batchMode) {
            String result = System.console().readLine("Confirm installation [Y/n]? ");
            if ("n".equalsIgnoreCase(result.trim())) {
                System.out.println("Installation aborted.");
                return false;
            }
        }
        request.perform();
        System.out.println("Installation completed successfully.");
        System.out.println();
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("> Forge version [" + runtimeAPIVersion + "]");
    }
    return true;
}

From source file:com.act.analysis.surfactant.SurfactantLabeler.java

public void runAnalysis(String licensePath, File inputFile, File outputFile, File inchiSourceFile,
        String inchiJoinField) throws Exception {
    LicenseManager.setLicenseFile(licensePath);
    // If a separate InChI source was specified, build a map from the join key to that source's per-molecule data.
    Map<String, Map<String, String>> inchiSource = null;
    if (inchiSourceFile != null) {
        TSVParser inchiSourceParser = new TSVParser();
        inchiSourceParser.parse(inchiSourceFile);
        List<Map<String, String>> inchiSourceData = inchiSourceParser.getResults();

        inchiSource = new HashMap<>(inchiSourceData.size());
        int i = 0;
        for (Map<String, String> row : inchiSourceData) {
            i++;/*from   ww w .  j  a  va 2s  . c om*/
            if (!row.containsKey(inchiJoinField)) {
                throw new RuntimeException(
                        String.format("Missing inchi join field %s on row %d of inchi source file %s",
                                inchiJoinField, i, inchiSourceFile.getAbsolutePath()));
            }
            inchiSource.put(row.get(inchiJoinField), row);
        }
        System.out.format("Loaded %d inchi source entries from %s\n", inchiSource.size(),
                inchiSourceFile.getAbsolutePath());
    }

    // Create the visualization environment.
    JFrame jFrame = new JFrame();
    jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    MSpaceEasy mspace = new MSpaceEasy(1, 2, true);
    mspace.addCanvas(jFrame.getContentPane());
    mspace.setSize(1200, 600);
    jFrame.pack();
    jFrame.setVisible(true);

    /* Read all the input chemicals at once.  We don't expect this file to be too big.  Do this before touching the
     * (possibly non-empty) results file in case there's a problem with the input. */
    TSVParser inputChemsParser = new TSVParser();
    inputChemsParser.parse(inputFile);
    List<Map<String, String>> chemicals = inputChemsParser.getResults();

    /* Read in any old results to find where we left off, and write them back to the (truncated) results file again.
     * TODO: add append mode to TSVWriter.  This re-writing stuff is kinda silly. */
    List<Map<String, String>> oldResults = new ArrayList<>();
    if (outputFile.exists()) {
        TSVParser oldResultsParser = new TSVParser();
        oldResultsParser.parse(outputFile);
        oldResults.addAll(oldResultsParser.getResults());
    }

    TSVWriter<String, String> resultsWriter = new TSVWriter<>(Arrays.asList("name", "id", "inchi", "label"));
    resultsWriter.open(outputFile);
    Set<String> knownInchis = new HashSet<>();
    for (Map<String, String> row : oldResults) {
        knownInchis.add(row.get("inchi"));
        resultsWriter.append(row);
    }
    resultsWriter.flush();

    int molNumber = 0;
    try {
        Console c = System.console();
        while (molNumber < chemicals.size()) {
            // Copy the source data; we're gonna add some fields to it, and a clean copy might come in handy.
            Map<String, String> r = new HashMap<>(chemicals.get(molNumber));

            // Lookup the InChI source data by this row's join field if a source is defined.
            if (inchiSource != null) {
                Map<String, String> sourceData = inchiSource.get(chemicals.get(molNumber).get(inchiJoinField));
                r.put("inchi", sourceData.get("inchi"));
                r.put("name", sourceData.get("name"));
            }

            String inchi = r.get("inchi");
            // If we've already seen this InChI, skip it and move to the next molecule.  Also de-duplicates a little bit.
            if (knownInchis.contains(inchi)) {
                System.out.format("Skpping known molecule %d\n", molNumber);
                molNumber++;
                continue;
            }
            knownInchis.add(inchi);

            /* Remove all existing molecules from the visualizer, draw the new one, and then reset/refresh to ensure both
             * panels are displayed (sometimes one of the visualizations is corrupted w/o user input due to some strange
             * mspace issue). */
            mspace.removeAllComponents();
            drawMolecule(mspace, MolImporter.importMol(inchi));
            jFrame.pack();
            mspace.resetAll();
            mspace.refresh();

            // Very liberally ask for a label.  TODO: figure out how to accept key input on the jFrame (tried+failed once).
            System.out.format("%s (%s)\n", r.get("name"), inchiJoinField == null ? "" : r.get(inchiJoinField));
            System.out.format("Input (?/1/0):\n");
            String line = c.readLine();
            String label = "?";
            switch (line) {
            case "1":
                label = "1";
                break;
            case "0":
                label = "0";
                break;
            }
            r.put("label", label);
            resultsWriter.append(r);
            // Flush every time to ensure a clean exit when the user gets tired of labeling.  It happens.
            resultsWriter.flush();

            molNumber++;
        }
    } finally {
        resultsWriter.close();
    }
    System.out.format("Done.\n");
}

From source file:com.opoopress.maven.plugins.plugin.AbstractDeployMojo.java

private static void configureScpWagonIfRequired(Wagon wagon, Log log) {
    log.debug("configureScpWagonIfRequired: " + wagon.getClass().getName());

    if (System.console() == null) {
        log.debug("No System.console(), skip configure Wagon");
        return;// www. jav a2  s .  c  om
    }

    ClassLoader parent = Thread.currentThread().getContextClassLoader();
    if (parent == null) {
        parent = AbstractDeployMojo.class.getClassLoader();
    }
    List<ClassLoader> loaders = new ArrayList<ClassLoader>();
    loaders.add(wagon.getClass().getClassLoader());
    ChainingClassLoader loader = new ChainingClassLoader(parent, loaders);

    Class<?> scpWagonClass;
    try {
        scpWagonClass = ClassUtils.getClass(loader, "org.apache.maven.wagon.providers.ssh.jsch.ScpWagon");
    } catch (ClassNotFoundException e) {
        log.debug(
                "Class 'org.apache.maven.wagon.providers.ssh.jsch.ScpWagon' not found, skip configure Wagon.");
        return;
    }

    //is ScpWagon
    if (scpWagonClass.isInstance(wagon)) {
        try {
            Class<?> userInfoClass = ClassUtils.getClass(loader,
                    "com.opoopress.maven.plugins.plugin.ssh.SystemConsoleInteractiveUserInfo");
            Object userInfo = userInfoClass.newInstance();
            MethodUtils.invokeMethod(wagon, "setInteractiveUserInfo", userInfo);
            log.debug("ScpWagon using SystemConsoleInteractiveUserInfo(Java 6+).");
        } catch (ClassNotFoundException e) {
            log.debug(
                    "Class 'com.opoopress.maven.plugins.plugin.ssh.SystemConsoleInteractiveUserInfo' not found, skip configure Wagon.");
        } catch (InstantiationException e) {
            log.debug("Instantiate class exception", e);
        } catch (IllegalAccessException e) {
            log.debug(e.getMessage(), e);
        } catch (NoSuchMethodException e) {
            log.debug(e.getMessage(), e);
        } catch (InvocationTargetException e) {
            log.debug(e.getMessage(), e);
        }
    } else {
        log.debug("Not a ScpWagon.");
    }
}

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

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

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

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

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

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

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