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:keepassj.cli.KeepassjCli.java

/**
 * @param args the command line arguments
 * @throws org.apache.commons.cli.ParseException
 * @throws java.io.IOException//  w w w .ja  va  2s. c  o m
 */
public static void main(String[] args) throws ParseException, IOException {
    Options options = KeepassjCli.getOptions();
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args);
    if (!KeepassjCli.validateOptions(cmd)) {
        HelpFormatter help = new HelpFormatter();
        help.printHelp("Usage: java -jar KeepassjCli -f dbfile [options]", options);
    } else {
        String password;
        if (cmd.hasOption('p')) {
            password = cmd.getOptionValue('p');
        } else {
            Console console = System.console();
            char[] hiddenString = console.readPassword("Enter password for %s\n", cmd.getOptionValue('f'));
            password = String.valueOf(hiddenString);
        }
        KeepassjCli instance = new KeepassjCli(cmd.getOptionValue('f'), password, cmd.getOptionValue('k'));
        System.out.println("Description:" + instance.db.getDescription());
        PwGroup rootGroup = instance.db.getRootGroup();
        System.out.println(String.valueOf(rootGroup.GetEntriesCount(true)) + " entries");
        if (cmd.hasOption('l')) {
            instance.printEntries(rootGroup.GetEntries(true), false);
        } else if (cmd.hasOption('s')) {
            PwObjectList<PwEntry> results = instance.search(cmd.getOptionValue('s'));
            System.out.println("Found " + results.getUCount() + " results for:" + cmd.getOptionValue('s'));
            instance.printEntries(results, false);
        } else if (cmd.hasOption('i')) {
            System.out.println("Entering interactive mode.");
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            String input = null;
            PwObjectList<PwEntry> results = null;
            while (!"\\q".equals(input)) {
                if (results != null) {
                    System.out.println("Would you like to view a specific entry? y/n");
                    input = bufferedReader.readLine();
                    if ("y".equalsIgnoreCase(input)) {
                        System.out.print("Enter the title number:");
                        input = bufferedReader.readLine();
                        instance.printCompleteEntry(results.GetAt(Integer.parseInt(input) - 1)); // Since humans start counting at 1
                    }
                    results = null;
                    System.out.println();
                } else {
                    System.out.print("Enter something to search for (or \\q to quit):");
                    input = bufferedReader.readLine();
                    if (!"\\q".equalsIgnoreCase(input)) {
                        results = instance.search(input);
                        instance.printEntries(results, true);
                    }
                }
            }
        }

        // Close before exit
        instance.db.Close();
    }
}

From source file:craterdog.security.DigitalNotaryMain.java

public static void main(String[] args) throws ParseException, IOException {
    HelpFormatter help = new HelpFormatter();
    Options options = new Options();
    options.addOption("help", false, "print this message");
    options.addOption("pubfile", true, "public key input file");
    options.addOption("prvfile", true, "private key input file");

    try {//from   w ww.  ja  v a 2s.  c  o m
        CommandLine cli = new BasicParser().parse(options, args);
        String pubfile = cli.getOptionValue("pubfile");
        String prvfile = cli.getOptionValue("prvfile");

        NotaryKey notaryKey = notarization.generateNotaryKey();

        if (pubfile != null || prvfile != null) {
            if (pubfile == null)
                throw new MissingArgumentException("Missing option: pubfile");
            if (prvfile == null)
                throw new MissingArgumentException("Missing option: prvfile");

            CertificateManager manager = new RsaCertificateManager();
            PublicKey publicKey = manager.decodePublicKey(FileUtils.readFileToString(new File(pubfile)));
            char[] password = System.console().readPassword("input private key password: ");
            PrivateKey privateKey = manager.decodePrivateKey(FileUtils.readFileToString(new File(prvfile)),
                    password);

            notaryKey.signingKey = privateKey;
            notaryKey.verificationKey = publicKey;

            // make sure it works
            DigitalSeal seal = notarization.notarizeDocument("test document", "test document", notaryKey);
            notarization.documentIsValid("test document", seal, publicKey);
        }
        char[] password = System.console().readPassword("verficationKey password: ");
        System.out.println(notarization.serializeNotaryKey(notaryKey, password));
    } catch (MissingArgumentException | FileNotFoundException ex) {
        System.out.println(ex.getMessage());
        help.printHelp(CMD_LINE_SYNTAX, options);
        System.exit(1);
    }
}

