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.vmware.photon.controller.common.auth.AuthOIDCRegistrar.java

public static int main(String[] args) {
    Options options = new Options();
    options.addOption(USERNAME_ARG, true, "Lightwave user name");
    options.addOption(PASSWORD_ARG, true, "Password");
    options.addOption(TARGET_ARG, true, "Registration Hostname or IPAddress"); // Possible
                                                                               // load-balancer
                                                                               // address
    options.addOption(MANAGEMENT_UI_REG_FILE_ARG, true, "Management UI Registration Path");
    options.addOption(SWAGGER_UI_REG_FILE_ARG, true, "Swagger UI Registration Path");
    options.addOption(HELP_ARG, false, "Help");

    try {/*from   w ww .  j av a 2 s .  c om*/
        String username = null;
        String password = null;
        String registrationAddress = null;
        String mgmtUiRegPath = null;
        String swaggerUiRegPath = null;

        CommandLineParser parser = new DefaultParser();
        CommandLine cmd = null;
        cmd = parser.parse(options, args);

        if (cmd.hasOption(HELP_ARG)) {
            showUsage(options);
            return 0;
        }

        if (cmd.hasOption(USERNAME_ARG)) {
            username = cmd.getOptionValue(USERNAME_ARG);
        }

        if (cmd.hasOption(PASSWORD_ARG)) {
            password = cmd.getOptionValue(PASSWORD_ARG);
        }

        if (cmd.hasOption(TARGET_ARG)) {
            registrationAddress = cmd.getOptionValue(TARGET_ARG);
        }

        if (cmd.hasOption(MANAGEMENT_UI_REG_FILE_ARG)) {
            mgmtUiRegPath = cmd.getOptionValue(MANAGEMENT_UI_REG_FILE_ARG);
        }

        if (cmd.hasOption(SWAGGER_UI_REG_FILE_ARG)) {
            swaggerUiRegPath = cmd.getOptionValue(SWAGGER_UI_REG_FILE_ARG);
        }

        if (username == null || username.trim().isEmpty()) {
            throw new UsageException("Error: username is not specified");
        }

        if (password == null) {
            char[] passwd = System.console().readPassword("Password:");
            password = new String(passwd);
        }

        DomainInfo domainInfo = DomainInfo.build();

        AuthOIDCRegistrar registrar = new AuthOIDCRegistrar(domainInfo);

        registrar.register(registrationAddress, username, password, mgmtUiRegPath, swaggerUiRegPath);

        return 0;
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        return ERROR_PARSE_EXCEPTION;
    } catch (UsageException e) {
        System.err.println(e.getMessage());
        showUsage(options);
        return ERROR_USAGE_EXCEPTION;
    } catch (AuthException e) {
        System.err.println(e.getMessage());
        return ERROR_AUTH_EXCEPTION;
    }
}

From source file:org.miloss.nexuscloner.Main.java

