/** * An interface method that allows users to change their password. * * @param username The username of the current user. */ public void changePassword(String username) { char[] current_pw = pe.getPassword(username); char[] entered_password; char[] new_password; boolean is_okay; System.out.println("\nCHANGE PASSWORD"); do { is_okay = true; System.out.print("Enter your current password: "******"Password is incorrect. Please try again!\n"); is_okay = false; } } while (!is_okay); System.out.print("Enter your new password: "******"Your password had been changed!\n"); }
public static void main(String[] args) throws MessagingException, IOException { Properties props = new Properties(); try (InputStream in = Files.newInputStream(Paths.get("mail", "mail.properties"))) { props.load(in); } List<String> lines = Files.readAllLines(Paths.get(args[0]), Charset.forName("UTF-8")); String from = lines.get(0); String to = lines.get(1); String subject = lines.get(2); StringBuilder builder = new StringBuilder(); for (int i = 3; i < lines.size(); i++) { builder.append(lines.get(i)); builder.append("\n"); } Console console = System.console(); String password = new String(console.readPassword("Password: ")); Session mailSession = Session.getDefaultInstance(props); // mailSession.setDebug(true); MimeMessage message = new MimeMessage(mailSession); message.setFrom(new InternetAddress(from)); message.addRecipient(RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); message.setText(builder.toString()); Transport tr = mailSession.getTransport(); try { tr.connect(null, password); tr.sendMessage(message, message.getAllRecipients()); } finally { tr.close(); } }
/** Allows the System Administrator to create a new staff profile. */ public void createStaffProfile() { Staff new_staff = new Staff(); boolean isOkay; do { // enter username System.out.print("\nPlease enter the username: "******"Enter a password: "******"Choose a role:"); new_staff.setRole(enterRole()); isOkay = pe.createStaffProfile(new_staff); if (!isOkay) { System.out.println( "The username \"" + new_staff.getUsername() + "\" already exists. Please try again!\n"); } } while (!isOkay); System.out.println( "New staff profile under username \"" + new_staff.getUsername() + "\" has been saved.\n"); }
/** * Main driver - run this to start interactive password manager. * * @param args Prog args * @throws Throwable If something went very wrong. */ public static void main(String[] args) throws Throwable { Console c = System.console(); if (c == null) FError.errAndExit("You need to be running in CLI mode"); c.printf( "Welcome to FLogin!%nThis utility will encrypt & store your usernames/passwords%n(c) 2016 Fastily%n%n"); // let user enter user & pw combos HashMap<String, String> ul = new HashMap<>(); while (true) { String u = c.readLine("Enter a username: "******"!!! Characters hidden for security !!! %n"); char[] p1 = c.readPassword("Enter password for %s: ", u); char[] p2 = c.readPassword("Confirm/Re-enter password for %s: ", u); if (Arrays.equals(p1, p2)) ul.put(u, new String(p1)); else c.printf("Entered passwords do not match!%n"); if (!c.readLine("Continue? (y/N): ").trim().toLowerCase().matches("(?i)(y|yes)")) break; c.printf("%n"); } if (ul.isEmpty()) FError.errAndExit("You didn't enter any user/pass. Program will exit."); // Generating our JSONObject JSONObject jo = new JSONObject(); for (Map.Entry<String, String> e : ul.entrySet()) { JSONObject internal = new JSONObject(); internal.put("pass", e.getValue()); jo.put(e.getKey(), internal); } // Encrypt and dump to file KeyGenerator kg = KeyGenerator.getInstance("AES"); kg.init(128); SecretKey sk = kg.generateKey(); writeFiles(pf, sk.getEncoded()); Cipher cx = Cipher.getInstance("AES"); cx.init(Cipher.ENCRYPT_MODE, sk); writeFiles(px, cx.doFinal(jo.toString().getBytes("UTF-8"))); c.printf( "Successfully written out to '%s', '%s', '%s%s' and '%s%s'%n", pf, px, homefmt, pf, homefmt, px); }
public static void main(String[] args) { Console c = System.console(); char[] pw; if (c == null) { return; } pw = c.readPassword("%s", "pw: "); System.out.println(c.readLine("%s", "input: ")); }
public static String readFromStdin(boolean isEcho) throws IOException { // int len = System.in.read(STDIN_BUFFER); // return new String(STDIN_BUFFER, 0, len).trim(); if (isEcho) { return console.readLine().trim(); } return new String(console.readPassword()).trim(); }
public static void main(String argv[]) { Console console = System.console(); String username = console.readLine("Username: "******"Password: "******"Entered password: " + new String(password)); // clear the array as soon as the password has been used Arrays.fill(password, ' '); }
/** Prompts the user to enter a password for authentication credentials. */ private String promptForPassword() { Console console = System.console(); if (console != null) { return new String( console.readPassword(Messages.i18n.format("PASSWORD_PROMPT"))); // $NON-NLS-1$ } else { System.err.println(Messages.i18n.format("NO_CONSOLE_ERROR_2")); // $NON-NLS-1$ return null; } }
/** get password from console */ public static char[] getPasswordFromConsole(BufferedReader br) throws IOException { char[] password; Console con = System.console(); if (null != con) { password = con.readPassword(); } else { password = br.readLine().toCharArray(); _log.debug("password=" + new String(password)); } return password; }
public static void main(String[] args) { Console console = System.console(); if (console != null) { String user = new String(console.readLine("Enter username:"******"Enter password")); console.printf("User name is " + user + "\n"); console.printf("Password is " + pwd + "\n"); } else { System.out.println("Console is unavaliable"); } }
public void _sign(SignOptions options) throws Exception { String password = null; if (options.password() == null) { Console console = System.console(); if (console == null) { error("No -p/--password set for PGP key and no console to ask"); } else { char[] pw = console.readPassword("Passsword: "); if (pw == null || pw.length == 0) { error("Password not entered"); } password = new String(pw); } } else password = options.password(); Signer signer = new Signer(new String(password), options.command(getProperty("gpg", System.getenv("GPG")))); if (signer == null || password == null || !isOk()) return; List<String> args = options._arguments(); if (args.isEmpty()) { List<URI> files = nexus.files(); for (URI uri : files) { try { trace("signing %s", relative(uri)); File f = nexus.download(uri); byte[] signature = signer.sign(f); if (options.show()) show(signature); else nexus.upload(new URI(uri + ".asc"), signature); } catch (Exception e) { exception(e, "could not download/sign/upload %s", relative(uri)); } } } else { for (String arg : args) { File f = getFile(arg); if (!f.isFile()) { error("Can't find file %s", f); } else { byte[] signature = signer.sign(f); if (options.show()) show(signature); else { File out = new File(f.getParentFile(), f.getName() + ".asc"); IO.store(signature, out); } } } } }
public static void main(String args[]) throws IOException { Console c = System.console(); if (c == null) { System.err.println("No console."); System.exit(1); } String login = c.readLine("Enter your login: "******"Enter your old password: "******"Enter new password: "******"Reenter new password: "******"Passwords don't match. Try again. %n"); } else { change(login, newPassword1); c.format("Password for %s changed.%n", login); } Arrays.fill(newPassword1, ' '); Arrays.fill(newPassword2, ' '); } while (noMatch); } String op = new String(oldPassword); System.out.println("oldPassword: "******"Unicode character at password position " + i + ": " + op.codePointAt(i)); i++; } Arrays.fill(oldPassword, ' '); String op2 = new String(oldPassword); System.out.println("oldPassword: " + op2 + op2.length()); }
public static String readPassword(String msg) { char[] answer = {0}; Console console = null; try { console = System.console(); } catch (Exception ex) { } if (console != null) { try { answer = console.readPassword(msg); } catch (Exception ex) { } } return new String(answer); }
public static void main(String[] args) { Console cons; char[] passwd; StringBuilder sb = new StringBuilder(); try { if ((cons = System.console()) != null && (passwd = cons.readPassword("[%s]", "Password:"******"password get: " + sb.insert(0, passwd).toString()); java.util.Arrays.fill(passwd, ' '); } // end if } catch (IOError e) { System.out.println(e); } // end catch } // end main
public static void main(String[] args) { WSDAPI api = WSDAPI.getInstance(); Console console = System.console(); APIResponse info_resp = api.getProfile(1); System.out.println(info_resp.toString()); System.out.println("Online: " + api.getUser().toString()); System.out.println("GenPass1: " + api.generatePassword()); System.out.println("GenPass2: " + api.generatePassword()); System.out.println("GenPass3: " + api.generatePassword()); Scanner sc = new Scanner(System.in); System.out.println("Username: "******"Password: "******"Success: " + login_resp.success() + ", error: " + login_resp.getError() + ", [" + login_resp.getID() + "] " + login_resp.getUsername() + ", rank: " + login_resp.getInt("rank")); APIResponse resp = api.getUser(); System.out.println( resp.success() + ": " + resp.getError() + ", [" + resp.getID() + "] " + resp.getUsername()); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } }
/** Allows the System Administrator to edit a staff profile. */ public void editStaffProfile() { Staff staff = pe.getStaff(enterUsername()); int choice = 0; boolean isOkay; System.out.println("Editing profile of " + staff.getUsername()); System.out.println("1. Change password"); System.out.println("2. Change role"); do { isOkay = true; System.out.print("Enter your choice: "); try { choice = in.nextInt(); if (choice < 1 || choice > 2) { isOkay = false; System.out.println("The selected option doesn't exist. Please try again!\n"); } } catch (InputMismatchException e) { isOkay = false; System.out.println("Invalid input detected. Please try again!\n"); } } while (!isOkay); switch (choice) { case 1: // enter password System.out.print("Enter the new password: "******"Staff profile under username \"" + staff.getUsername() + "\" has been saved.\n"); }
/** Get password for the input principal from console */ private static String getPassword(String principal) { Console console = System.console(); if (console == null) { System.out.println( "Couldn't get Console instance, " + "maybe you're running this from within an IDE. " + "Use scanner to read password."); System.out.println("Password for " + principal + ":"); try (Scanner scanner = new Scanner(System.in, "UTF-8")) { return scanner.nextLine().trim(); } } console.printf("Password for " + principal + ":"); char[] passwordChars = console.readPassword(); String password = new String(passwordChars).trim(); Arrays.fill(passwordChars, ' '); return password; }
public static void main(String args[]) { Console consola = System.console(); // si consola es null significa que no tenemos consola if (consola == null) { System.out.printf("No existe una consola"); System.exit(0); // Termina la aplicación } consola.printf("user: "******"pass: "******"\nEl usuario introducido es: " + usuario + ", y el password es: " + pass + "\n"); }
public void create(Node node, Interrupter interrupter) throws Exception { AgentChannelManager agentChannelManager = node.agentChannelManager(); System.out.println( "\n*** ConsoleApp " + agentChannelManager.agentChannelManagerAddress() + " ***\n"); Console cons = System.console(); boolean authenticated = false; while (!authenticated) { operatorName = cons.readLine("name: "); authenticated = node.passwordAuthenticator() .authenticate(operatorName, new String(cons.readPassword("password: "******"invalid\n\n"); } interpreter = new Interpreter(); interpreter.initialize(node.mailboxFactory().createAsyncMailbox()); interpreter.configure(operatorName, node, this, System.out); if (interrupter != null) { node.mailboxFactory().addClosable(interrupter); interrupter.activate(interpreter); } this.node = node; agentChannelManager.interpreters.add(interpreter); inbr = new BufferedReader(new InputStreamReader(System.in)); JAFuture future = new JAFuture(); boolean first = true; while (true) { String commandLine = null; while (commandLine == null) { if (!first) System.out.println(); else first = false; interpreter.prompt(); commandLine = input(); } (new Interpret(commandLine)).send(future, interpreter); } }
// // This should probably be a separate tool and not be baked into Maven. // private void encryption(CliRequest cliRequest) throws Exception { if (cliRequest.commandLine.hasOption(CLIManager.ENCRYPT_MASTER_PASSWORD)) { String passwd = cliRequest.commandLine.getOptionValue(CLIManager.ENCRYPT_MASTER_PASSWORD); if (passwd == null) { Console cons = System.console(); char[] password = (cons == null) ? null : cons.readPassword("Master password: "******"Password: "******"~")) { configurationFile = System.getProperty("user.home") + configurationFile.substring(1); } String file = System.getProperty(DefaultSecDispatcher.SYSTEM_PROPERTY_SEC_LOCATION, configurationFile); String master = null; SettingsSecurity sec = SecUtil.read(file, true); if (sec != null) { master = sec.getMaster(); } if (master == null) { throw new IllegalStateException( "Master password is not set in the setting security file: " + file); } DefaultPlexusCipher cipher = new DefaultPlexusCipher(); String masterPasswd = cipher.decryptDecorated(master, DefaultSecDispatcher.SYSTEM_PROPERTY_SEC_LOCATION); System.out.println(cipher.encryptAndDecorate(passwd, masterPasswd)); throw new ExitException(0); } }
public static void main(String[] args) { // default values String host = ""; String domain = ""; String user = ""; String passwd = ""; int timeout = 5000; int n_measures = 1; int delay = 1000; boolean cpu = false; int cpu_warning = 85; int cpu_critical = 95; boolean memory = false; int mem_warning = 85; int mem_critical = 95; boolean disk = false; int disk_warning = 85; int disk_critical = 95; boolean service = false; String exclude = ""; int serv_critical = 1; int verbose = 1; Level logging = Level.OFF; // create a new parser and add all possible options CmdLineParser parser = new CmdLineParser(); Option host_op = parser.addStringOption('t', "targethost"); Option domain_op = parser.addStringOption('d', "domain"); Option user_op = parser.addStringOption('u', "user"); Option passwd_op = parser.addStringOption('p', "password"); Option timeout_op = parser.addIntegerOption("timeout"); Option n_measures_op = parser.addIntegerOption('n', "number_of_measures"); Option delay_op = parser.addIntegerOption("delay"); Option cpu_op = parser.addBooleanOption("cpu"); Option cpu_warning_op = parser.addIntegerOption("cpu_warning"); Option cpu_critical_op = parser.addIntegerOption("cpu_critical"); Option memory_op = parser.addBooleanOption("memory"); Option mem_warning_op = parser.addIntegerOption("mem_warning"); Option mem_critical_op = parser.addIntegerOption("mem_critical"); Option disk_op = parser.addBooleanOption("disk"); Option disk_warning_op = parser.addIntegerOption("disk_warning"); Option disk_critical_op = parser.addIntegerOption("disk_critical"); Option service_op = parser.addBooleanOption("services"); Option exclude_op = parser.addStringOption('x', "exclude"); Option help_op = parser.addBooleanOption('h', "help"); Option verbose_op = parser.addBooleanOption('v', "verbose"); Option version_op = parser.addBooleanOption('V', "version"); try { // parse the arguments parser.parse(args); } catch (Exception e) { fail(e.getMessage()); } // -h or --help option was given just print helpmessage and exit if ((Boolean) parser.getOptionValue(help_op, false)) { System.out.println(helpmessage); System.exit(0); } // -V or --version option was given just print version information and exit if ((Boolean) parser.getOptionValue(version_op, false)) { System.out.println(version); System.exit(0); } // check if a settingsfile was given and check if it exists if (args.length == 0) fail("Please provide a settingsfile"); String settingsFile = args[0]; if (!new File(settingsFile).exists()) fail("Settingsfile '" + settingsFile + "' not found"); if (parser.getRemainingArgs().length != 1) fail("Syntax error"); // Properties properties = new Properties(); try { properties.load(new FileInputStream(settingsFile)); } catch (IOException e) { fail(e.getMessage()); } try { // get all values host = (String) getValue(parser, properties, host_op, host); domain = (String) getValue(parser, properties, domain_op, domain); user = (String) getValue(parser, properties, user_op, user); passwd = (String) getValue(parser, properties, passwd_op, passwd); timeout = (Integer) getValue(parser, properties, timeout_op, timeout); n_measures = (Integer) getValue(parser, properties, n_measures_op, n_measures); delay = (Integer) getValue(parser, properties, delay_op, delay); cpu = (Boolean) getValue(parser, properties, cpu_op, cpu); cpu_warning = getPercentage((Integer) getValue(parser, properties, cpu_warning_op, cpu_warning)); cpu_critical = getPercentage((Integer) getValue(parser, properties, cpu_critical_op, cpu_critical)); memory = (Boolean) getValue(parser, properties, memory_op, memory); mem_warning = getPercentage((Integer) getValue(parser, properties, mem_warning_op, mem_warning)); mem_critical = getPercentage((Integer) getValue(parser, properties, mem_critical_op, mem_critical)); disk = (Boolean) getValue(parser, properties, disk_op, disk); disk_warning = getPercentage((Integer) getValue(parser, properties, disk_warning_op, disk_warning)); disk_critical = getPercentage((Integer) getValue(parser, properties, disk_critical_op, disk_critical)); service = (Boolean) getValue(parser, properties, service_op, service); exclude = (String) getValue(parser, properties, exclude_op, service); verbose += parser.getOptionValues(verbose_op).size(); } catch (NumberFormatException e) { fail(e.getMessage()); } catch (IllegalOptionValueException e) { fail(e.getMessage()); } catch (IllegalArgumentException e) { fail(e.getMessage()); } // check if all necessary values were given if (host.isEmpty() || domain.isEmpty() || user.isEmpty() || passwd.isEmpty()) { String message = "Following values are missing: "; if (host.isEmpty()) message += "targethost, "; if (domain.isEmpty()) message += "domain, "; if (user.isEmpty()) message += "user, "; if (passwd.isEmpty()) message += "password, "; message = message.substring(0, message.length() - 2); fail(message); } // if the password is a asterisk ask the user for the password if (passwd.equals("*")) { Console cons = System.console(); if (cons == null) fail("must use a console"); System.out.print("Password: "******"getting password failed"); passwd = ""; for (char z : password) passwd += z; java.util.Arrays.fill(password, ' '); } // all warnings and criticals are added to this lists LinkedList<String> warnings = new LinkedList<String>(); LinkedList<String> criticals = new LinkedList<String>(); try { try { // disable console logging JISystem.setInBuiltLogHandler(false); Handler inbuildloghandler = JISystem.getLogger().getHandlers()[0]; JISystem.getLogger().removeHandler(inbuildloghandler); inbuildloghandler.close(); } catch (IOException e) { } catch (SecurityException e) { } JISystem.getLogger().setLevel(logging); if (logging != Level.OFF) { // enable file logging Random r = new Random(); // create a random string with a length of 12 - 13 characters String token = Long.toString(Math.abs(r.nextLong()), 36); try { String tmpdir = System.getProperty("java.io.tmpdir"); // on windows java.io.tmpdir ends with a slash on unix not if (!tmpdir.endsWith(File.separator)) tmpdir = tmpdir + File.separator; FileHandler logFile = new FileHandler(tmpdir + "j-Interop-" + token + ".log"); logFile.setFormatter(new SimpleFormatter()); JISystem.getLogger().addHandler(logFile); } catch (FileNotFoundException e) { System.out.println("ERROR: Failed to open log file: " + e.getMessage()); } catch (SecurityException e) { fail(e, verbose); } catch (IOException e) { fail(e, verbose); } } JISystem.setAutoRegisteration(true); WindowsHealth monitor = new WindowsHealth(host, domain, user, passwd, timeout, verbose > 2); boolean print; if (cpu) monitor.getCPUUsage(); // first measure gives no result for (int i = 0; i < n_measures; i++) { try { Thread.sleep(delay); } catch (InterruptedException e) { break; } if (verbose > 0 && i != 0) { System.out.println(); } if (verbose > 1 && n_measures > 1) System.out.println(" - Measure " + (i + 1) + " -"); // cpu load measure if (cpu) { print = false; int percent_cpu = monitor.getCPUUsage(); if (percent_cpu >= cpu_critical) { criticals.add("CPU (" + percent_cpu + "%)"); print = true; if (verbose > 0) System.out.print("CRITICAL: "); } else if (percent_cpu >= cpu_warning) { warnings.add("CPU (" + percent_cpu + "%)"); print = true; if (verbose > 0) System.out.print("WARNING: "); } if ((print && verbose > 0) || verbose > 1) System.out.println("CPU usage: " + percent_cpu + " %"); } // memory space measure if (memory) { print = false; long mem_size = monitor.getTotalMemorySize(); long mem_free = monitor.getFreeMemorySpace(); long mem_used = mem_size - mem_free; double percent_mem = (double) mem_used / (double) mem_size * 100; if (percent_mem >= mem_critical) { criticals.add("Memory (" + round(percent_mem, 1) + "%)"); print = true; if (verbose > 0) System.out.print("CRITICAL: "); } else if (percent_mem >= mem_warning) { warnings.add("Memory (" + round(percent_mem, 1) + "%)"); print = true; if (verbose > 0) System.out.print("WARNING: "); } if ((print && verbose > 0) || verbose > 1) System.out.println( "Memory: " + round(percent_mem, 2) + " % used (" + mem_used + " KB)"); } // disk space measure if (disk) { LinkedList<IJIDispatch> drives = monitor.getDiskDrives(); for (IJIDispatch drive : drives) { print = false; String name = drive.get("Name").getObjectAsString2(); double disk_free = Long.parseLong(drive.get("FreeSpace").getObjectAsString().getString()); double disk_size = Long.parseLong(drive.get("Size").getObjectAsString().getString()); double disk_used = disk_size - disk_free; double percent_disk = 0; if (disk_size != 0) percent_disk = disk_used / disk_size * 100; else { if (verbose > 1) System.out.println(name); continue; } if (percent_disk >= disk_critical) { criticals.add(name + " (" + round(percent_disk, 1) + "%)"); print = true; if (verbose > 0) System.out.print("CRITICAL: "); } else if (percent_disk >= disk_warning) { warnings.add(name + " (" + round(percent_disk, 1) + "%)"); print = true; if (verbose > 0) System.out.print("WARNING: "); } if ((print && verbose > 0) || verbose > 1) System.out.println( name + " " + round(percent_disk, 3) + " % used (" + getSizeRepresentation(disk_used, 3) + ")"); } } // find services if (service) { LinkedList<IJIDispatch> services = monitor.getServices(); LinkedList<IJIDispatch> services_final = new LinkedList<IJIDispatch>(); Scanner scanner = new Scanner(exclude); scanner.useDelimiter("\\s*,\\s*"); LinkedList<String> exclusions = new LinkedList<String>(); while (scanner.hasNext()) exclusions.add(scanner.next()); for (IJIDispatch service_dispatch : services) { String name = service_dispatch.get("DisplayName").getObjectAsString2(); if (!exclusions.contains(name)) services_final.add(service_dispatch); } int size = services_final.size(); String name; String serv = "services ("; for (IJIDispatch service_dispatch : services_final) { name = service_dispatch.get("DisplayName").getObjectAsString2(); serv += name + ";"; } serv += ")"; if (size >= serv_critical) { criticals.add(serv); } else if (verbose == 1) continue; if (verbose >= 1) { if (size >= serv_critical) System.out.print("CRITICAL: "); if (verbose == 1) { System.out.print(size + " service(s) ("); for (IJIDispatch service_dispatch : services_final) { name = service_dispatch.get("DisplayName").getObjectAsString2(); System.out.print(name + ";"); } System.out.println(") are/is not running"); } else { System.out.print(size + " problem(s) with services"); if (services_final.size() == 0) System.out.println("."); else System.out.println(":"); for (IJIDispatch service_dispatch : services_final) { name = service_dispatch.get("DisplayName").getObjectAsString2(); System.out.println(" service '" + name + "' is not running"); } } } } } // output a summary if (verbose < 1) { if (warnings.size() > 0) { System.out.print("WARNINGS:"); for (String w : warnings) { System.out.print(" " + w + ";"); } } if (criticals.size() > 0) { System.out.print(" CRITICALS:"); for (String c : criticals) { System.out.print(" " + c + ";"); } } if (warnings.size() == 0 && criticals.size() == 0) System.out.print("ALL OK"); System.out.println(); } else { if (warnings.size() == 0 && criticals.size() == 0) System.out.println("ALL OK"); else { System.out.println(); System.out.print("" + warnings.size() + " warnings and "); System.out.println("" + criticals.size() + " criticals."); } } } catch (UnknownHostException e) { fail("Unknown host: " + host, e, verbose); } catch (JIAutomationException e) { JIExcepInfo f = e.getExcepInfo(); fail(f.getExcepDesc() + "0x" + Integer.toHexString(f.getErrorCode()) + " ]", e, verbose); } catch (JIException e) { if (e.getCause().getClass().equals(SocketTimeoutException.class)) fail("Timeout error", e, verbose); else fail(e, verbose); } // if there are one or more criticals exit with exit status 2 if (criticals.size() != 0) System.exit(2); // if there are one or more warnings exit with exit status 1 if (warnings.size() != 0) System.exit(1); // otherwise exit with exit status 0 System.exit(0); }
@Override public char[] readPassword() throws ConsoleException { return console.readPassword(); }
/** * Possible commands are: - NAMESPACE - NAMESPACE name - LIST * - LIST kind - LIST kind * {"filter_name": filter_value} - LIST kind {"filter_name": filter_value} [fields] - PRINT key - * PUT key {full_json_obj} - SET key {fields_to_set} - EXIT * * @param args * @throws IOException */ public static void main(String[] args) throws IOException { Options options = new Options(); options.addOption(null, "localhost", false, "Connect to localhost instead of App Engine cloud"); options.addOption("A", "application", true, "The application ID to use."); options.addOption( "u", "email", true, "The email address of the Google account of an administrator for the application, for actions that require signing in. If omitted and no cookie is stored from a previous use of the command, the command will prompt for this value."); options.addOption("p", "password", true, "Password"); options.addOption( null, "passin", false, "If given, the tool accepts the Google account password in stdin instead of prompting for it interactively. This allows you to invoke the tool from a script without putting your password on the command line."); options.addOption("q", "quiet", false, "Do not print messages when successful."); options.addOption("v", "verbose", false, "Print messages about what the command is doing."); options.addOption("h", "help", false, "Print this help message."); try { CommandLineParser parser = new GnuParser(); CommandLine cmd = parser.parse(options, args); if (args.length == 0 || cmd.hasOption('h')) { printHelpAndExit(options); } else if (!cmd.hasOption('A') && !cmd.hasOption("localhost")) { System.err.println("Application ID is not specidfied, but it's required."); printHelpAndExit(options); } if (cmd.hasOption('q')) { System.setOut(new PrintStream(new NullOutputStream())); } String app_id = null; if (cmd.hasOption('A')) { app_id = cmd.getOptionValue('A'); } String email; if (!cmd.hasOption('u')) { System.out.print("Email:"); Scanner in = new Scanner(System.in); email = in.nextLine(); } else { email = cmd.getOptionValue('u'); } String password; if (cmd.hasOption("passin")) { System.out.print(String.format("Password for %s:", email)); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); password = br.readLine(); } else if (cmd.hasOption("password")) { password = cmd.getOptionValue("password"); } else { System.out.print(String.format("Password for %s:", email)); // hide input Console console = System.console(); if (console == null) { System.out.println("Couldn't get Console instance"); System.exit(0); } char passwordArray[] = console.readPassword(""); password = new String(passwordArray); } AppEngineShell shell; if (cmd.hasOption("localhost")) { shell = new AppEngineShell(cmd.hasOption('v'), email, password); } else { shell = new AppEngineShell(cmd.hasOption('v'), app_id, email, password); } shell.run(); } catch (ParseException e) { System.err.println(e.getMessage()); } }
public static void main(String[] args) throws Exception { String host = null; int port = -1; for (int i = 0; i < args.length; i++) { System.out.println("args[" + i + "] = " + args[i]); } if (args.length < 2) { System.out.println("USAGE: java client host port"); System.exit(-1); } try { /* get input parameters */ host = args[0]; port = Integer.parseInt(args[1]); } catch (IllegalArgumentException e) { System.out.println("USAGE: java client host port"); System.exit(-1); } try { /* set up a key manager for client authentication */ SSLSocketFactory factory = null; try { KeyStore ks = KeyStore.getInstance("JKS"); KeyStore ts = KeyStore.getInstance("JKS"); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); SSLContext ctx = SSLContext.getInstance("TLS"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter keystore: "); String keystoreName = br.readLine(); Console cons = System.console(); if (cons != null) { password = cons.readPassword("%s", "Password: "******"Cannot find a console to read password from. Eclipse CANNOT fork a terminal child process."); } ks.load(new FileInputStream("keystores/" + keystoreName), password); // keystore // password // (storepass) char[] cliTrustPW = "password".toCharArray(); ts.load(new FileInputStream("clienttruststore"), cliTrustPW); // truststore // password // (storepass); kmf.init(ks, password); // user password (keypass) tmf.init(ts); // keystore can be used as truststore here ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); factory = ctx.getSocketFactory(); } catch (Exception e) { e.printStackTrace(); throw new IOException(e.getMessage()); } SSLSocket socket = (SSLSocket) factory.createSocket(host, port); System.out.println("Handshake socket: " + socket + "\n"); /* * send http request * * See SSLSocketClient.java for more information about why there is * a forced handshake here when using PrintWriters. */ socket.startHandshake(); SSLSession session = socket.getSession(); X509Certificate cert = (X509Certificate) session.getPeerCertificateChain()[0]; System.out.println("Server DN: " + cert.getSubjectDN().getName()); System.out.println("Handshake socket: " + socket); System.out.println("Secure connection."); System.out.println("Issuer DN: " + cert.getIssuerDN().getName()); System.out.println("Serial N: " + cert.getSerialNumber().toString()); read = new BufferedReader(new InputStreamReader(System.in)); serverMsg = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getOutputStream(), true); ois = new ObjectInputStream(socket.getInputStream()); records = new ArrayList<Record>(); boolean isLoggedIn = false; boolean isDone = false; isLoggedIn = waitForLoginData(); if (!isLoggedIn) { System.out.println( "This certificate does not have a user. \n Press the RETURN key to exit."); System.console().readLine(); out.close(); read.close(); socket.close(); return; } boolean accessDenied = false; while (!isDone) { if (accessDenied) { System.out.println( "Access denied, or no such record exists! \n Type 'help' for commands."); } System.out.print(user.getUsername() + " commands>"); msg = read.readLine(); fetchRecords(); splitMsg = msg.split("\\s+"); try { if (msg.equalsIgnoreCase("quit")) { break; } else if (msg.equalsIgnoreCase("help")) { printHelp(); } else if (splitMsg[0].equalsIgnoreCase("records")) { printRecords(); accessDenied = false; } else if (splitMsg[0].equalsIgnoreCase("edit") && (accessDenied = hasPermissions(msg))) { editRecord(splitMsg[1]); fetchRecords(); accessDenied = false; } else if (splitMsg[0].equalsIgnoreCase("read") && (accessDenied = hasPermissions(msg))) { printRecord(splitMsg[1]); accessDenied = false; } else if (splitMsg[0].equalsIgnoreCase("delete") && (accessDenied = hasPermissions(msg))) { for (Record r : records) { if (r.getId() == Long.parseLong(splitMsg[1])) { r.delete(user); accessDenied = false; } } fetchRecords(); } else if (splitMsg[0].equalsIgnoreCase("create") && (accessDenied = hasPermissions(msg))) { createRecord(); fetchRecords(); accessDenied = false; } else { accessDenied = true; } } catch (Exception e) { accessDenied = true; } } ois.close(); out.close(); read.close(); socket.close(); } catch (Exception e) { e.printStackTrace(); } }
public Main(String[] commandLineArgs) throws Exception { Options options = new Options(); options.addOption("h", "hosts", true, "Set the Aerospike host node."); options.addOption("p", "port", true, "Set the port on which to connect to Aerospike."); options.addOption("U", "user", true, "User name."); options.addOption("P", "password", true, "Password."); options.addOption("n", "namespace", true, "Set the Aerospike namespace. Default: test."); options.addOption("s", "set", true, "Set the Aerospike set name. Default: set."); options.addOption( "k", "keys", true, "Set the number of keys the client is dealing with. " + "If using an 'insert' workload (detailed below), the client will write this " + "number of keys, starting from value = start_value. Otherwise, the client " + "will read and update randomly across the values between start_value and " + "start_value + num_keys."); options.addOption( "o", "objectSpec", true, "I | S:<size> | M:<type>:<size>\n" + "Set the type of object(s) to use in Aerospike transactions. Type can be 'I' " + "for integer, 'S' for string, or 'M' for map. If type is 'I' (integer), " + "do not set a size (integers are always 8 bytes). If type is 'S' " + "(string), this value represents the length of the string. If type is 'M' " + "(map), type represents the type of data which can be 'I' or 'S', and size " + "represents the length of the string if type is 'S'."); options.addOption( "R", "random", false, "Use dynamically generated random bin values instead of default static fixed bin values."); options.addOption( "S", "startkey", true, "Set the starting value of the working set of keys. " + "If using an 'insert' workload, the start_value indicates the first value to write. " + "Otherwise, the start_value indicates the smallest value in the working set of keys."); options.addOption( "w", "workload", true, "I | RU,{o,%}\n" + "Set the desired workload.\n\n" + " -w I sets a linear 'insert' workload.\n\n" + " -w RU,o,80 picks one item randomly and sets a random read-update workload with 80% reads and 20% writes.\n\n" + " -w RU,50,40 for 50% of items, sets a random read-update workload with 40% reads and 60% writes."); options.addOption( "g", "throughput", true, "Set a target transactions per second for the client. The client should not exceed this " + "average throughput."); options.addOption( "t", "transactions", true, "Number of transactions to perform in read/write mode before shutting down. " + "The default is to run indefinitely."); options.addOption( "T", "timeout", true, "Set read and write transaction timeout in milliseconds."); options.addOption( "z", "threads", true, "Set the number of threads the client will use to generate load. " + "It is not recommended to use a value greater than 125."); options.addOption( "latency", true, "<number of latency columns>,<range shift increment>\n" + "Show transaction latency percentages using elapsed time ranges.\n" + "<number of latency columns>: Number of elapsed time ranges.\n" + "<range shift increment>: Power of 2 multiple between each range starting at column 3.\n\n" + "A latency definition of '-latency 7,1' results in this layout:\n" + " <=1ms >1ms >2ms >4ms >8ms >16ms >32ms\n" + " x% x% x% x% x% x% x%\n" + "A latency definition of '-latency 4,3' results in this layout:\n" + " <=1ms >1ms >8ms >64ms\n" + " x% x% x% x%\n\n" + "Latency columns are cumulative. If a transaction takes 9ms, it will be included in both the >1ms and >8ms columns."); options.addOption("D", "debug", false, "Run benchmarks in debug mode."); options.addOption("u", "usage", false, "Print usage."); options.addOption("PS", "pageSize", true, "Page size in kilobyte. Default: 4K"); options.addOption("IC", "itemCount", true, "Number of items in LDT. Default: 100"); options.addOption("IS", "itemSize", true, "Item size in byte. Default: 8"); // Parse the command line arguments. CommandLineParser parser = new PosixParser(); CommandLine line = parser.parse(options, commandLineArgs); String[] extra = line.getArgs(); if (line.hasOption("u")) { logUsage(options); throw new UsageException(); } if (extra.length > 0) { throw new Exception("Unexpected arguments: " + Arrays.toString(extra)); } args.readPolicy = clientPolicy.readPolicyDefault; args.writePolicy = clientPolicy.writePolicyDefault; if (line.hasOption("hosts")) { this.hosts = line.getOptionValue("hosts").split(","); } else { this.hosts = new String[1]; this.hosts[0] = "127.0.0.1"; } if (line.hasOption("port")) { this.port = Integer.parseInt(line.getOptionValue("port")); } else { this.port = 3000; } clientPolicy.user = line.getOptionValue("user"); clientPolicy.password = line.getOptionValue("password"); if (clientPolicy.user != null && clientPolicy.password == null) { java.io.Console console = System.console(); if (console != null) { char[] pass = console.readPassword("Enter password:"******"pageSize")) { args.pageSize = Integer.parseInt(line.getOptionValue("pageSize")); } else { args.pageSize = 4096; // Default LDT page size: 4K. } if (line.hasOption("itemCount")) { args.itemCount = Integer.parseInt(line.getOptionValue("itemCount")); } else { args.itemCount = 100; // Default LDT item count. } if (line.hasOption("itemSize")) { args.itemSize = Integer.parseInt(line.getOptionValue("itemSize")); } else { args.itemSize = 8; // Default LDT item size. } if (line.hasOption("namespace")) { args.namespace = line.getOptionValue("namespace"); } else { args.namespace = "test"; } if (line.hasOption("set")) { args.setName = line.getOptionValue("set"); } else { args.setName = "set"; } if (line.hasOption("keys")) { this.nKeys = Integer.parseInt(line.getOptionValue("keys")); } else { this.nKeys = 100000; } if (line.hasOption("startkey")) { this.startKey = Integer.parseInt(line.getOptionValue("startkey")); } if (line.hasOption("objectSpec")) { String[] objectsArr = line.getOptionValue("objectSpec").split(","); args.objectSpec = new DBObjectSpec(); for (int i = 0; i < objectsArr.length; i++) { String[] objarr = objectsArr[i].split(":"); DBObjectSpec dbobj = new DBObjectSpec(); if ((DBObjectSpec.type = objarr[0].charAt(0)) == 'M') { DBObjectSpec.mapDataType = objarr[1].charAt(0); if (DBObjectSpec.mapDataType == 'S') { DBObjectSpec.mapDataSize = Integer.parseInt(objarr[2]); if (DBObjectSpec.mapDataSize <= 0) { throw new Exception("String length must be > 0."); } // How many entries inside the map. DBObjectSpec.mapValCount = (int) Math.ceil((float) args.itemSize / DBObjectSpec.mapDataSize); // System.out.println("********" + DBObjectSpec.mapValCount); } else { DBObjectSpec.mapValCount = (int) Math.ceil((float) args.itemSize / 8); // How many entries inside the map. System.out.println("mapValCount: " + DBObjectSpec.mapValCount); } } if (objarr.length > 1 && DBObjectSpec.type == 'S') { // There is a size value. DBObjectSpec.size = Integer.parseInt(objarr[1]); if (DBObjectSpec.size <= 0) { throw new Exception("String length must be > 0."); } } args.objectSpec = dbobj; System.out.println("type: " + DBObjectSpec.type); System.out.println("size: " + DBObjectSpec.size); System.out.println("mapType " + DBObjectSpec.mapDataType); System.out.println("mapSize " + DBObjectSpec.mapDataSize); System.out.println( "mapValCount " + args.itemSize + "/" + DBObjectSpec.mapDataSize + " = " + DBObjectSpec.mapValCount); } } else { args.objectSpec = new DBObjectSpec(); DBObjectSpec dbobj = new DBObjectSpec(); DBObjectSpec.type = 'I'; // If the object is not specified, it has one bin of integer type. args.objectSpec = dbobj; } args.readPct = 50; if (line.hasOption("workload")) { String[] workloadOpts = line.getOptionValue("workload").split(","); String workloadType = workloadOpts[0]; if (workloadType.equals("I")) { args.workload = Workload.INITIALIZE; this.initialize = true; if (workloadOpts.length > 1) { throw new Exception( "Invalid workload number of arguments: " + workloadOpts.length + " Expected 1."); } } else if (workloadType.equals("RU")) { args.workload = Workload.READ_UPDATE; if (workloadOpts.length != 3) { throw new Exception( "Invalid workload number of arguments: " + workloadOpts.length + " Expected 3."); } else { args.readPct = Integer.parseInt(workloadOpts[2]); if (workloadOpts[1].charAt(0) == 'o') { args.updateOne = true; } else { args.updatePct = Integer.parseInt(workloadOpts[1]); // Get the %. } if (args.readPct < 0 || args.readPct > 100) { throw new Exception("Read-update workload read percentage must be between 0 and 100."); } } } else { throw new Exception("Unknown workload: " + workloadType); } } if (line.hasOption("throughput")) { args.throughput = Integer.parseInt(line.getOptionValue("throughput")); } if (line.hasOption("transactions")) { args.transactionLimit = Long.parseLong(line.getOptionValue("transactions")); } if (line.hasOption("timeout")) { int timeout = Integer.parseInt(line.getOptionValue("timeout")); args.readPolicy.timeout = timeout; args.writePolicy.timeout = timeout; } if (line.hasOption("threads")) { this.nThreads = Integer.parseInt(line.getOptionValue("threads")); if (this.nThreads < 1) { throw new Exception("Client threads (-z) must be > 0"); } } else { this.nThreads = 16; } if (line.hasOption("debug")) { args.debug = true; } if (line.hasOption("latency")) { String[] latencyOpts = line.getOptionValue("latency").split(","); if (latencyOpts.length != 2) { throw new Exception("Latency expects 2 arguments. Received: " + latencyOpts.length); } int columns = Integer.parseInt(latencyOpts[0]); int bitShift = Integer.parseInt(latencyOpts[1]); counters.read.latency = new LatencyManager(columns, bitShift); counters.write.latency = new LatencyManager(columns, bitShift); } if (!line.hasOption("random")) { args.setFixedBins(); } System.out.println( "Benchmark: " + this.hosts[0] + ":" + this.port + ", namespace: " + args.namespace + ", set: " + (args.setName.length() > 0 ? args.setName : "<empty>") + ", threads: " + this.nThreads + ", workload: " + args.workload); if (args.workload == Workload.READ_UPDATE) { System.out.print("read: " + args.readPct + '%'); // System.out.print(" (all bins: " + args.readMultiBinPct + '%'); // System.out.print(", single bin: " + (100 - args.readMultiBinPct) + "%)"); System.out.print(", write: " + (100 - args.readPct) + '%'); // System.out.print(" (all bins: " + args.writeMultiBinPct + '%'); // System.out.println(", single bin: " + (100 - args.writeMultiBinPct) + "%)"); } System.out.println( "keys: " + this.nKeys + ", start key: " + this.startKey + ", transactions: " + args.transactionLimit + ", items: " + args.itemCount + ", random values: " + (args.fixedLDTBins == null) + ", throughput: " + (args.throughput == 0 ? "unlimited" : (args.throughput + " tps"))); if (args.workload != Workload.INITIALIZE) { System.out.println("read policy: timeout: " + args.readPolicy.timeout); } System.out.println("write policy: timeout: " + args.writePolicy.timeout); System.out.print("ldt-bin[" + args.itemCount + "]: "); switch (DBObjectSpec.type) { case 'I': System.out.println("integer"); break; case 'S': System.out.println("string[" + DBObjectSpec.size + "]"); break; case 'M': switch (DBObjectSpec.mapDataType) { case 'I': System.out.println("map of " + "integer"); case 'S': System.out.println("map of " + "string[" + DBObjectSpec.mapDataSize + "]"); default: throw new Exception("Unknown DataType: " + DBObjectSpec.type); } } System.out.println("debug: " + args.debug); Log.Level level = (args.debug) ? Log.Level.DEBUG : Log.Level.INFO; Log.setLevel(level); Log.setCallback(this); clientPolicy.failIfNotConnected = true; }
public void showMenu() { Scanner in = new Scanner(System.in); System.out.println("Welcome to the System!"); System.out.println("-login\n-exit\n**********"); String command; while (true) { command = in.next(); if (!isLoggedIn) { if (command.equals("exit")) { System.out.println("Thanks for using the system."); System.exit(0); } else if (command.equals("login")) { // if not already logged in,it will log in Console console = System.console(); System.out.print("username:"******"password:"******"Invalid username or password!"); } else if (result == 1) { System.out.println("You are successfully authenticated by kerberos server. "); isLoggedIn = true; System.out.println( "-create\n-open\n-Append\n-Copy" + "\n-Move\n-Delete\n-List\n-createdir\n-deletedir\n-logout\n**********"); } else if (result == -1) { } } else if (command.equals("logout")) { System.err.println("You are already logged out."); } /* }else{ // if already logged in, check for validity System.err.println("Already logged in. "); } */ } else if (this.isLoggedIn) { if (command.equals("login")) { System.err.println("Already logged in. "); } else if (command.equals("create")) { System.out.println("enter the path"); String path = in.next(); // send to server try { out3.writeInt(1); ticketValidationCode = in3.readInt(); if (ticketValidationCode != -1) { out3.writeUTF(path); int r = in3.readInt(); if (r == -1) { System.out.println("The file is already exist!"); } else { System.out.println("The file is created in " + path); } } else { this.isLoggedIn = false; } } catch (IOException e) { e.printStackTrace(); } // get a yes or no // create(file1); } else if (command.equals("open")) { System.out.println("enter the path"); String path = in.next(); try { out3.writeInt(2); ticketValidationCode = in3.readInt(); if (ticketValidationCode != -1) { out3.writeUTF(path); String r = in3.readUTF(); if (r.equals("NO")) { System.out.println("The file did not exist. A new file was created."); } else { this.cachCopy = r; System.out.println(cachCopy); } } else { this.isLoggedIn = false; } } catch (IOException e) { e.printStackTrace(); } } else if (command.equals("append")) { System.out.println("enter the path"); String path = in.next(); try { out3.writeInt(3); ticketValidationCode = in3.readInt(); if (ticketValidationCode != -1) { out3.writeUTF(path); int r = in3.readInt(); if (r == -1) { System.out.println("No content added! The path may be wrong."); } else { // out3.writeUTF(input); // String contents=FileOperations.readFile(path, Charset.defaultCharset()); String contents = FileOperations.append(path); out3.writeUTF(cachCopy + "\n" + contents); // System.out.println(contents); System.out.println("The input was appended to the file."); } } else { this.isLoggedIn = false; } } catch (IOException e) { e.printStackTrace(); } } else if (command.equals("copy")) { System.out.println("please enter source path:"); String sour = in.next(); try { out3.writeInt(4); ticketValidationCode = in3.readInt(); if (ticketValidationCode != -1) { out3.writeUTF(sour); int r = in3.readInt(); // System.out.println(r3); if (r == -1) { System.err.println("File can not be copied.The file may not exist!"); } else if (r == -2) { System.out.println("please enter target path:"); String tar = in.next(); out3.writeUTF(tar); System.out.println("The file was copied."); } } else { this.isLoggedIn = false; } } catch (IOException e) { e.printStackTrace(); } } else if (command.equals("move")) { System.out.println("please enter source path:"); String sour = in.next(); try { out3.writeInt(5); ticketValidationCode = in3.readInt(); if (ticketValidationCode != -1) { out3.writeUTF(sour); int r = in3.readInt(); // System.out.println(r2); if (r == -1) { System.out.println("File does not exist!"); } else if (r == -2) { System.out.println("please enter target path:"); String tar = in.next(); out3.writeUTF(tar); System.out.println("The file was moved."); } else { this.isLoggedIn = false; } } } catch (IOException e) { e.printStackTrace(); } } else if (command.equals("delete")) { System.out.println("enter the path"); String path = in.next(); try { out3.writeInt(6); ticketValidationCode = in3.readInt(); if (ticketValidationCode != -1) { out3.writeUTF(path); int r = in3.readInt(); if (r == -2) { System.out.println("No such file exist!"); } else { System.out.println("file was deleted."); } } else { this.isLoggedIn = false; } } catch (IOException e) { e.printStackTrace(); } } else if (command.equals("list")) { System.out.println("enter the path"); String path = in.next(); try { out3.writeInt(7); ticketValidationCode = in3.readInt(); if (ticketValidationCode != -1) { out3.writeUTF(path); String result = in3.readUTF(); if (result.equals("NO")) { System.out.println("An error happend while listing. Directory may not exist."); } else { System.out.println(result); } } else { this.isLoggedIn = false; } } catch (IOException e) { e.printStackTrace(); } } else if (command.equals("deletedir")) { System.out.println("enter the path"); String path = in.next(); try { out3.writeInt(8); ticketValidationCode = in3.readInt(); if (ticketValidationCode != -1) { out3.writeUTF(path); int r = in3.readInt(); if (r == -1) { System.out.println("The directory can not be deleted.It is not empty!"); } else if (r == -2) { System.out.println("No such directory exist!"); } else { System.out.println("Directory was deleted."); } } else { this.isLoggedIn = false; } } catch (IOException e) { e.printStackTrace(); } } else if (command.equals("createdir")) { System.out.println("enter the path"); String path = in.next(); try { out3.writeInt(9); ticketValidationCode = in3.readInt(); if (ticketValidationCode != -1) { out3.writeUTF(path); int r = in3.readInt(); if (r == -1) { System.out.println("The directory already exist!"); } else { System.out.println("The directory was created."); } } else { this.isLoggedIn = false; } } catch (IOException e) { e.printStackTrace(); } } else if (command.equals("logout")) { if (isLoggedIn) { isLoggedIn = false; System.out.println("You successfully logged out."); System.out.println("-login\n-exit\n**********"); } else { System.err.println("You are already logged out."); } } else { System.err.println("Invalid command!"); } } else { /* if(command.equals("logout")){ System.err.println("You are already logged out."); }else if (command.equals("exit")) { System.out.println("Thanks for using the system."); System.exit(0); }else{ */ System.out.println("You ticket is expired. You are logged out. Please log in to continue"); System.out.println("-login\n-exit\n**********"); } } }
/** * builds a StressTester object using the command line arguments * * @param args * @return * @throws Exception */ public static OStressTester getStressTester(String[] args) throws Exception { final Map<String, String> options = checkOptions(readOptions(args)); final OStressTesterSettings settings = new OStressTesterSettings(); settings.dbName = TEMP_DATABASE_NAME + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); settings.mode = OStressTester.OMode.valueOf(options.get(OPTION_MODE).toUpperCase()); settings.rootPassword = options.get(OPTION_ROOT_PASSWORD); settings.resultOutputFile = options.get(OPTION_OUTPUT_FILE); settings.plocalPath = options.get(OPTION_PLOCAL_PATH); settings.operationsPerTransaction = getNumber(options.get(OPTION_TRANSACTIONS), "transactions"); settings.concurrencyLevel = getNumber(options.get(OPTION_CONCURRENCY), "concurrency"); settings.remoteIp = options.get(OPTION_REMOTE_IP); settings.haMetrics = options.get(OPTION_HA_METRICS) != null ? Boolean.parseBoolean(options.get(OPTION_HA_METRICS)) : false; settings.workloadCfg = options.get(OPTION_WORKLOAD); settings.keepDatabaseAfterTest = options.get(OPTION_KEEP_DATABASE_AFTER_TEST) != null ? Boolean.parseBoolean(options.get(OPTION_KEEP_DATABASE_AFTER_TEST)) : false; settings.remotePort = 2424; settings.checkDatabase = Boolean.parseBoolean(options.get(OPTION_CHECK_DATABASE)); if (settings.plocalPath != null) { if (settings.plocalPath.endsWith(File.separator)) { settings.plocalPath = settings.plocalPath.substring( 0, settings.plocalPath.length() - File.separator.length()); } File plocalFile = new File(settings.plocalPath); if (!plocalFile.exists()) { throw new IllegalArgumentException( String.format(COMMAND_LINE_PARSER_NOT_EXISTING_PLOCAL_PATH, settings.plocalPath)); } if (!plocalFile.canWrite()) { throw new IllegalArgumentException( String.format( COMMAND_LINE_PARSER_NO_WRITE_PERMISSION_PLOCAL_PATH, settings.plocalPath)); } if (!plocalFile.isDirectory()) { throw new IllegalArgumentException( String.format(COMMAND_LINE_PARSER_PLOCAL_PATH_IS_NOT_DIRECTORY, settings.plocalPath)); } } if (settings.resultOutputFile != null) { File outputFile = new File(settings.resultOutputFile); if (outputFile.exists()) { outputFile.delete(); } File parentFile = outputFile.getParentFile(); // if the filename does not contain a path (both relative and absolute) if (parentFile == null) { parentFile = new File("."); } if (!parentFile.exists()) { throw new IllegalArgumentException( String.format( COMMAND_LINE_PARSER_NOT_EXISTING_OUTPUT_DIRECTORY, parentFile.getAbsoluteFile())); } if (!parentFile.canWrite()) { throw new IllegalArgumentException( String.format( COMMAND_LINE_PARSER_NO_WRITE_PERMISSION_OUTPUT_FILE, parentFile.getAbsoluteFile())); } } if (options.get(OPTION_REMOTE_PORT) != null) { settings.remotePort = getNumber(options.get(OPTION_REMOTE_PORT), "remotePort"); if (settings.remotePort > 65535) { throw new IllegalArgumentException( String.format(COMMAND_LINE_PARSER_INVALID_REMOTE_PORT_NUMBER, settings.remotePort)); } } if (settings.mode == OStressTester.OMode.DISTRIBUTED) { throw new IllegalArgumentException( String.format("OMode [%s] not yet supported.", settings.mode)); } if (settings.mode == OStressTester.OMode.REMOTE && settings.remoteIp == null) { throw new IllegalArgumentException(COMMAND_LINE_PARSER_MISSING_REMOTE_IP); } if (settings.rootPassword == null && settings.mode == OStressTester.OMode.REMOTE) { Console console = System.console(); if (console != null) { settings.rootPassword = String.valueOf( console.readPassword( String.format( CONSOLE_REMOTE_PASSWORD_PROMPT, settings.remoteIp, settings.remotePort))); } else { throw new Exception(ERROR_OPENING_CONSOLE); } } final List<OWorkload> workloads = parseWorkloads(settings.workloadCfg); final ODatabaseIdentifier databaseIdentifier = new ODatabaseIdentifier(settings); return new OStressTester(workloads, databaseIdentifier, settings); }
protected String readPassword(String prompt) { Console console = System.console(); System.out.print(prompt); char[] pw = console.readPassword(); return new String(pw); }
@Override public synchronized void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { final Console console = System.console(); if (console == null) throw new IOException("Console not available"); for (Callback callback : callbacks) { if (callback instanceof PasswordCallback) { final PasswordCallback password = (PasswordCallback) callback; final String prompt = getDefault(password.getPrompt(), "Enter password"); char[] answer = console.readPassword("\u001b[34m%s\u001b[0m: ", prompt); if (answer == null) throw new EOFException(); password.setPassword(answer); } else if (callback instanceof NameCallback) { final NameCallback name = (NameCallback) callback; final String prompt = getDefault(name.getPrompt(), "Enter name"); final String defaultName = name.getDefaultName(); if (defaultName == null) while (true) { final String answer = console.readLine("\u001b[34m%s\u001b[0m: ", prompt); if (answer == null) throw new EOFException(); if (answer.length() == 0) continue; name.setName(answer); break; } else { final String answer = console.readLine( "\u001b[34m%s\u001b[0m [\u001b[36m%s\u001b[0m]: ", prompt, defaultName); if (answer == null) throw new EOFException(); if (answer.length() == 0) name.setName(defaultName); else name.setName(answer); } } else if (callback instanceof TextInputCallback) { final TextInputCallback input = (TextInputCallback) callback; final String prompt = getDefault(input.getPrompt(), "Enter value"); final String defaultText = input.getDefaultText(); if (defaultText == null) while (true) { final String answer = console.readLine("\u001b[34m%s\u001b[0m: ", prompt); if (answer == null) throw new EOFException(); if (answer.length() == 0) continue; input.setText(answer); break; } else { final String answer = console.readLine( "\u001b[34m%s\u001b[0m [\u001b[36m%s\u001b[0m]: ", prompt, defaultText); if (answer == null) throw new EOFException(); if (answer.length() == 0) input.setText(defaultText); else input.setText(answer); } } else if (callback instanceof TextOutputCallback) { final TextOutputCallback output = (TextOutputCallback) callback; final String message = output.getMessage(); switch (output.getMessageType()) { case TextOutputCallback.INFORMATION: console.format("\u001b[32m%s\u001b[0m\n", message); break; case TextOutputCallback.WARNING: console.format("\u001b[33mWARNING: %s\u001b[0m\n", message); break; case TextOutputCallback.ERROR: console.format("\u001b[31mERROR: %s\u001b[0m\n", message); break; default: console.format("\u001b[35m??? [%d]: %s\u001b[0m\n", output.getMessageType(), message); break; } } else { throw new UnsupportedCallbackException(callback, "Callback type not supported"); } } }
public static String promptForPassword(String prompt) throws IOException { Console console = System.console(); char[] cbuf = console.readPassword("%s", prompt); return new String(cbuf); }