From source file:com.msopentech.ThaliClient.ProxyDesktop.java

public static void main(String[] rgs) throws InterruptedException, URISyntaxException, IOException {

    final ProxyDesktop instance = new ProxyDesktop();
    try {/*www . j  a  v  a  2s  .  c  o m*/
        instance.initialize();
    } catch (RuntimeException e) {
        System.out.println(e);
    }

    // Attempt to launch the default browser to our page
    if (Desktop.isDesktopSupported()) {
        Desktop.getDesktop().browse(new URI("http://localhost:" + localWebserverPort));
    }

    // Register to shutdown the server properly from a sigterm
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            instance.shutdown();
        }
    });

    // Let user press enter to kill the console session
    Console console = System.console();
    if (console != null) {
        console.format("\nPress ENTER to exit.\n");
        console.readLine();
        instance.shutdown();
    } else {
        // Don't exit on your own when running without a console (debugging in an IDE).
        while (true) {
            Thread.sleep(500);
        }
    }
}

From source file:com.mijecu25.sqlplus.SQLPlus.java

public static void main(String[] args) throws IOException {
    // Create and load the properties from the application properties file
    Properties properties = new Properties();
    properties.load(SQLPlus.class.getClassLoader().getResourceAsStream(SQLPlus.APPLICATION_PROPERTIES_FILE));

    SQLPlus.logger.info("Initializing " + SQLPlus.PROGRAM_NAME + " version "
            + properties.getProperty(SQLPlus.APPLICATION_PROPERTIES_FILE_VERSION));

    // Check if the user is using a valid console (i.e. not from Eclipse)
    if (System.console() == null) {
        // The Console object for the JVM could not be found. Alert the user 
        SQLPlus.logger.fatal(Messages.FATAL + "A JVM Console object was not found. Try running "
                + SQLPlus.PROGRAM_NAME + "from the command line");
        System.out.println(/*from   www  . j ava 2s . c om*/
                Messages.FATAL + SQLPlus.PROGRAM_NAME + " was not able to find your JVM's Console object. "
                        + "Try running " + SQLPlus.PROGRAM_NAME + " from the command line.");

        SQLPlus.exitSQLPlus();

        SQLPlus.logger.fatal(Messages.FATAL + Messages.QUIT_PROGRAM_ERROR(PROGRAM_NAME));
        return;
    }

    // UI intro
    System.out.println("Welcome to " + SQLPlus.PROGRAM_NAME
            + "! This program has a DSL to add alerts to various SQL DML events.");
    System.out.println("Be sure to use " + SQLPlus.PROGRAM_NAME + " from the command line.");
    System.out.println();

    // Get the version
    System.out.println("Version: " + properties.getProperty(SQLPlus.APPLICATION_PROPERTIES_FILE_VERSION));
    System.out.println();

    // Read the license file
    BufferedReader bufferedReader;
    bufferedReader = new BufferedReader(new FileReader(SQLPlus.LICENSE_FILE));

    // Read a line
    String line = bufferedReader.readLine();

    // While the line is not null
    while (line != null) {
        System.out.println(line);

        // Read a new lines
        line = bufferedReader.readLine();
    }

    // Close the buffer
    bufferedReader.close();
    System.out.println();

    // Create the jline console that allows us to remember commands, use arrow keys, and catch interruptions
    // from the user
    SQLPlus.console = new ConsoleReader();
    SQLPlus.console.setHandleUserInterrupt(true);

    try {
        // Get credentials from the user
        SQLPlus.logger.info("Create SQLPlusConnection");
        SQLPlus.createSQLPlusConnection();
    } catch (NullPointerException | SQLException | IllegalArgumentException e) {
        // NPE: This exception can occur if the user is running the program where the JVM Console
        // object cannot be found.
        // SQLE: TODO should I add here the error code?
        // This exception can occur when trying to establish a connection
        // IAE: This exception can occur when trying to establish a connection
        SQLPlus.logger
                .fatal(Messages.FATAL + Messages.FATAL_EXIT(SQLPlus.PROGRAM_NAME, e.getClass().getName()));
        System.out.println(Messages.FATAL + Messages.FATAL_EXCEPTION_ACTION(e.getClass().getSimpleName()) + " "
                + Messages.CHECK_LOG_FILES);
        SQLPlus.exitSQLPlus();

        SQLPlus.logger.fatal(Messages.FATAL + Messages.QUIT_PROGRAM_ERROR(SQLPlus.PROGRAM_NAME));
        return;
    } catch (UserInterruptException uie) {
        SQLPlus.logger.warn(Messages.WARNING + "The user typed an interrupt instruction.");
        SQLPlus.exitSQLPlus();

        return;
    }

    System.out.println("Connection established! Commands end with " + SQLPlus.END_OF_COMMAND);
    System.out.println("Type " + SQLPlus.EXIT + " or " + SQLPlus.QUIT + " to exit the application ");

    try {
        // Execute the input scanner
        while (true) {
            // Get a line from the user until the hit enter (carriage return, line feed/ new line).
            System.out.print(SQLPlus.PROMPT);
            try {
                line = SQLPlus.console.readLine().trim();
            } catch (NullPointerException npe) {
                // TODO test this behavior
                // If this exception is catch, it is very likely that the user entered the end of line command.
                // This means that the program should quit.
                SQLPlus.logger.warn(Messages.WARNING + "The input from the user is null. It is very likely that"
                        + "the user entered the end of line command and they want to quit.");
                SQLPlus.exitSQLPlus();

                return;
            }

            // If the user did not enter anything
            if (line.isEmpty()) {
                // Continue to the next iteration
                continue;
            }

            if (line.equals(".")) {
                line = "use courses;";
            }

            if (line.equals("-")) {
                line = "select created_at from classes;";
            }

            if (line.equals("--")) {
                line = "select name, year from classes;";
            }

            if (line.equals("*")) {
                line = "select * from classes;";
            }

            if (line.equals("x")) {
                line = "select name from classes, classes;";
            }

            if (line.equals("e")) {
                line = "select * feom classes;";
            }

            // Logic to quit
            if (line.equals(SQLPlus.QUIT) || line.equals(SQLPlus.EXIT)) {
                SQLPlus.logger.info("The user wants to quit " + SQLPlus.PROGRAM_NAME);
                SQLPlus.exitSQLPlus();
                break;
            }

            // Use a StringBuilder since jline works weird when it has read a line. The issue we were having was with the
            // end of command logic. jline does not keep the input from the user in the variable that was stored in. Each
            // time jline reads a new line, the variable is empty
            StringBuilder query = new StringBuilder();
            query.append(line);

            // While the user does not finish the command with the SQLPlus.END_OF_COMMAND
            while (query.charAt(query.length() - 1) != SQLPlus.END_OF_COMMAND) {
                // Print the wait for command prompt and get the next line for the user
                System.out.print(SQLPlus.WAIT_FOR_END_OF_COMMAND);
                query.append(" ");
                line = StringUtils.stripEnd(SQLPlus.console.readLine(), null);
                query.append(line);
            }

            SQLPlus.logger.info("Raw input from the user: " + query);

            try {
                Statement statement;

                try {
                    // Execute the antlr code to parse the user input
                    SQLPlus.logger.info("Will parse the user input to determine what to execute");
                    ANTLRStringStream input = new ANTLRStringStream(query.toString());
                    SQLPlusLex lexer = new SQLPlusLex(input);
                    CommonTokenStream tokens = new CommonTokenStream(lexer);
                    SQLPlusParser parser = new SQLPlusParser(tokens);

                    statement = parser.sqlplus();
                } catch (RecognitionException re) {
                    // TODO move this to somehwere else
                    //                        String message = Messages.WARNING + "You have an error in your SQL syntax. Check the manual"
                    //                                + " that corresponds to your " + SQLPlus.sqlPlusConnection.getCurrentDatabase()
                    //                                + " server or " + SQLPlus.PROGRAM_NAME + " for the correct syntax";
                    //                        SQLPlus.logger.warn(message);
                    //                        System.out.println(message);
                    statement = new StatementDefault();
                }

                statement.setStatement(query.toString());
                SQLPlus.sqlPlusConnection.execute(statement);
            } catch (UnsupportedOperationException uoe) {
                // This exception can occur when the user entered a command allowed by the parsers, but not currently
                // supported by SQLPlus. This can occur because the parser is written in such a way that supports
                // the addition of features.
                SQLPlus.logger.warn(Messages.WARNING + uoe);
                System.out.println(
                        Messages.WARNING + Messages.FATAL_EXCEPTION_ACTION(uoe.getClass().getSimpleName()) + " "
                                + Messages.CHECK_LOG_FILES);
                SQLPlus.logger.warn(Messages.WARNING + "The previous command is not currently supported.");
            }

        }
    } catch (IllegalArgumentException iae) {
        // This exception can occur when a command is executed but it had illegal arguments. Most likely
        // it is a programmer's error and should be addressed by the developer.
        SQLPlus.logger
                .fatal(Messages.FATAL + Messages.FATAL_EXIT(SQLPlus.PROGRAM_NAME, iae.getClass().getName()));
        SQLPlus.exitSQLPlus();

        SQLPlus.logger.fatal(Messages.FATAL + Messages.QUIT_PROGRAM_ERROR(SQLPlus.PROGRAM_NAME));
    } catch (UserInterruptException uie) {
        SQLPlus.logger.warn(Messages.WARNING + "The user typed an interrupt instruction.");
        SQLPlus.exitSQLPlus();
    }
}

