List of usage examples for java.lang System console
public static Console console()
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);/*from www .j av a2 s . co 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.jboss.as.security.vault.VaultTool.java
public static void main(String[] args) { VaultTool tool = null;//from w w w. java 2 s . c o m if (args != null && args.length > 0) { int returnVal = 0; try { tool = new VaultTool(args); returnVal = tool.execute(); } catch (Exception e) { System.err.println(SecurityLogger.ROOT_LOGGER.problemOcurred()); e.printStackTrace(System.err); System.exit(1); } System.exit(returnVal); } else { tool = new VaultTool(); System.out.println("**********************************"); System.out.println("**** JBoss Vault ***************"); System.out.println("**********************************"); Console console = System.console(); if (console == null) { System.err.println(SecurityLogger.ROOT_LOGGER.noConsole()); System.exit(1); } Scanner in = new Scanner(System.in); while (true) { System.out.println(SecurityLogger.ROOT_LOGGER.interactiveCommandString()); try { int choice = in.nextInt(); switch (choice) { case 0: System.out.println(SecurityLogger.ROOT_LOGGER.startingInteractiveSession()); VaultInteractiveSession vsession = new VaultInteractiveSession(); tool.setSession(vsession); vsession.start(); break; case 1: System.out.println(SecurityLogger.ROOT_LOGGER.removingInteractiveSession()); tool.setSession(null); break; default: in.close(); System.exit(0); } } catch (InputMismatchException e) { in.close(); System.exit(0); } } } }
From source file:org.apache.juddi.v3.auth.MD5XMLDocAuthenticator.java
public static void main(String[] args) throws Exception { System.out.print("Password: "); char[] readPassword = System.console().readPassword(); System.out.println("Cipher: " + new MD5XMLDocAuthenticator(true).hash(new String(readPassword))); }
From source file:com.github.trohovsky.jira.analyzer.Main.java
public static void main(String[] args) throws Exception { final Options options = new Options(); options.addOption("u", true, "username"); options.addOption("p", true, "password (optional, if not provided, the password is prompted)"); options.addOption("h", false, "show this help"); options.addOption("s", true, "use the strategy for querying and output, the strategy can be either 'issues_toatal' (default) or" + " 'per_month'"); options.addOption("d", true, "CSV delimiter"); // parsing of the command line arguments final CommandLineParser parser = new DefaultParser(); CommandLine cmdLine = null;/*w w w . ja v a 2 s .c o m*/ try { cmdLine = parser.parse(options, args); if (cmdLine.hasOption('h') || cmdLine.getArgs().length == 0) { final HelpFormatter formatter = new HelpFormatter(); formatter.setOptionComparator(null); formatter.printHelp(HELP_CMDLINE, HELP_HEADER, options, null); return; } if (cmdLine.getArgs().length != 3) { throw new ParseException("You should specify exactly three arguments JIRA_SERVER JQL_QUERY_TEMPLATE" + " PATH_TO_PARAMETER_FILE"); } } catch (ParseException e) { System.err.println("Error parsing command line: " + e.getMessage()); final HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(HELP_CMDLINE, HELP_HEADER, options, null); return; } final String csvDelimiter = (String) (cmdLine.getOptionValue('d') != null ? cmdLine.getOptionObject('d') : CSV_DELIMITER); final URI jiraServerUri = URI.create(cmdLine.getArgs()[0]); final String jqlQueryTemplate = cmdLine.getArgs()[1]; final List<List<String>> queryParametersData = readCSVFile(cmdLine.getArgs()[2], csvDelimiter); final String username = cmdLine.getOptionValue("u"); String password = cmdLine.getOptionValue("p"); final String strategy = cmdLine.getOptionValue("s"); try { // initialization of the REST client final AsynchronousJiraRestClientFactory factory = new AsynchronousJiraRestClientFactory(); if (username != null) { if (password == null) { final Console console = System.console(); final char[] passwordCharacters = console.readPassword("Password: "); password = new String(passwordCharacters); } restClient = factory.createWithBasicHttpAuthentication(jiraServerUri, username, password); } else { restClient = factory.create(jiraServerUri, new AnonymousAuthenticationHandler()); } final SearchRestClient searchRestClient = restClient.getSearchClient(); // choosing of an analyzer strategy AnalyzerStrategy analyzer = null; if (strategy != null) { switch (strategy) { case "issues_total": analyzer = new IssuesTotalStrategy(searchRestClient); break; case "issues_per_month": analyzer = new IssuesPerMonthStrategy(searchRestClient); break; default: System.err.println("The strategy does not exist"); return; } } else { analyzer = new IssuesTotalStrategy(searchRestClient); } // analyzing for (List<String> queryParameters : queryParametersData) { analyzer.analyze(jqlQueryTemplate, queryParameters); } } finally { // destroy the REST client, otherwise it stucks restClient.close(); } }
From source file:org.jsweet.candies.InitProjectTool.java
public static void main(String[] args) throws Throwable { logger.info("JSweet init candy project tool - version: " + JSweetDefTranslatorConfig.getVersionNumber()); JSAP jsapSpec = defineArgs();// w w w . ja v a2 s . c o m JSAPResult jsapArgs = parseArgs(jsapSpec, args); if (!jsapArgs.success() || jsapArgs.getBoolean("help")) { printUsage(jsapSpec); System.exit(0); } if (jsapArgs.getBoolean("verbose")) { LogManager.getLogger("org.jsweet").setLevel(Level.ALL); } String artifactId = jsapArgs.getString("artifactId"); String version = jsapArgs.getString("version"); List<String> dependencyLocators = asList(defaultString(jsapArgs.getString("deps")).split(",")); File outDir = jsapArgs.getFile("out"); if (outDir == null || StringUtils.isBlank(outDir.getPath())) { outDir = new File("./target/candy-projects"); } outDir.mkdirs(); String projectName = "candy-" + artifactId; File projectDir = new File(outDir, projectName); logger.info("init candy project: \n" // + "* projectName: " + projectName + "\n" // + "* artifactId: " + artifactId + "\n" // + "* version: " + version + "\n" // + " to: " + projectDir.getAbsolutePath()); FileUtils.copyDirectory(getResourceFile("templates/candy-project"), projectDir); logger.info("generating README"); File readmeFile = new File(projectDir, "README.md"); String readmeFileContent = FileUtils.readFileToString(readmeFile) // .replace("${{CANDY_NAME}}", artifactId).replace("${{CANDY_VERSION}}", version); FileUtils.write(readmeFile, readmeFileContent); logger.info("generating pom.xml"); File pomFile = new File(projectDir, "pom.xml"); String pomFileContent = FileUtils.readFileToString(pomFile) // .replace("${{ARTIFACT_ID}}", artifactId) // .replace("${{VERSION}}", version) // .replace("${{DEPENDENCIES}}", generateMavenXmlForDependencies(dependencyLocators)); FileUtils.write(pomFile, pomFileContent); if (BooleanUtils.toBoolean(jsapArgs.getString("createGitHubRepository"))) { String gitHubUser = jsapArgs.getString("gitHubUser"); String gitHubPass = jsapArgs.getString("gitHubPass"); Console console = System.console(); if (isBlank(gitHubUser)) { gitHubUser = console.readLine("GitHub username: "); } if (isBlank(gitHubPass)) { gitHubPass = new String(console.readPassword("GitHub password for " + gitHubUser + ": ")); } createGitHubRepo(projectName, "Java API bridge for " + artifactId + " (JSweet candy)", gitHubUser, gitHubPass); ProcessUtil.init(); ProcessUtil.runCmd(projectDir, (out) -> { logger.info("git: " + out); }, "git init && git remote add origin https://github.com/jsweet-candies/" + projectName); } logger.info("***************************************************************************"); logger.info("candy project " + projectName + " successfully created to " + projectDir); logger.info("***************************************************************************"); }
From source file:org.apache.flume.tools.PasswordObfuscator.java
/** * * @param args needs --outfile/*from w w w. ja v a2 s.c o m*/ */ public static void main(String[] args) throws IOException, ParseException { Options options = new Options(); Option option = new Option(null, "outfile", true, "the file in which to store the password"); option.setRequired(true); options.addOption(option); CommandLineParser parser = new GnuParser(); CommandLine commandLine = parser.parse(options, args); String outputFile = commandLine.getOptionValue("outfile"); System.out.println("Enter the password : "); String password = new String(System.console().readPassword()); System.out.println("Verify password : "); if (!password.equals(new String(System.console().readPassword()))) { System.err.println("Passwords do not match. Please try again"); return; } try { encodeToFile(password, outputFile); System.out.println(); System.out.println("Password has been stored in file : " + outputFile); } catch (IOException e) { System.err.println("Unable to write to output file : " + outputFile); } }
From source file:pa55.java.core.PA55.java
public static void main(String[] args) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeySpecException { System.out.println("**** This is a reference implementation version " + APP_VERSION + " of pa55. Please see the project page (http://anirbanbasu.github.io/pa55/) for details. ****\r\n"); Console inputConsole = System.console(); //If it is available, we need Console for masking passwords. Scanner inputConsoleScanner;//w w w. java 2 s .com Scanner echoOptionScanner = new Scanner(System.in); boolean disableEcho = false; if (inputConsole != null) { //We can hide the input, but should we? Ask the user. System.out.println( "Do you want to hide the master secret and the password hint as you type them? Enter 1 to hide or 0 to not hide."); disableEcho = echoOptionScanner.nextInt() == 0 ? false : true; } String echoNotice; if (disableEcho) { inputConsoleScanner = new Scanner(inputConsole.reader()); echoNotice = " (your input will NOT be visible as you type)"; } else { inputConsoleScanner = new Scanner(System.in); echoNotice = " (your input will be visible as you type)"; } PA55 core = new PA55(); String lineInput = ""; System.out.println("Enter master secret" + echoNotice); lineInput = (disableEcho ? new String(inputConsole.readPassword()) : inputConsoleScanner.nextLine().trim()); while (lineInput.length() == 0) { System.out.println("Please enter a non-empty string" + echoNotice); lineInput = (inputConsole != null ? new String(inputConsole.readPassword()) : inputConsoleScanner.nextLine().trim()); } core.setMasterSecret(lineInput); System.out.println("Enter password hint" + echoNotice); lineInput = (disableEcho ? new String(inputConsole.readPassword()) : inputConsoleScanner.nextLine().trim()); while (lineInput.length() == 0) { System.out.println("Please enter a non-empty string" + echoNotice); lineInput = (inputConsole != null ? new String(inputConsole.readPassword()) : inputConsoleScanner.nextLine().trim()); } core.setPasswordHint(lineInput); int choiceInput = 0; System.out.println( "Choose desired length in characters:\r\n (0) default: 12 characters\r\n (1) 8 characters\r\n (2) 12 characters\r\n (3) 16 characters\r\n (4) 20 characters\r\n (5) 24 characters\r\n (6) 28 characters\r\n (7) 32 characters"); choiceInput = inputConsoleScanner.nextInt(); while (choiceInput < 0 || choiceInput > 7) { System.out.println("Please enter a choice between 0 and 7."); choiceInput = inputConsoleScanner.nextInt(); } if (choiceInput == 0) { choiceInput = 2; } core.setPbkdfLength((choiceInput + 1) * 3); System.out.println( "Choose the password iterations:\r\n (0) default: 500K\r\n (1) Low (10K)\r\n (2) 250K\r\n (3) 500K\r\n (4) 750K\r\n (5) 1M\r\n (6) 1.25M\r\n (7) 1.5M"); choiceInput = inputConsoleScanner.nextInt(); while (choiceInput < 0 || choiceInput > 7) { System.out.println("Please enter a choice between 0 and 7."); choiceInput = inputConsoleScanner.nextInt(); } if (choiceInput == 0) { choiceInput = 3; } if (choiceInput != 1) { core.setPbkdfRounds((choiceInput - 1) * 250000); } else { core.setPbkdfRounds(10000); } System.out.println( "Choose the HMAC algorithm:\r\n (0) default: SHA256\r\n (1) SHA1\r\n (2) SHA256\r\n (3) SHA512"); choiceInput = inputConsoleScanner.nextInt(); while (choiceInput < 0 || choiceInput > 3) { System.out.println("Please enter a choice between 0 and 3."); choiceInput = inputConsoleScanner.nextInt(); } if (choiceInput == 0) { choiceInput = 2; } core.setPbkdfAlgorithm(HMACHashFunction.values()[choiceInput - 1]); inputConsoleScanner.close(); echoOptionScanner.close(); System.out.print("Generating password...\r"); core.generatePBKDF2Password(); System.out.println("Your password is: " + core.getPbkdfGeneratedPassword()); }
From source file:nl.paston.bonita.importfile.Main.java
public static void main(String[] args) { // Parse the commandline arguments. CommandLine cmd = parseArguments(args); log.info("Starting bonita-importfile. For help information add -h."); // Get input paramters for Login API String serverUrl = getConsoleInput("Bonita server URL", DEFAULT_URL, cmd, Cmd.SERVER_URL.getName()); String applicationName = getConsoleInput("Bonita application name", DEFAULT_APPLICATION, cmd, Cmd.APPLICATION_NAME.getName()); // Connect to Bonita server and create the Login API. LoginAPI loginAPI = getLoginAPI(serverUrl, applicationName); // Get login parameters for APISession String userName = getConsoleInput("Bonita user name", DEFAULT_USER, cmd, Cmd.USERNAME.getName()); char[] password = cmd.hasOption(Cmd.PASSWORD.getName()) ? cmd.getOptionValue(Cmd.PASSWORD.getName()).toCharArray() : System.console().readPassword("Bonita password: "); // Create an APISession and a ProcessAPI. APISession apiSession = getAPISession(loginAPI, userName, password); ProcessAPI processAPI = getProcessAPI(apiSession); // Get a list of processes and let the user choose the process. List<ProcessDeploymentInfo> processList = getProcessList(processAPI); ProcessDeploymentInfo processDeploymentInfo = getProcess(processList, cmd); // Read records from file; Reader in = getReader(cmd);//from w w w . j a va2 s .co m Iterable<CSVRecord> records = getCSVRecords(in); // Parse and push records to Bonita. Iterator<CSVRecord> iterator = records.iterator(); CSVRecord fullHeader = getFullHeader(iterator); for (CSVRecord record : records) { Map<String, Serializable> map = parseRecord(record, fullHeader); pushRecordToBonita(processAPI, processDeploymentInfo, map); } log.info("Finished bonita-importfile succesfully."); }
From source file:org.osmdroid.geopackagetoosm.Main.java
/** * Main method to write tiles from a GeoPackage * * @param args//w ww.ja v a 2 s. co m */ public static void main(String[] args) throws Exception { TileFormatType tileType = null; String imageFormat = null; boolean rawImage = false; File geoPackageFile = null; String tileTable = null; String outputFile = ""; Options opts = new Options(); opts.addOption("t", true, "geopackage - x and y represent GeoPackage Tile Matrix width and height, " + "standard - x and y origin is top left (Google format)," + "tms - (Tile Map Service) x and y origin is bottom left"); opts.addOption("i", true, "Output image format: png, jpg, jpeg (default is 'jpg')"); opts.addOption("raw", false, "Use the raw image bytes, only works when combining and cropping is not required"); opts.addOption("table", true, "the tile table to export"); opts.addOption("input", true, "geopackage_file"); opts.addOption("output", true, "output database file"); opts.addOption("list", true, "(geopackage), lists all tile tables"); opts.addOption("shift", false, "interactive z x y into an osm key"); opts.addOption("help", false, "help"); CommandLineParser parser = new DefaultParser(); CommandLine parse = parser.parse(opts, args); if (parse.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("geopackageToOsm", opts); return; } if (parse.hasOption("list")) { GeoPackage geoPackage = GeoPackageManager.open(new File(parse.getOptionValue("list"))); Iterator<String> iterator = geoPackage.getTileTables().iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } return; } if (parse.hasOption("shift")) { System.out.print("Z = "); int z = Integer.parseInt(System.console().readLine()); System.out.print("Y = "); int y = Integer.parseInt(System.console().readLine()); System.out.print("X = "); int x = Integer.parseInt(System.console().readLine()); long key = ((z << z) + x << z) + y; System.out.println(key); return; } if (parse.hasOption("t")) { tileType = TileFormatType.valueOf(parse.getOptionValue("t").toUpperCase()); } else { tileType = TileFormatType.STANDARD; } if (parse.hasOption("i")) { imageFormat = (parse.getOptionValue("i")); } else { imageFormat = "jpg"; } if (parse.hasOption("raw")) { rawImage = true; } if (parse.hasOption("output")) { outputFile = parse.getOptionValue("output"); } else { outputFile = "out.sqlite"; } con = DriverManager.getConnection("jdbc:sqlite:output.db"); try { Statement stmt = con.createStatement(); stmt.executeUpdate("CREATE TABLE tiles (key INTEGER PRIMARY KEY, provider TEXT, tile BLOB);"); stmt.close(); } catch (Exception ex) { } geoPackageFile = new File(parse.getOptionValue("input")); if (!geoPackageFile.exists()) { System.err.println(geoPackageFile.getAbsolutePath() + " does not exist!"); return; } //outputDirectory = new File(parse.getOptionValue("output")); tileTable = parse.getOptionValue("table"); // Write the tiles try { writeTiles(geoPackageFile, tileTable, null, imageFormat, tileType, rawImage); } catch (Exception e) { throw e; } con.close(); }
From source file:cloud.elasticity.elastman.App.java
/** * The entry point to the ElastMan main program. * //from ww w . j a va 2 s . c om * @param args The first argument is the mode which can be inter, ident, or control * corresponding to interactive mode, system identification mode, or control mode. * The second argument is the configuration file * The third argument is password password */ public static void main(String[] args) { // 1) parse the command line // For more information http://commons.apache.org/cli/ Options options = new Options(); options.addOption("i", "ident", false, "Enter system identification mode."); options.addOption("c", "control", false, "Enter controller mode."); options.addOption("o", "options", true, "Configuration file. Default elastman.conf"); options.addOption("u", "username", true, "Username in the form Tenant:UserName"); options.addOption("p", "password", true, "User password"); options.addOption("k", "keyname", true, "Name of SSH key to use"); options.addOption("z", "zone", true, "The OpenStack availability zone such as the default RegionOne"); options.addOption("e", "endpoint", true, "The URL to access OpenStack API such as http://192.168.1.1:5000/v2.0/"); options.addOption("s", "syncserver", true, "The URL access the WebSyncServer"); options.addOption("h", "help", false, "Print this help"); CommandLineParser parser = new GnuParser(); try { cmd = parser.parse(options, args); } catch (ParseException e2) { System.out.println(e2.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("ElastMan", options, true); System.exit(1); } // if h then show help and exit if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("ElastMan", options, true); System.exit(0); } // 2) Try to load the properties file. // Command line arguments override settings in the properties file // If no properties file exists. defaults will be used String filename = "control.prop"; // the default file name if (cmd.hasOption("o")) { filename = cmd.getOptionValue("o"); } Props.load(filename, cmd); // Props.save(filename); // System.exit(-1); // 3) If no password in command line nor in config file then ask the user if (Props.password == null) { Console cons; char[] passwd; if ((cons = System.console()) != null && // more secure and without echo! (passwd = cons.readPassword("[%s]", "Password:")) != null) { Props.password = new String(passwd); } else { // if you don't have a console! E.g., Running in eclipse System.out.print("Password: "); Props.password = scanner.nextLine(); } } // 4) Start the UI App app = new App(); app.textUI(args); }