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:gov.va.isaac.mojos.profileSync.ProfilesMojoBase.java

protected String getPassword() throws MojoExecutionException {
    if (password == null) {
        password = System.getProperty(PROFILE_SYNC_PASSWORD_PROPERTY);

        //still blank, try the passed in param
        if (StringUtils.isBlank(password)) {
            password = profileSyncPassword;
        }//from ww  w .  j  av a  2  s  .  c  om

        //still no password, prompt if allowed
        if (StringUtils.isBlank(password) && !Boolean.getBoolean(PROFILE_SYNC_NO_PROMPTS)) {
            Callable<Void> callable = new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    try {
                        if (!disableHintGiven) {
                            System.out.println("To disable remote sync during build, add '-D"
                                    + PROFILE_SYNC_DISABLE + "=true' to your maven command");
                            disableHintGiven = true;
                        }
                        System.out.println("Enter the " + config_.getChangeSetUrlType().name()
                                + " password for the Profiles/Changset remote store: ("
                                + config_.getChangeSetUrl() + "):");

                        //Use console if available, for password masking
                        Console console = System.console();
                        if (console != null) {
                            password = new String(console.readPassword());
                        } else {
                            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                            password = br.readLine();
                        }
                    } catch (IOException e) {
                        throw new MojoExecutionException("Error reading password from console");
                    }
                    return null;
                }
            };

            try {
                Executors.newSingleThreadExecutor(new ThreadFactory() {
                    @Override
                    public Thread newThread(Runnable r) {
                        Thread t = new Thread(r, "User Password Prompt Thread");
                        t.setDaemon(true);
                        return t;
                    }
                }).submit(callable).get(2, TimeUnit.MINUTES);
            } catch (TimeoutException | InterruptedException e) {
                throw new MojoExecutionException("Password not provided within timeout");
            } catch (ExecutionException ee) {
                throw (ee.getCause() instanceof MojoExecutionException ? (MojoExecutionException) ee.getCause()
                        : new MojoExecutionException("Unexpected", ee.getCause()));
            }
        }
    }
    return password;
}

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

void setReplicationConfig(String authtoken) throws Exception {
    List<Node> uddiNodeList = clerkManager.getClientConfig().getUDDINodeList();
    System.out.println();//  ww  w.j  a  v a  2 s  .  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();
    System.out.println("fetching...");
    //NodeList allNodes = juddiApiService.getAllNodes(authtoken);
    ReplicationConfiguration replicationNodes = null;
    try {
        replicationNodes = juddiApiService.getReplicationNodes(authtoken);
    } catch (Exception ex) {
        System.out.println("Error getting replication config");
        ex.printStackTrace();
        replicationNodes = new ReplicationConfiguration();

    }
    String input = "";
    while (!"d".equalsIgnoreCase(input) && !"q".equalsIgnoreCase(input)) {
        System.out.println("Current Config:");
        JAXB.marshal(replicationNodes, System.out);
        System.out.println("1) Remove a replication node");
        System.out.println("2) Add a replication node");
        System.out.println("3) Remove an Edge");
        System.out.println("4) Add an Edge");
        System.out.println("5) Set Registry Contact");
        System.out.println("6) Add Operator info");
        System.out.println("7) Remove Operator info");
        System.out.println("d) Done, save changes");
        System.out.println("q) Quit and abandon changes");

        input = System.console().readLine();
        if (input.equalsIgnoreCase("1")) {
            menu_RemoveReplicationNode(replicationNodes);
        } else if (input.equalsIgnoreCase("2")) {
            menu_AddReplicationNode(replicationNodes, juddiApiService, authtoken);
        } else if (input.equalsIgnoreCase("d")) {
            if (replicationNodes.getCommunicationGraph() == null) {
                replicationNodes.setCommunicationGraph(new CommunicationGraph());
            }
            if (replicationNodes.getRegistryContact() == null) {
                replicationNodes.setRegistryContact(new ReplicationConfiguration.RegistryContact());
            }
            if (replicationNodes.getRegistryContact().getContact() == null) {
                replicationNodes.getRegistryContact().setContact(new Contact());
                replicationNodes.getRegistryContact().getContact().getPersonName()
                        .add(new PersonName("unknown", null));
            }

            replicationNodes.setSerialNumber(0L);
            replicationNodes.setTimeOfConfigurationUpdate("");
            replicationNodes.setMaximumTimeToGetChanges(BigInteger.ONE);
            replicationNodes.setMaximumTimeToSyncRegistry(BigInteger.ONE);

            JAXB.marshal(replicationNodes, System.out);
            juddiApiService.setReplicationNodes(authtoken, replicationNodes);
        }

    }
    if (input.equalsIgnoreCase("d")) {
        //save the changes
        DispositionReport setReplicationNodes = juddiApiService.setReplicationNodes(authtoken,
                replicationNodes);
        System.out.println("Saved!, dumping config from the server");
        replicationNodes = juddiApiService.getReplicationNodes(authtoken);
        JAXB.marshal(replicationNodes, System.out);

    } else {
        //quit this sub menu
        System.out.println("aborting!");
    }

}

