Example usage for java.io Console readLine

List of usage examples for java.io Console readLine

Introduction

In this page you can find the example usage for java.io Console readLine.

Prototype

public String readLine() 

Source Link

Document

Reads a single line of text from the console.

Usage

From source file:io.github.benas.jql.shell.Shell.java

public static void main(String[] args) {
    String databaseFile = "";
    if (args.length >= 1) {
        databaseFile = args[0];//from w  ww . j ava  2 s  .co  m
    }

    DataSource dataSource = getDataSourceFrom(databaseFile);
    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    resultSetExtractor = new StringResultSetExtractor();
    queryExecutor = new QueryExecutor(jdbcTemplate);

    Console console = getConsole();

    String command;
    while (true) {
        System.out.print("$>");
        command = console.readLine();
        if (command.equalsIgnoreCase("quit")) {
            break;
        }
        process(command);
    }
    System.out.println("bye!");
}

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

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

    final ProxyDesktop instance = new ProxyDesktop();
    try {//from w  ww .jav  a2s .  c  om
        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.wittawat.wordseg.Main.java

public static void main(String[] args) throws Exception {
    Console con = System.console();
    if (con == null) {
        System.out.println("The system must support console to run the program.");
        System.exit(1);// w ww  .j  av  a2 s .c  o  m
    }
    // Load model
    System.out.println("Loading model ...");
    Classifier model = Data.getDefaultModel();

    System.out.println("Finished loading model.");
    System.out.println(getAgreement());

    boolean isUseDict = true;

    // Dummy statement to eliminate all lazy loading
    System.out.println("\n" + new NukeTokenizer3(
            "?????",
            model, isUseDict).tokenize() + "\n");

    System.out.println(getHelp());

    final String SET_DICT_PAT_STR = "\\s*set\\s+dict\\s+(true|false)\\s*";
    final Pattern SET_DICT_PAT = Pattern.compile(SET_DICT_PAT_STR);
    while (true) {
        System.out.print(">> ");
        String line = con.readLine();
        if (line != null && !line.trim().equals("")) {

            line = line.trim();
            try {
                if (line.equals("h") || line.equals("help")) {
                    System.out.println(getHelp());
                } else if (line.equals("about")) {
                    System.out.println(getAbout());
                } else if (line.equals("agreement")) {
                    System.out.println(getAgreement());
                } else if (SET_DICT_PAT.matcher(line).find()) {
                    Matcher m = SET_DICT_PAT.matcher(line);
                    m.find();
                    String v = m.group(1);
                    isUseDict = v.equals("true");
                    System.out.println("Dictionary will " + (isUseDict ? "" : "not ") + "be used.");
                } else if (line.matches("q|quit|exit")) {
                    System.out.println("Bye");
                    System.exit(0);
                } else if (line.contains(":tokfile:")) {
                    String[] splits = line.split(":tokfile:");
                    String in = splits[0];
                    String out = splits[1];
                    String content = FileUtils.readFileToString(new File(in));
                    long start = new Date().getTime();

                    NukeTokenizer tokenizer = new NukeTokenizer3(content, model, isUseDict);

                    String tokenized = tokenizer.tokenize();
                    long end = new Date().getTime();
                    System.out.println("Time to tokenize: " + (end - start) + " ms.");
                    FileUtils.writeStringToFile(new File(out), tokenized);
                } else if (line.contains(":tokfile")) {
                    String[] splits = line.split(":tokfile");
                    String in = splits[0];

                    String content = FileUtils.readFileToString(new File(in));
                    long start = new Date().getTime();
                    NukeTokenizer tokenizer = new NukeTokenizer3(content, model, isUseDict);
                    String tokenized = tokenizer.tokenize();
                    long end = new Date().getTime();

                    System.out.println(tokenized);
                    System.out.println("Time to tokenize: " + (end - start) + " ms.");
                } else if (line.contains(":tok:")) {
                    String[] splits = line.split(":tok:");
                    String inText = splits[0];
                    String out = splits[1];

                    long start = new Date().getTime();
                    NukeTokenizer tokenizer = new NukeTokenizer3(inText, model, isUseDict);
                    String tokenized = tokenizer.tokenize();
                    long end = new Date().getTime();
                    System.out.println("Time to tokenize: " + (end - start) + " ms.");
                    FileUtils.writeStringToFile(new File(out), tokenized);
                } else if (line.contains(":tok")) {
                    String[] splits = line.split(":tok");
                    String inText = splits[0];

                    long start = new Date().getTime();
                    NukeTokenizer tokenizer = new NukeTokenizer3(inText, model, isUseDict);
                    String tokenized = tokenizer.tokenize();
                    long end = new Date().getTime();

                    System.out.println(tokenized);
                    System.out.println("Time to tokenize: " + (end - start) + " ms.");
                } else {
                    System.out.println("Unknown command");
                }
            } catch (Exception e) {
                System.out.println("Error. See the exception.");
                e.printStackTrace();
            }

        }
    }

}

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

/**
 * Entry point//from   w  w  w  .  ja  v a 2  s  .c  o 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:org.zanata.client.commands.ConfigurableCommand.java

@Deprecated
protected static void expectYes(Console console) throws IOException {
    String line = console.readLine();
    if (line == null) {
        throw new IOException("console stream closed");
    }//from  w  w w.j a va  2s  .  c  om
    if (!line.toLowerCase().equals("y") && !line.toLowerCase().equals("yes")) {
        throw new RuntimeException("operation aborted by user");
    }
}

From source file:net.minder.KnoxWebHdfsJavaClientExamplesTest.java

@BeforeClass
public static void setupSuite() {
    Console console = System.console();
    if (console != null) {
        console.printf("Knox Host: ");
        KNOX_HOST = console.readLine();
        console.printf("Topology : ");
        TOPOLOGY_PATH = console.readLine();
        console.printf("Username : ");
        TEST_USERNAME = console.readLine();
        console.printf("Password: ");
        TEST_PASSWORD = new String(console.readPassword());
    } else {/*from   w  ww .ja  v a  2s . co  m*/
        JLabel label = new JLabel("Enter Knox host, topology, username, password:");
        JTextField host = new JTextField(KNOX_HOST);
        JTextField topology = new JTextField(TOPOLOGY_PATH);
        JTextField username = new JTextField(TEST_USERNAME);
        JPasswordField password = new JPasswordField(TEST_PASSWORD);
        int choice = JOptionPane.showConfirmDialog(null,
                new Object[] { label, host, topology, username, password }, "Credentials",
                JOptionPane.OK_CANCEL_OPTION);
        assertThat(choice, is(JOptionPane.YES_OPTION));
        TEST_USERNAME = username.getText();
        TEST_PASSWORD = new String(password.getPassword());
        KNOX_HOST = host.getText();
        TOPOLOGY_PATH = topology.getText();
    }
    TOPOLOGY_URL = String.format("%s://%s:%d/%s/%s", KNOX_SCHEME, KNOX_HOST, KNOX_PORT, KNOX_PATH,
            TOPOLOGY_PATH);
    WEBHDFS_URL = String.format("%s/%s", TOPOLOGY_URL, WEBHDFS_PATH);
}