From source file:edu.internet2.middleware.changelogconsumer.googleapps.GoogleAppsFullSync.java

public static void main(String[] args) {
    if (args.length == 0) {
        System.console().printf("Google Change Log Consumer Name must be provided\n");
        System.console().printf("*nix: googleAppsFullSync.sh consumerName [--dry-run]\n");
        System.console().printf("Windows: googleAppsFullSync.bat consumerName [--dry-run]\n");

        System.exit(-1);//from   w  ww.ja  v  a  2s  .c  om
    }

    try {
        GoogleAppsFullSync googleAppsFullSync = new GoogleAppsFullSync(args[0]);
        googleAppsFullSync.process(args.length > 1 && args[1].equalsIgnoreCase("--dry-run"));

    } catch (Exception e) {
        System.console().printf(e.toString() + ": \n");
        e.printStackTrace();
    }

    System.exit(0);
}

From source file:org.ow2.proactive.authentication.crypto.CreateCredentials.java

/**
 * Entry point//from  ww w . ja  va 2 s .co  m
 * 
 * @see org.ow2.proactive.authentication.crypto.Credentials
 * @param args arguments, try '-h' for help
 * @throws IOException
 * @throws ParseException
 *
 */
public static void main(String[] args) throws IOException, ParseException {

    SecurityManagerConfigurator.configureSecurityManager(
            CreateCredentials.class.getResource("/all-permissions.security.policy").toString());

    Console console = System.console();
    /**
     * default values
     */
    boolean interactive = true;
    String pubKeyPath = null;
    PublicKey pubKey = null;
    String login = null;
    String pass = null;
    String keyfile = null;
    String cipher = "RSA/ECB/PKCS1Padding";
    String path = Credentials.getCredentialsPath();
    String rm = null;
    String scheduler = null;
    String url = null;

    Options options = new Options();

    Option opt = new Option("h", "help", false, "Display this help");
    opt.setRequired(false);
    options.addOption(opt);

    OptionGroup group = new OptionGroup();
    group.setRequired(false);
    opt = new Option("F", "file", true,
            "Public key path on the local filesystem [default:" + Credentials.getPubKeyPath() + "]");
    opt.setArgName("PATH");
    opt.setArgs(1);
    opt.setRequired(false);
    group.addOption(opt);

    opt = new Option("R", "rm", true, "Request the public key to the Resource Manager at URL");
    opt.setArgName("URL");
    opt.setArgs(1);
    opt.setRequired(false);
    group.addOption(opt);

    opt = new Option("S", "scheduler", true, "Request the public key to the Scheduler at URL");
    opt.setArgName("URL");
    opt.setArgs(1);
    opt.setRequired(false);
    group.addOption(opt);
    options.addOptionGroup(group);

    opt = new Option("l", "login", true,
            "Generate credentials for this specific user, will be asked interactively if not specified");
    opt.setArgName("LOGIN");
    opt.setArgs(1);
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("p", "password", true, "Use this password, will be asked interactively if not specified");
    opt.setArgName("PWD");
    opt.setArgs(1);
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("k", "keyfile", true,
            "Use specified ssh private key, asked interactively if specified without PATH, not specified otherwise.");
    opt.setArgName("PATH");
    opt.setOptionalArg(true);
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("o", "output", true,
            "Output the resulting credentials to the specified file [default:" + path + "]");
    opt.setArgName("PATH");
    opt.setArgs(1);
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("c", "cipher", true,
            "Use specified cipher parameters, need to be compatible with the specified key [default:" + cipher
                    + "]");
    opt.setArgName("PARAMS");
    opt.setArgs(1);
    opt.setRequired(false);
    options.addOption(opt);

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(newline + "ERROR : " + e.getMessage() + newline);
        System.out.println("type -h or --help to display help screen");
        System.exit(1);
    }

    if (cmd.hasOption("help")) {
        displayHelp(options);
    }

    if (cmd.hasOption("file")) {
        pubKeyPath = cmd.getOptionValue("file");
    }
    if (cmd.hasOption("rm")) {
        rm = cmd.getOptionValue("rm");
    }
    if (cmd.hasOption("scheduler")) {
        scheduler = cmd.getOptionValue("scheduler");
    }

    if (cmd.hasOption("login")) {
        login = cmd.getOptionValue("login");
    }
    if (cmd.hasOption("password")) {
        pass = cmd.getOptionValue("password");
    }
    if (cmd.hasOption("keyfile") && cmd.getOptionValues("keyfile") != null) {
        keyfile = cmd.getOptionValue("keyfile");
    }

    if (cmd.hasOption("output")) {
        path = cmd.getOptionValue("output");
    }
    if (cmd.hasOption("cipher")) {
        cipher = cmd.getOptionValue("cipher");
    }

    int acc = 0;
    if (pubKeyPath != null) {
        acc++;
    }
    if (scheduler != null) {
        url = Connection.normalize(scheduler) + "SCHEDULER";
        acc++;

    }
    if (rm != null) {
        url = Connection.normalize(rm) + "RMAUTHENTICATION";
        acc++;
    }
    if (acc > 1) {
        System.out.println("--rm, --scheduler and --file arguments cannot be combined.");
        System.out.println("try -h for help.");
        System.exit(1);
    }

    if (url != null) {
        try {
            Connection<AuthenticationImpl> conn = new Connection<AuthenticationImpl>(AuthenticationImpl.class) {
                public Logger getLogger() {
                    return Logger.getLogger("pa.scheduler.credentials");
                }
            };
            AuthenticationImpl auth = conn.connect(url);
            pubKey = auth.getPublicKey();
        } catch (Exception e) {
            System.err.println("ERROR : Could not retrieve public key from '" + url + "'");
            e.printStackTrace();
            System.exit(3);
        }
        System.out.println("Successfully obtained public key from " + url + newline);
    } else if (pubKeyPath != null) {
        try {
            pubKey = Credentials.getPublicKey(pubKeyPath);
        } catch (KeyException e) {
            System.err
                    .println("ERROR : Could not retrieve public key from '" + pubKeyPath + "' (no such file)");
            System.exit(4);
        }
    } else {
        System.out.println("No public key specified, attempting to retrieve it from default location.");
        pubKeyPath = Credentials.getPubKeyPath();
        try {
            pubKey = Credentials.getPublicKey(pubKeyPath);
        } catch (KeyException e) {
            System.err
                    .println("ERROR : Could not retrieve public key from '" + pubKeyPath + "' (no such file)");
            System.exit(5);
        }
    }

    if (login != null && pass != null
            && (!cmd.hasOption("keyfile") || cmd.getOptionValues("keyfile") != null)) {
        System.out.println("Running in non-interactive mode." + newline);
        interactive = false;
    } else {
        System.out.println("Running in interactive mode.");
    }

    if (interactive) {
        System.out.println("Please enter Scheduler credentials,");
        System.out.println("they will be stored encrypted on disk for future logins." + newline);
        System.out.print("login: ");
        if (login == null) {
            login = console.readLine();
        } else {
            System.out.println(login);
        }
        System.out.print("password: ");
        if (pass == null) {
            pass = new String(console.readPassword());
        } else {
            System.out.println("*******");
        }
        System.out.print("keyfile: ");
        if (!cmd.hasOption("keyfile")) {
            System.out.println("no key file specified");
        } else if (cmd.hasOption("keyfile") && cmd.getOptionValues("keyfile") != null) {
            System.out.println(keyfile);
        } else {
            keyfile = console.readLine();
        }
    }

    try {
        CredData credData;
        if (keyfile != null && keyfile.length() > 0) {
            byte[] keyfileContent = FileToBytesConverter.convertFileToByteArray(new File(keyfile));
            credData = new CredData(CredData.parseLogin(login), CredData.parseDomain(login), pass,
                    keyfileContent);
        } else {
            System.out.println("--> Ignoring keyfile, credential does not contain SSH key");
            credData = new CredData(CredData.parseLogin(login), CredData.parseDomain(login), pass);
        }
        Credentials cred = Credentials.createCredentials(credData, pubKey, cipher);
        cred.writeToDisk(path);
    } catch (FileNotFoundException e) {
        System.err.println("ERROR : Could not retrieve ssh private key from '" + keyfile + "' (no such file)");
        System.exit(6);
    } catch (Throwable t) {
        t.printStackTrace();
        System.exit(7);
    }

    System.out.println("Successfully stored encrypted credentials on disk at :");
    System.out.println("\t" + path);

    System.exit(0);
}