public static void main(String[] args) throws Exception {

    final long now = System.currentTimeMillis();
    Options opts = new Options();
    opts.addOption("url", true, "root url of the repository you want to clone");

    opts.addOption("delay", true, "wait time between downloads (throttling)");
    opts.addOption("index", false, "build the index, must run first");
    opts.addOption("download", false, "download");
    opts.addOption("cookie", false, "prompt for cookie token");
    opts.addOption("username", true, "");
    opts.addOption("password", true, "prompt for password");
    opts.addOption("output", true, "output folder, default is ./output/");
    opts.addOption("threads", true, "threads for concurrent downloads");
    opts.addOption("help", false, "help");

    CommandLineParser parser = new DefaultParser();
    CommandLine parse = parser.parse(opts, args);

    initSsl();//from   w w w  . j  av a2 s.c om
    if (parse.hasOption("help") || !parse.hasOption("url")
            || (!parse.hasOption("index") && !parse.hasOption("download"))) {
        HelpFormatter f = new HelpFormatter();
        f.printHelp("java -jar nexusCloner-{VERSION}-jar-with-dependencies.jar {options}", opts);
        return;
    }

    String url = parse.getOptionValue("url");
    if (!url.endsWith("/")) {
        url = url + "/";
    }
    if (parse.hasOption("username") && parse.hasOption("password")) {
        System.out.println("Password: ");

        String password = new String(System.console().readPassword());
        auth = new String(Base64.encodeBase64((parse.getOptionValue("username") + ":" + password).getBytes()));
    }
    if (parse.hasOption("cookie")) {
        System.out.println("Cookie: ");

        String password = new String(System.console().readPassword());
        cookie = password;
        System.out.println("using cookie " + cookie);
    }
    sourceUrl = url;
    File outputFolder;
    if (parse.hasOption("output")) {
        outputFolder = new File(parse.getOptionValue("output"));
    } else
        outputFolder = new File("./output");
    outputFolder.mkdirs();
    Kryo kryo = new Kryo();
    if (parse.hasOption("index")) {
        process(url, outputFolder);
        //store the index
        Iterator<Container> iterator = filesToDownload.iterator();
        ArrayList<Container> data = new ArrayList<>();
        while (iterator.hasNext()) {
            data.add(iterator.next());
        }

        Wrapper d = new Wrapper();
        d.data = data;
        // ...
        Output output = new Output(new FileOutputStream("index.bin"));

        kryo.writeObject(output, d);
        output.close();

    }
    if (parse.hasOption("download")) {
        if (filesToDownload.isEmpty()) {

            Input input = new Input(new FileInputStream("index.bin"));
            Wrapper someObject = kryo.readObject(input, Wrapper.class);
            input.close();
            filesToDownload.addAll(someObject.data);
        }
        System.out.println(filesToDownload.size() + " files to download");
        System.out.println(filesToDownload.size() + " files to download");
        System.out.println(filesToDownload.size() + " files to download");
        int threads = 4;
        if (parse.hasOption("threads")) {
            threads = Integer.parseInt(parse.getOptionValue("threads"));
        }
        for (int i = 0; i < threads; i++) {
            DownloadWorker dw = new DownloadWorker();
            new Thread(dw).start();
        }

        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("processed in " + (System.currentTimeMillis() - now) + "ms");
                System.out.println("Download failures: " + failures.size());
                for (int i = 0; i < failures.size(); i++) {
                    System.out.println(failures.get(i).url + ": " + failures.get(i).ex.getMessage());
                }
            }
        }));
        System.out.println("PRESS ENTER TO STOP THE DOWNLOADS AFTER THE CURRENT FILES END");
        System.console().readLine();
        running = false;
    }

    System.out.println("processed in " + (System.currentTimeMillis() - now) + "ms");
}

From source file:ch.epfl.leb.sass.commandline.CommandLineInterface.java

/**
 * Shows help, launches the interpreter and executes scripts according to input args.
 * @param args input arguments//from  w ww  .  j a va  2s. c  o  m
 */