From source file:com.example.dawn.helloandroid.EasyHttpClient.java

public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    System.console().writer().write("check Server\n");
}

From source file:org.ehealth_connector.demo.iti.pix.DemoMPIClient.java

private String readStringFromConsole() {
    try {/*from  ww  w.  j av a2  s.c o m*/
        Console console = System.console();
        return console.readLine();
    } catch (Exception e) {
        log.debug("note: eclipse console does not support input");
        System.out.println("aborted (eclipse console does not support input)");
        return null;
    }
}

From source file:edu.umd.cs.submit.CommandLineSubmit.java

public static String[] getSubmitUserForOpenId(String courseKey, String projectNumber, String baseURL)
        throws UnsupportedEncodingException, URISyntaxException, IOException {
    Console console = System.console();

    boolean requested = false;
    String encodedProjectNumber = URLEncoder.encode(projectNumber, "UTF-8");
    URI u = new URI(baseURL + "/view/submitStatus.jsp?courseKey=" + courseKey + "&projectNumber="
            + encodedProjectNumber);//from   ww w .  jav  a2  s  . c  o  m

    if (java.awt.Desktop.isDesktopSupported()) {
        Desktop desktop = java.awt.Desktop.getDesktop();
        if (desktop.isSupported(Desktop.Action.BROWSE)) {
            System.out.println(
                    "Your browser will connect to the submit server, which may require you to authenticate yourself");
            System.out.println("Please do so, and then you will be shown a page with a textfield on it");
            System.out.println("Then copy that text and paste it into the prompt here");
            desktop.browse(u);
            requested = true;
        }
    }
    if (!requested) {
        System.out.println("Please enter the following URL into your browser");
        System.out.println("  " + u);
        System.out.println();
        System.out.println(
                "Your browser will connect to the submit server, which may require you to authenticate yourself");
        System.out.println("Please do so, and then you will be shown a page with a textfield on it");
        System.out.println("Then copy that text and paste it into the prompt here");

    }
    while (true) {
        System.out.println();
        System.out.println("Submission verification information from browser? ");
        String info = new String(console.readLine());
        if (info.length() > 2) {
            int checksum = Integer.parseInt(info.substring(info.length() - 1), 16);
            info = info.substring(0, info.length() - 1);
            int hash = info.hashCode() & 0x0f;
            if (checksum == hash) {
                String fields[] = info.split(";");
                if (fields.length == 2) {
                    return fields;

                }
            }
        }
        System.out.println("That doesn't seem right");
        System.out.println(
                "The information should be your account name and a string of hexidecimal digits, separated by a semicolon");
        System.out.println("Please try again");
        System.out.println();
    }
}

From source file:net.dv8tion.jda.core.utils.SimpleLog.java

/**
 * Will return whether the program has a console present, or was launched without
 *
 * @return boolean true, if console is present
 *//*from   w  ww . j  a  v a  2s . c o m*/
public static boolean isConsolePresent() {
    return System.console() != null;
}

From source file:org.ut.biolab.medsavant.server.MedSavantServerEngine.java