From source file:de.petendi.ethereum.secure.proxy.Application.java

public static void main(String[] args) {

    try {/*from  w  w  w  .j  a  v a2s.  c o  m*/
        cmdLineResult = new CmdLineResult();
        cmdLineResult.parseArguments(args);
    } catch (CmdLineException e) {
        System.out.println(e.getMessage());
        System.out.println("Usage:");
        cmdLineResult.printExample();
        System.exit(-1);
        return;
    }

    File workingDirectory = new File(System.getProperty("user.home"));
    if (cmdLineResult.getWorkingDirectory().length() > 0) {
        workingDirectory = new File(cmdLineResult.getWorkingDirectory()).getAbsoluteFile();
    }

    ArgumentList argumentList = new ArgumentList();
    argumentList.setWorkingDirectory(workingDirectory);
    File certificate = new File(workingDirectory, "seccoco-secured/cert.p12");
    if (certificate.exists()) {
        char[] passwd = null;
        if (cmdLineResult.getPassword() != null) {
            System.out.println("Using password from commandline argument - DON'T DO THIS IN PRODUCTION !!");
            passwd = cmdLineResult.getPassword().toCharArray();
        } else {
            Console console = System.console();
            if (console != null) {
                passwd = console.readPassword("[%s]", "Enter application password:");
            } else {
                System.out.print("No suitable console found for entering password");
                System.exit(-1);
            }
        }
        argumentList.setTokenPassword(passwd);
    }
    try {
        SeccocoFactory seccocoFactory = new SeccocoFactory("seccoco-secured", argumentList);
        seccoco = seccocoFactory.create();
    } catch (InitializationException e) {
        System.out.println(e.getMessage());
        System.exit(-1);
    }
    try {
        System.out.println("Connecting to Ethereum RPC at " + cmdLineResult.getUrl());
        URL url = new URL(cmdLineResult.getUrl());
        HashMap<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json");
        String additionalHeaders = cmdLineResult.getAdditionalHeaders();
        if (additionalHeaders != null) {
            StringTokenizer tokenizer = new StringTokenizer(additionalHeaders, ",");
            while (tokenizer.hasMoreTokens()) {
                String keyValue = tokenizer.nextToken();
                StringTokenizer innerTokenizer = new StringTokenizer(keyValue, ":");
                headers.put(innerTokenizer.nextToken(), innerTokenizer.nextToken());
            }
        }
        settings = new Settings(cmdLineResult.isExposeWhisper(), headers);
        jsonRpcHttpClient = new JsonRpcHttpClient(url);
        jsonRpcHttpClient.setRequestListener(new JsonRpcRequestListener());

        jsonRpcHttpClient.invoke("eth_protocolVersion", null, Object.class, headers);
        if (cmdLineResult.isExposeWhisper()) {
            jsonRpcHttpClient.invoke("shh_version", null, Object.class, headers);
        }
        System.out.println("Connection succeeded");
    } catch (Throwable e) {
        System.out.println("Connection failed: " + e.getMessage());
        System.exit(-1);
    }
    SpringApplication app = new SpringApplication(Application.class);
    app.setBanner(new Banner() {
        @Override
        public void printBanner(Environment environment, Class<?> aClass, PrintStream printStream) {
            //send the Spring Boot banner to /dev/null
        }
    });
    app.run(new String[] {});
}