From source file:net.jmhertlein.alphonseirc.MSTDeskEngRunner.java

private static void loadConfig() {
    boolean read = false;
    File f = CONFIG_FILE;/*ww  w  .  ja v  a2  s  . c o m*/
    if (!f.exists()) {
        read = true;
        try {
            f.getParentFile().mkdirs();
            f.createNewFile();
            java.nio.file.Files.setPosixFilePermissions(Paths.get(f.toURI()),
                    PosixFilePermissions.fromString("rw-------"));
        } catch (IOException ex) {
            Logger.getLogger(MSTDeskEngRunner.class.getName()).log(Level.SEVERE, null, ex);
            System.err.println("Error writing empty config.yml!");
        }
    }

    Map<String, Object> config;

    if (read) {
        Console console = System.console();
        console.printf("Nick: \n->");
        nick = console.readLine();
        console.printf("\nPassword: \n-|");
        pass = new String(console.readPassword());
        console.printf("\nServer: \n->");
        server = console.readLine();
        console.printf("\nChannels: (ex: #java,#linux,#gnome)\n->");
        channels = Arrays.asList(console.readLine().split(","));
        System.out.println("Fetching max XKCD...");
        maxXKCD = fetchMaxXKCD();
        System.out.println("Fetched.");
        cachedUTC = System.currentTimeMillis();

        dadLeaveTimes = new HashMap<>();
        noVoiceNicks = new HashSet<>();

        writeConfig();
        System.out.println("Wrote config to file: " + CONFIG_FILE.getAbsolutePath());

    } else {
        try (FileInputStream fis = new FileInputStream(f)) {
            Yaml y = new Yaml();
            config = y.loadAs(fis, Map.class);
        } catch (IOException ex) {
            Logger.getLogger(MSTDeskEngRunner.class.getName()).log(Level.SEVERE, null, ex);
            System.err.println("Error parsing config!");
            return;
        }

        nick = (String) config.get("nick");
        pass = (String) config.get("password");
        server = (String) config.get("server");
        channels = (List<String>) config.get("channels");
        maxXKCD = (Integer) config.get("cachedMaxXKCD");
        cachedUTC = (Long) config.get("cachedUTC");
        noVoiceNicks = (Set<String>) config.get("noVoiceNicks");
        masters = (Set<String>) config.get("masters");
        if (masters == null) {
            masters = new HashSet<>();
            masters.add("Everdras");
        }

        if (noVoiceNicks == null)
            noVoiceNicks = new HashSet<>();

        noVoiceNicks.stream().forEach((s) -> System.out.println("Loaded novoice nick: " + s));
        masters.stream().forEach((s) -> System.out.println("Loaded master nick: " + s));

        if (checkXKCDUpdate())
            writeConfig();
        else
            System.out.println("Loaded cached XKCD.");

        Map<String, Object> serialDadLeaveTimes = (Map<String, Object>) config.get("dadLeaveTimes");
        dadLeaveTimes = new HashMap<>();
        if (serialDadLeaveTimes != null)
            serialDadLeaveTimes.keySet().stream().forEach((time) -> {
                dadLeaveTimes.put(LocalDate.parse(time),
                        LocalTime.parse((String) serialDadLeaveTimes.get(time)));
            });

    }
}

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