public MedSavantServerEngine(String databaseHost, int databasePort, String rootUserName, String password)
        throws RemoteException, SQLException, SessionExpiredException {
    host = databaseHost;// ww w . j  av a  2 s  .  c  o m
    port = databasePort;
    rootName = rootUserName;
    pass = password;
    try {
        // get the address of this host.
        thisAddress = (InetAddress.getLocalHost()).toString();
    } catch (Exception e) {
        throw new RemoteException("Can't get inet address.");
    }

    listenOnPort = MedSavantServerUnicastRemoteObject.getListenPort();

    if (!performPreemptiveSystemCheck()) {
        System.out.println("System check FAILED, see errors above");
        System.exit(1);
    }

    System.out.println("Server Information:");
    System.out.println("  SERVER VERSION: " + VersionSettings.getVersionString() + "\n" + "  SERVER ADDRESS: "
            + thisAddress + "\n" + "  LISTENING ON PORT: " + listenOnPort + "\n" + "  EXPORT PORT: "
            + MedSavantServerUnicastRemoteObject.getExportPort() + "\n" + "  MAX THREADS: " + maxThreads + "\n"
            + " MAX IO THREADS: " + MAX_IO_JOBS + "\n");

    //+ "  EXPORTING ON PORT: " + MedSavantServerUnicastRemoteObject.getExportPort());
    try {
        // create the registry and bind the name and object.
        if (isTLSRequired()) {
            System.out.println("SSL/TLS Encryption is enabled, Client authentication is "
                    + (isClientAuthRequired() ? "required." : "NOT required."));
        } else {
            System.out.println("SSL/TLS Encryption is NOT enabled");
            //registry = LocateRegistry.createRegistry(listenOnPort);
        }
        registry = LocateRegistry.createRegistry(listenOnPort, getDefaultClientSocketFactory(),
                getDefaultServerSocketFactory());

        //TODO: get these from the user
        ConnectionController.setHost(databaseHost);
        ConnectionController.setPort(databasePort);

        System.out.println();
        System.out.println("Database Information:");

        System.out.println("  DATABASE ADDRESS: " + databaseHost + "\n" + "  DATABASE PORT: " + databasePort);

        System.out.println("  DATABASE USER: " + rootUserName);
        if (password == null) {
            System.out.print("  PASSWORD FOR " + rootUserName + ": ");
            System.out.flush();
            char[] pass = System.console().readPassword();
            password = new String(pass);
        }

        System.out.print("Connecting to database ... ");
        try {
            ConnectionController.connectOnce(databaseHost, databasePort, "", rootUserName, password);
        } catch (SQLException ex) {
            System.out.println("FAILED");
            throw ex;
        }
        System.out.println("OK");

        bindAdapters(registry);

        System.out.println("\nServer initialized, waiting for incoming connections...");

        EmailLogger.logByEmail("Server booted", "The MedSavant Server Engine successfully booted.");
    } catch (RemoteException e) {
        throw e;
    } catch (SessionExpiredException e) {
        throw e;
    }
}

From source file:nl.paston.bonita.importfile.Main.java

protected static Reader getReader(CommandLine cmd) {
    log.debug("Reading CSV file.");
    while (cmd != null) {
        String fileName = cmd.hasOption(Cmd.CSV_FILE.getName()) ? cmd.getOptionValue(Cmd.CSV_FILE.getName())
                : System.console().readLine("Name of the CSV File to read: ");
        String userDir = System.getProperty("user.dir");
        File file = new File(userDir + File.separatorChar + fileName);
        try {/*from  w  w w  . j  av a  2s  .c  o  m*/
            InputStream is = new FileInputStream(file);
            log.info("Succesfully read CSV file.");
            return new InputStreamReader(is);
        } catch (FileNotFoundException ex) {
            log.error("File cannot be found: " + file.getAbsolutePath());
            System.exit(1);
        }
    }
    return null;
}

From source file:com.netscape.cmstools.client.ClientCertRequestCLI.java