From source file:org.apache.tomcat.vault.VaultTool.java

public static void main(String[] args) {

    VaultTool tool = null;//  w  ww . j  av  a  2s  .  c  o  m

    if (args != null && args.length > 0) {
        int returnVal = 0;
        try {
            tool = new VaultTool(args);
            returnVal = tool.execute();
            if (!skipSummary) {
                tool.summary();
            }
        } catch (Exception e) {
            System.err.println("Problem occured:");
            System.err.println(e.getMessage());
            System.exit(1);
        }
        System.exit(returnVal);
    } else {
        tool = new VaultTool();

        Console console = System.console();

        if (console == null) {
            System.err.println("No console.");
            System.exit(1);
        }

        Scanner in = new Scanner(System.in);
        while (true) {
            String commandStr = "Please enter a Digit::   0: Start Interactive Session "
                    + " 1: Remove Interactive Session " + " Other: Exit";

            System.out.println(commandStr);
            int choice = -1;

            try {
                choice = in.nextInt();
            } catch (InputMismatchException e) {
                System.err.println("'" + in.next() + "' is not a digit. Restart and enter a digit.");
                System.exit(3);
            }

            switch (choice) {
            case 0:
                System.out.println("Starting an interactive session");
                VaultInteractiveSession vsession = new VaultInteractiveSession();
                tool.setSession(vsession);
                vsession.start();
                break;
            case 1:
                System.out.println("Removing the current interactive session");
                tool.setSession(null);
                break;
            default:
                System.exit(0);
            }
        }

    }

}