/**
 * @param submitUserFile//from  w  ww  .j  ava  2 s  .  com
 * @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:io.stallion.boot.MainRunner.java

/**
 * Runs the main Stallion service in auto-reload mode, which means that if a configuration file,
 * or a server-side javascript file, or a plugin file is touched, the entire application context
 * will reload and all server-side javascript will be re-processed. Use this when developing
 * to avoid having to manually restart every time you change a file.
 *
 *
 * @param args/*from  w w w  . j  a v  a 2s  .co m*/
 * @param plugins
 * @throws Exception
 */
public static void runWithAutoReload(String[] args, StallionJavaPlugin[] plugins) throws Exception {
    isDebugRunner = true;

    Console console = System.console();
    while (true) {
        Log.info("(re)start in debug reloading mode.");
        try {
            reboot(args, plugins);
            if (doReload) {
                doReload = false;
                continue;
            }
            System.out.println("Interrupted. Type q to quit, any other key to reboot.");
            String input = console.readLine();
            if (input.startsWith("q")) {
                break;
            }
        } catch (Exception e) {
            ExceptionUtils.printRootCauseStackTrace(e);
            System.out.println("Other exception. Type q to quit, any other key to reboot.");
            String input = console.readLine();
            if (input.startsWith("q")) {
                break;
            }
        }
    }
    Log.info("Shutting down javascript and conf file watcher.");
    if (watcher != null) {
        watcher.setShouldRun(false);
    }
    watcherThread.interrupt();
    watcherThread.join();
    System.out.println("Exiting.");
    System.exit(0);
}

From source file:org.wso2.ppaas.tools.artifactmigration.ConversionTool.java

/**
 * Method to validate configuration inputs and redirect to console inputs
 *
 * @param propertyConstant/* w w w .  j  ava 2  s  .  com*/
 * @param propertyName
 */
private static void validateConfigurationInputs(String propertyConstant, String propertyName) {
    Console console = System.console();
    if (System.getProperty(propertyConstant) == null || System.getProperty(propertyConstant).isEmpty()) {
        System.out.print("Enter the " + propertyName);
        if (propertyName.contains("Password")) {
            char[] passwordChars = console.readPassword();
            System.setProperty(propertyConstant, new String(passwordChars));
        } else {
            System.setProperty(propertyConstant, console.readLine());
        }
        System.out.println();
    }
}