public void execute(String[] args) throws Exception {
    CommandLine cmd = parser.parse(options, args);

    String[] cmdArgs = cmd.getArgs();

    if (cmd.hasOption("help")) {
        printHelp();//from   w  ww  . j  a va  2 s .  c o m
        return;
    }

    if (cmdArgs.length > 1) {
        throw new Exception("Too many arguments specified.");
    }

    String certRequestUsername = cmd.getOptionValue("username");

    String subjectDN;

    if (cmdArgs.length == 0) {
        if (certRequestUsername == null) {
            throw new Exception("Missing subject DN or request username.");
        }

        subjectDN = "UID=" + certRequestUsername;

    } else {
        subjectDN = cmdArgs[0];
    }

    // pkcs10, crmf
    String requestType = cmd.getOptionValue("type", "pkcs10");

    boolean attributeEncoding = cmd.hasOption("attribute-encoding");

    // rsa, ec
    String algorithm = cmd.getOptionValue("algorithm", "rsa");
    int length = Integer.parseInt(cmd.getOptionValue("length", "1024"));

    String curve = cmd.getOptionValue("curve", "nistp256");
    boolean sslECDH = cmd.hasOption("ssl-ecdh");
    boolean temporary = !cmd.hasOption("permanent");

    String s = cmd.getOptionValue("sensitive");
    int sensitive;
    if (s == null) {
        sensitive = -1;
    } else {
        if (!s.equalsIgnoreCase("true") && !s.equalsIgnoreCase("false")) {
            throw new IllegalArgumentException("Invalid sensitive parameter: " + s);
        }
        sensitive = Boolean.parseBoolean(s) ? 1 : 0;
    }

    s = cmd.getOptionValue("extractable");
    int extractable;
    if (s == null) {
        extractable = -1;
    } else {
        if (!s.equalsIgnoreCase("true") && !s.equalsIgnoreCase("false")) {
            throw new IllegalArgumentException("Invalid extractable parameter: " + s);
        }
        extractable = Boolean.parseBoolean(s) ? 1 : 0;
    }

    String transportCertFilename = cmd.getOptionValue("transport");

    String profileID = cmd.getOptionValue("profile");
    if (profileID == null) {
        if (algorithm.equals("rsa")) {
            profileID = "caUserCert";
        } else if (algorithm.equals("ec")) {
            profileID = "caECUserCert";
        }
    }

    boolean withPop = !cmd.hasOption("without-pop");

    AuthorityID aid = null;
    if (cmd.hasOption("issuer-id")) {
        String aidString = cmd.getOptionValue("issuer-id");
        try {
            aid = new AuthorityID(aidString);
        } catch (IllegalArgumentException e) {
            throw new Exception("Invalid issuer ID: " + aidString, e);
        }
    }

    X500Name adn = null;
    if (cmd.hasOption("issuer-dn")) {
        String adnString = cmd.getOptionValue("issuer-dn");
        try {
            adn = new X500Name(adnString);
        } catch (IOException e) {
            throw new Exception("Invalid issuer DN: " + adnString, e);
        }
    }

    if (aid != null && adn != null) {
        throw new Exception("--issuer-id and --issuer-dn options are mutually exclusive");
    }

    MainCLI mainCLI = (MainCLI) parent.getParent();
    File certDatabase = mainCLI.certDatabase;

    String password = mainCLI.config.getNSSPassword();
    if (password == null) {
        throw new Exception("Missing security database password.");
    }

    String csr;
    PKIClient client;
    if ("pkcs10".equals(requestType)) {
        if ("rsa".equals(algorithm)) {
            csr = generatePkcs10Request(certDatabase, password, algorithm, Integer.toString(length), subjectDN);
        }

        else if ("ec".equals(algorithm)) {
            csr = generatePkcs10Request(certDatabase, password, algorithm, curve, subjectDN);
        } else {
            throw new Exception("Error: Unknown algorithm: " + algorithm);
        }

        // initialize database after PKCS10Client to avoid conflict
        mainCLI.init();
        client = getClient();

    } else if ("crmf".equals(requestType)) {

        // initialize database before CRMFPopClient to load transport certificate
        mainCLI.init();
        client = getClient();

        String encoded;
        if (transportCertFilename == null) {
            SystemCertClient certClient = new SystemCertClient(client, "ca");
            encoded = certClient.getTransportCert().getEncoded();

        } else {
            encoded = new String(Files.readAllBytes(Paths.get(transportCertFilename)));
        }

        byte[] transportCertData = Cert.parseCertificate(encoded);

        CryptoManager manager = CryptoManager.getInstance();
        X509Certificate transportCert = manager.importCACertPackage(transportCertData);

        // get archival and key wrap mechanisms from CA
        String kwAlg = CRMFPopClient.getKeyWrapAlgotihm(client);
        KeyWrapAlgorithm keyWrapAlgorithm = KeyWrapAlgorithm.fromString(kwAlg);

        csr = generateCrmfRequest(transportCert, subjectDN, attributeEncoding, algorithm, length, curve,
                sslECDH, temporary, sensitive, extractable, withPop, keyWrapAlgorithm);

    } else {
        throw new Exception("Unknown request type: " + requestType);
    }

    if (verbose) {
        System.out.println("CSR:");
        System.out.println(csr);
    }

    CAClient caClient = new CAClient(client);
    CACertClient certClient = new CACertClient(caClient);

    if (verbose) {
        System.out.println("Retrieving " + profileID + " profile.");
    }

    CertEnrollmentRequest request = certClient.getEnrollmentTemplate(profileID);

    // Key Generation / Dual Key Generation
    for (ProfileInput input : request.getInputs()) {

        ProfileAttribute typeAttr = input.getAttribute("cert_request_type");
        if (typeAttr != null) {
            typeAttr.setValue(requestType);
        }

        ProfileAttribute csrAttr = input.getAttribute("cert_request");
        if (csrAttr != null) {
            csrAttr.setValue(csr);
        }
    }

    // parse subject DN and put the values in a map
    DN dn = new DN(subjectDN);
    Vector<?> rdns = dn.getRDNs();

    Map<String, String> subjectAttributes = new HashMap<String, String>();
    for (int i = 0; i < rdns.size(); i++) {
        RDN rdn = (RDN) rdns.elementAt(i);
        String type = rdn.getTypes()[0].toLowerCase();
        String value = rdn.getValues()[0];
        subjectAttributes.put(type, value);
    }

    ProfileInput sn = request.getInput("Subject Name");
    if (sn != null) {
        if (verbose)
            System.out.println("Subject Name:");

        for (ProfileAttribute attribute : sn.getAttributes()) {
            String name = attribute.getName();
            String value = null;

            if (name.equals("subject")) {
                // get the whole subject DN
                value = subjectDN;

            } else if (name.startsWith("sn_")) {
                // get value from subject DN
                value = subjectAttributes.get(name.substring(3));

            } else {
                // unknown attribute, ignore
                if (verbose)
                    System.out.println(" - " + name);
                continue;
            }

            if (value == null)
                continue;

            if (verbose)
                System.out.println(" - " + name + ": " + value);
            attribute.setValue(value);
        }
    }

    if (certRequestUsername != null) {
        request.setAttribute("uid", certRequestUsername);
    }

    if (cmd.hasOption("password")) {
        Console console = System.console();
        String certRequestPassword = new String(console.readPassword("Password: "));
        request.setAttribute("pwd", certRequestPassword);
    }

    if (verbose) {
        System.out.println("Sending certificate request.");
    }

    CertRequestInfos infos = certClient.enrollRequest(request, aid, adn);

    MainCLI.printMessage("Submitted certificate request");
    CACertCLI.printCertRequestInfos(infos);
}

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

private static File dealWithGZIP(File gzip) throws IOException {
    int ndx = gzip.getName().lastIndexOf(".");
    File output = new File(gzip.getParentFile().getPath(), gzip.getName().substring(0, ndx));
    GZIPInputStream gzipInputStream = new GZIPInputStream(new FileInputStream(gzip));
    logger.info("Writing {} ...", FileUtils.getFilePath(output));
    long t0 = System.currentTimeMillis();

    int downloadedSize = writeFileFromInputStream(gzipInputStream, output, gzip.length(),
            System.console() != null);
    long t1 = System.currentTimeMillis();
    long downloadTime = t1 - t0;
    long downloadSecs = downloadTime / 1000;
    logger.info("Wrote {}K in {} millis", (downloadedSize / 1024), (downloadSecs < 1 ? "< 1" : downloadSecs));

    return output;
}