From source file:uk.org.openeyes.diagnostics.FieldProcessorApp.java

public static void main(String[] args) {

    if (args.length == 0) {
        System.out.println("Try -h");
        System.exit(1);//from w w w  .java2s .  c o m
    }
    Options options = CommonOptions.getCommonOptions();
    Option optionHost = new Option("s", "host", true, "Specify server to send messages to.");
    Option optionPort = new Option("p", "port", true, "Port to connect to on server.");
    Option optionCredentials = new Option("c", "credentials", true,
            "Supply username/password (comma separated) for authentication.");
    Option optionInDir = new Option("d", "dir", true, "Directory to watch for new files.");
    Option optionDupDir = new Option("u", "duplicates", true,
            "Duplicate files (successfully transferred) are moved to this directory.");
    Option optionOutgoing = new Option("t", "outgoing", true,
            "Directory to place measurement files that were not successfully sent.");
    options.addOption(optionInDir);
    options.addOption(optionHost);
    options.addOption(optionCredentials);
    options.addOption(optionPort);
    options.addOption(optionDupDir);
    options.addOption(optionOutgoing);
    FieldProcessor watcher = new FieldProcessor();
    CommonOptions.parseCommonOptions(watcher, options, args);
    CommandLineParser parser = new PosixParser();
    try {
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption("help") || cmd.hasOption('h')) {
            FhirUtils.printHelp(options);
        }
        if (cmd.hasOption("s") || cmd.hasOption("host")) {
            watcher.setHost(cmd.getOptionValue("host"));
        }
        if (cmd.hasOption("t") || cmd.hasOption("outgoing")) {
            watcher.setOutgoingDir(cmd.getOptionValue("outgoing"));
        }
        if (cmd.hasOption("c") || cmd.hasOption("credentials")) {
            if (!cmd.getOptionValue("credentials").contains(",")) {
                System.err.println("Supply credentials separated by a comma (',').");
                System.exit(1);
            }
            String[] credentials = cmd.getOptionValue("credentials").split(",");
            if (credentials.length == 1) {
                Console cnsl = System.console();
                ;
                if (cnsl != null) {
                    watcher.setAuthenticationPassword(
                            new String(cnsl.readPassword("Enter authentication password: ")));
                }
                watcher.setAuthenticationUsername(credentials[0]);
            } else {
                watcher.setAuthenticationUsername(credentials[0]);
                watcher.setAuthenticationPassword(credentials[1]);
            }
        }
        if (cmd.hasOption("p") || cmd.hasOption("port")) {
            String port = cmd.getOptionValue("port");
            try {
                watcher.setPort(Integer.parseInt(port));
            } catch (NumberFormatException nfex) {
                System.err.println("Invalid value: " + port);
                System.err.println("Specify port number as a positive integer.");
                System.exit(1);
            }
        }
    } catch (Exception ex) {
        System.err.println("Error: " + ex.getMessage());
    }
}

From source file:com.github.sgelb.sldownloader.SLDownloader.java

public static void main(String[] args) {
    SLDownloader sl = new SLDownloader();
    if (System.console() != null) { // started from console
        sl.runCLI(args);//  www .  ja va  2  s .c  o  m
    } else {
        sl.runGUI();
    }
}