public static void main(String args[]) {
    // parse input arguments
    CommandLineParser parser = new DefaultParser();
    CommandLine line = null;
    try {
        line = parser.parse(options, args);
    } catch (ParseException ex) {
        System.err.println("Parsing of arguments failed. Reason: " + ex.getMessage());
        System.err.println("Use -help for usage.");
        System.exit(1);
    }

    // decide how do we make the interpreter available based on options
    Interpreter interpreter = null;
    // show help and exit
    if (line.hasOption("help")) {
        HelpFormatter helpFormatter = new HelpFormatter();
        helpFormatter.printHelp("java -jar <jar-name>", options, true);
        System.exit(0);
        // launch interpreter inside current terminal
    } else if (line.hasOption("interpreter")) {
        // assign in, out and err streams to the interpreter
        interpreter = new Interpreter(new InputStreamReader(System.in), System.out, System.err, true);
        interpreter.setShowResults(true);
        // if a script was given, execute it before giving access to user
        if (line.hasOption("script")) {
            try {
                interpreter.source(line.getOptionValue("script"));
            } catch (IOException ex) {
                Logger.getLogger(BeanShellConsole.class.getName()).log(Level.SEVERE,
                        "IOException while executing shell script.", ex);
            } catch (EvalError ex) {
                Logger.getLogger(BeanShellConsole.class.getName()).log(Level.SEVERE,
                        "EvalError while executing shell script.", ex);
            }
        }
        // give access to user
        new Thread(interpreter).start();
        // only execute script and exit
    } else if (line.hasOption("script")) {
        interpreter = new Interpreter();
        try {
            interpreter.source(line.getOptionValue("script"));
            System.exit(0);
        } catch (IOException ex) {
            Logger.getLogger(BeanShellConsole.class.getName()).log(Level.SEVERE,
                    "IOException while executing shell script.", ex);
            System.exit(1);
        } catch (EvalError ex) {
            Logger.getLogger(BeanShellConsole.class.getName()).log(Level.SEVERE,
                    "EvalError while executing shell script.", ex);
            System.exit(1);
        }

        // Launches the RPC server with the model contained in the file whose
        // filename was passed by argument.
    } else if (line.hasOption("rpc_server")) {

        IJPluginModel model = new IJPluginModel();
        File file = new File(line.getOptionValue("rpc_server"));
        try {
            FileInputStream stream = new FileInputStream(file);
            model = IJPluginModel.read(stream);
        } catch (FileNotFoundException ex) {
            System.out.println("Error: " + file.getName() + " not found.");
            System.exit(1);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        // Check whether a port number was specified.
        if (line.hasOption("port")) {
            try {
                port = Integer.valueOf(line.getOptionValue("port"));
                System.out.println("Using port: " + String.valueOf(port));
            } catch (java.lang.NumberFormatException ex) {
                System.out.println("Error: the port number argument is not a number.");
                System.exit(1);
            }
        } else {
            System.out.println("No port number provided. Using default port: " + String.valueOf(port));
        }

        RPCServer server = new RPCServer(model, port);

        System.out.println("Starting RPC server...");
        server.serve();

    } else if (line.hasOption("port") & !line.hasOption("rpc_server")) {
        System.out.println("Error: Port number provided without requesting the RPC server. Exiting...");
        System.exit(1);

        // if System.console() returns null, it means we were launched by
        // double-clicking the .jar, so launch own BeanShellConsole
        // if System.console() returns null, it means we were launched by
        // double-clicking the .jar, so launch own ConsoleFrame
    } else if (System.console() == null) {
        BeanShellConsole cframe = new BeanShellConsole("SASS BeanShell Prompt");
        interpreter = cframe.getInterpreter();
        cframe.setVisible(true);
        System.setOut(cframe.getInterpreter().getOut());
        System.setErr(cframe.getInterpreter().getErr());
        new Thread(cframe.getInterpreter()).start();
        // otherwise, show help
    } else {
        HelpFormatter helpFormatter = new HelpFormatter();
        helpFormatter.printHelp("java -jar <jar-name>", options, true);
        System.exit(0);
    }

    if (interpreter != null) {
        printWelcomeText(interpreter.getOut());
    }
}

From source file:com.trsst.Command.java

public static void main(String[] argv) {

    // during alpha period: expire after one week
    Date builtOn = Common.getBuildDate();
    if (builtOn != null) {
        long weekMillis = 1000 * 60 * 60 * 24 * 7;
        Date expiry = new Date(builtOn.getTime() + weekMillis);
        if (new Date().after(expiry)) {
            System.err.println("Build expired on: " + expiry);
            System.err.println("Please obtain a more recent build for testing.");
            System.exit(1);//from  w  w w. ja  v a2  s .c  o m
        } else {
            System.err.println("Build will expire on: " + expiry);
        }
    }

    // experimental tor support
    boolean wantsTor = false;
    for (String s : argv) {
        if ("--tor".equals(s)) {
            wantsTor = true;
            break;
        }
    }
    if (wantsTor && !HAS_TOR) {
        try {
            log.info("Attempting to connect to tor network...");
            Security.addProvider(new BouncyCastleProvider());
            JvmGlobalUtil.init();
            NetLayer netLayer = NetFactory.getInstance().getNetLayerById(NetLayerIDs.TOR);
            JvmGlobalUtil.setNetLayerAndNetAddressNameService(netLayer, true);
            log.info("Connected to tor network");
            HAS_TOR = true;
        } catch (Throwable t) {
            log.error("Could not connect to tor: exiting", t);
            System.exit(1);
        }
    }

    // if unspecified, default relay to home.trsst.com
    if (System.getProperty("com.trsst.server.relays") == null) {
        System.setProperty("com.trsst.server.relays", "https://home.trsst.com/feed");
    }

    // default to user-friendlier file names
    String home = System.getProperty("user.home", ".");
    if (System.getProperty("com.trsst.client.storage") == null) {
        File client = new File(home, "Trsst Accounts");
        System.setProperty("com.trsst.client.storage", client.getAbsolutePath());
    }
    if (System.getProperty("com.trsst.server.storage") == null) {
        File server = new File(home, "Trsst System Cache");
        System.setProperty("com.trsst.server.storage", server.getAbsolutePath());
    }
    // TODO: try to detect if launching from external volume like a flash
    // drive and store on the local flash drive instead

    Console console = System.console();
    int result;
    try {
        if (console == null && argv.length == 0) {
            argv = new String[] { "serve", "--gui" };
        }
        result = new Command().doBegin(argv, System.out, System.in);

        // task queue prevents exit unless stopped
        if (TrsstAdapter.TASK_QUEUE != null) {
            TrsstAdapter.TASK_QUEUE.cancel();
        }
    } catch (Throwable t) {
        result = 1; // "general catchall error code"
        log.error("Unexpected error, exiting.", t);
    }

    // if error
    if (result != 0) {
        // force exit
        System.exit(result);
    }
}

From source file:Main.java

private static PKCS8EncodedKeySpec decryptPrivateKey(byte[] encryptedPrivateKey)
        throws GeneralSecurityException {
    EncryptedPrivateKeyInfo epkInfo;
    try {//from w ww . j a  v  a2  s  .  c om
        epkInfo = new EncryptedPrivateKeyInfo(encryptedPrivateKey);
    } catch (IOException ex) {
        // Probably not an encrypted key.
        return null;
    }

    char[] password = System.console().readPassword("Password for the private key file: ");

    SecretKeyFactory skFactory = SecretKeyFactory.getInstance(epkInfo.getAlgName());
    Key key = skFactory.generateSecret(new PBEKeySpec(password));
    Arrays.fill(password, '\0');

    Cipher cipher = Cipher.getInstance(epkInfo.getAlgName());
    cipher.init(Cipher.DECRYPT_MODE, key, epkInfo.getAlgParameters());

    try {
        return epkInfo.getKeySpec(cipher);
    } catch (InvalidKeySpecException ex) {
        System.err.println("Password may be bad.");
        throw ex;
    }
}

From source file:DateServer.java

private void runServer() {
    Console console = System.console();
    Handler h = new Handler(ss);
    h.start();/*from www .  j  av a2s .  c  o  m*/

    while (true) {
        String cmd = console.readLine(">");
        if (cmd == null)
            continue;
        if (cmd.equals("exit"))
            System.exit(0);
    }
}

From source file:org.jboss.as.quickstarts.datagrid.hotrod.FootballManager.java

public static void main(String[] args) {
    Console con = System.console();
    FootballManager manager = new FootballManager(con);
    con.printf(initialPrompt);/*from www  .  ja  va  2 s.  c o m*/

    while (true) {
        String action = con.readLine(">");
        if ("at".equals(action)) {
            manager.addTeam();
        } else if ("ap".equals(action)) {
            manager.addPlayers();
        } else if ("rt".equals(action)) {
            manager.removeTeam();
        } else if ("rp".equals(action)) {
            manager.removePlayer();
        } else if ("p".equals(action)) {
            manager.printTeams();
        } else if ("ar".equals(action)) {
            manager.addResidential(true);
        } else if ("arm".equals(action)) {
            manager.addResidential(false);
        } else if ("pR".equals(action)) {
            manager.printResidentials();
        } else if ("pr".equals(action)) {
            manager.printResidential();
        } else if ("rr".equals(action)) {
            con.printf("status:" + manager.removeResidential());
        } else if ("rR".equals(action)) {
            con.printf("status:" + manager.removeResidentials());
        } else if ("nani".equals(action)) {
            manager.insert7nani();
        } else if ("mr".equals(action)) {
            manager.massiveResidentialInsert(true);
        } else if ("mrm".equals(action)) {
            manager.massiveResidentialInsert(false);
        } else if ("help".equals(action)) {
            con.printf(initialPrompt);
        } else if ("k".equals(action)) {
            manager.printKeySet();
        } else if ("q".equals(action)) {
            manager.stop();
            break;
        }
    }
}

From source file:com.aerospike.delivery.db.aerospike.Parameters.java

static Parameters parseServerParameters(CommandLine cl) {
    String host = cl.getOptionValue("h", "127.0.0.1");
    String portString = cl.getOptionValue("p", "3000");
    String user = cl.getOptionValue("U");
    String password = cl.getOptionValue("P");
    String namespace = cl.getOptionValue("n", "demo1");

    int port = Integer.parseInt(portString);

    if (user != null && password == null) {
        java.io.Console console = System.console();

        if (console != null) {
            char[] pass = console.readPassword("Enter password:");

            if (pass != null) {
                password = new String(pass);
            }/*from   w  w w  .j  a  v  a2s.  co  m*/
        }
    }
    try {
        return new Parameters(host, port, user, password, namespace);
    } catch (Exception e) {
        return null;
    }
}

From source file:org.unitedid.yhsm.YubiHSMCmdLine.java

/**
 * Prompts for HSM key storage password on the command line.
 *///  w  ww. j a  v a2s .  c om
public static void runUnlock() {
    try {
        hsm = new YubiHSM(deviceName, 1);

        Console in = System.console();
        if (in == null) {
            System.out.println("Failed to open system console.");
            System.exit(1);
        }

        String otp = null;
        String password = new String(in.readPassword("Please enter HSM password: "));
        if (hsm.getInfo().getMajorVersion() > 0 && useOtp) {
            otp = ModHex.decode(new String(in.readPassword("Please enter admin YubiKey OTP: ")));
        }

        if (unlock(password, otp)) {
            System.out.println("YubiHSM " + deviceName + " was successfully unlocked.");
        } else {
            System.out.println("Unlock failed, bad password.");
        }

    } catch (YubiHSMCommandFailedException e) {
        System.out.println("Unlock command failed with the reason: " + e.getMessage());
    } catch (YubiHSMInputException e) {
        System.out.println("Invalid input. Password has to be in hex format.");
        if (debug) {
            System.out.println(e);
        }
    } catch (NumberFormatException e) {
        System.out.println("Invalid input. Password has to be in hex format.");
    } catch (YubiHSMErrorException e) {
        System.out.println("An error has occurred: " + e.getMessage());
    }
}

From source file:com.geeksaga.light.console.Main.java

private void doConsole() throws Exception {
    Console console = System.console();

    String command = console.readLine("> ");

    System.out.println(command);/*w w w .ja  v  a  2s .c om*/
}