List of usage examples for java.lang System in
InputStream in
To view the source code for java.lang System in.
Click Source Link
From source file:com.canyapan.randompasswordgenerator.cli.Main.java
public static void main(String[] args) { Options options = new Options(); options.addOption("h", false, "prints help"); options.addOption("def", false, "generates 8 character password with default options"); options.addOption("p", true, "password length (default 8)"); options.addOption("l", false, "include lower case characters"); options.addOption("u", false, "include upper case characters"); options.addOption("d", false, "include digits"); options.addOption("s", false, "include symbols"); options.addOption("lc", true, "minimum lower case character count (default 0)"); options.addOption("uc", true, "minimum upper case character count (default 0)"); options.addOption("dc", true, "minimum digit count (default 0)"); options.addOption("sc", true, "minimum symbol count (default 0)"); options.addOption("a", false, "avoid ambiguous characters"); options.addOption("f", false, "force every character type"); options.addOption("c", false, "continuous password generation"); CommandLineParser parser = new DefaultParser(); CommandLine cmd = null;// w w w . j av a2s . c o m boolean printHelp = false; try { cmd = parser.parse(options, args); } catch (ParseException e) { printHelp = true; } if (printHelp || args.length == 0 || cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( "java -jar RandomPasswordGenerator.jar [-p <arg>] [-l] [-u] [-s] [-d] [-dc <arg>] [-a] [-f]", options); return; } RandomPasswordGenerator rpg = new RandomPasswordGenerator(); if (cmd.hasOption("def")) { rpg.withDefault().withPasswordLength(Integer.parseInt(cmd.getOptionValue("p", "8"))); } else { rpg.withPasswordLength(Integer.parseInt(cmd.getOptionValue("p", "8"))) .withLowerCaseCharacters(cmd.hasOption("l")).withUpperCaseCharacters(cmd.hasOption("u")) .withDigits(cmd.hasOption("d")).withSymbols(cmd.hasOption("s")) .withAvoidAmbiguousCharacters(cmd.hasOption("a")) .withForceEveryCharacterType(cmd.hasOption("f")); if (cmd.hasOption("lc")) { rpg.withMinLowerCaseCharacterCount(Integer.parseInt(cmd.getOptionValue("lc", "0"))); } if (cmd.hasOption("uc")) { rpg.withMinUpperCaseCharacterCount(Integer.parseInt(cmd.getOptionValue("uc", "0"))); } if (cmd.hasOption("dc")) { rpg.withMinDigitCount(Integer.parseInt(cmd.getOptionValue("dc", "0"))); } if (cmd.hasOption("sc")) { rpg.withMinSymbolCount(Integer.parseInt(cmd.getOptionValue("sc", "0"))); } } Scanner scanner = new Scanner(System.in); try { do { final String password = rpg.generate(); final PasswordMeter.Result result = PasswordMeter.check(password); System.out.printf("%s%nScore: %s%%%nComplexity: %s%n%n", password, result.getScore(), result.getComplexity()); if (cmd.hasOption("c")) { System.out.print("Another? y/N: "); } } while (cmd.hasOption("c") && scanner.nextLine().matches("^(?i:y(?:es)?)$")); } catch (RandomPasswordGeneratorException e) { System.err.println(e.getMessage()); } catch (PasswordMeterException e) { System.err.println(e.getMessage()); } }
From source file:ch.swisscom.mid.verifier.MobileIdCmsVerifier.java
public static void main(String[] args) { if (args == null || args.length < 1) { System.out.println("Usage: ch.swisscom.mid.verifier.MobileIdCmsVerifier [OPTIONS]"); System.out.println();//from w w w .ja v a2s . c o m System.out.println("Options:"); System.out.println( " -cms=VALUE or -stdin - base64 encoded CMS/PKCS7 signature string, either as VALUE or via standard input"); System.out.println( " -jks=VALUE - optional path to truststore file (default is 'jks/truststore.jks')"); System.out.println(" -jkspwd=VALUE - optional truststore password (default is 'secret')"); System.out.println(); System.out.println("Example:"); System.out.println(" java ch.swisscom.mid.verifier.MobileIdCmsVerifier -cms=MIII..."); System.out.println(" echo -n MIII... | java ch.swisscom.mid.verifier.MobileIdCmsVerifier -stdin"); System.exit(1); } try { MobileIdCmsVerifier verifier = null; String jks = "jks/truststore.jks"; String jkspwd = "secret"; String param; for (int i = 0; i < args.length; i++) { param = args[i].toLowerCase(); if (param.contains("-jks=")) { jks = args[i].substring(args[i].indexOf("=") + 1).trim(); } else if (param.contains("-jkspwd=")) { jkspwd = args[i].substring(args[i].indexOf("=") + 1).trim(); } else if (param.contains("-cms=")) { verifier = new MobileIdCmsVerifier(args[i].substring(args[i].indexOf("=") + 1).trim()); } else if (param.contains("-stdin")) { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String stdin; if ((stdin = in.readLine()) != null && stdin.length() != 0) verifier = new MobileIdCmsVerifier(stdin.trim()); } } KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(new FileInputStream(jks), jkspwd.toCharArray()); // If you are behind a Proxy.. // System.setProperty("proxyHost", "10.185.32.54"); // System.setProperty("proxyPort", "8079"); // or set it via VM arguments: -DproxySet=true -DproxyHost=10.185.32.54 -DproxyPort=8079 // Print Issuer/SubjectDN/SerialNumber of all x509 certificates that can be found in the CMSSignedData verifier.printAllX509Certificates(); // Print Signer's X509 Certificate Details System.out.println("X509 SignerCert SerialNumber: " + verifier.getX509SerialNumber()); System.out.println("X509 SignerCert Issuer: " + verifier.getX509IssuerDN()); System.out.println("X509 SignerCert Subject DN: " + verifier.getX509SubjectDN()); System.out.println("X509 SignerCert Validity Not Before: " + verifier.getX509NotBefore()); System.out.println("X509 SignerCert Validity Not After: " + verifier.getX509NotAfter()); System.out.println("X509 SignerCert Validity currently valid: " + verifier.isCertCurrentlyValid()); System.out.println("User's unique Mobile ID SerialNumber: " + verifier.getMIDSerialNumber()); // Print signed content (should be equal to the DTBS Message of the Signature Request) System.out.println("Signed Data: " + verifier.getSignedData()); // Verify the signature on the SignerInformation object System.out.println("Signature Valid: " + verifier.isVerified()); // Validate certificate path against trust anchor incl. OCSP revocation check System.out.println("X509 SignerCert Valid (Path+OCSP): " + verifier.isCertValid(keyStore)); } catch (Exception e) { e.printStackTrace(); } }
From source file:de.topobyte.osm4j.pbf.executables.EntitySplit.java
public static void main(String[] args) throws IOException { // @formatter:off Options options = new Options(); OptionHelper.add(options, OPTION_INPUT, true, false, "input file"); OptionHelper.add(options, OPTION_OUTPUT_NODES, true, false, "the file to write nodes to"); OptionHelper.add(options, OPTION_OUTPUT_WAYS, true, false, "the file to write ways to"); OptionHelper.add(options, OPTION_OUTPUT_RELATIONS, true, false, "the file to write relations to"); // @formatter:on CommandLine line = null;//w w w .j av a2 s . c o m try { line = new GnuParser().parse(options, args); } catch (ParseException e) { System.out.println("unable to parse command line: " + e.getMessage()); new HelpFormatter().printHelp(HELP_MESSAGE, options); System.exit(1); } if (line == null) { return; } InputStream in = null; if (line.hasOption(OPTION_INPUT)) { String inputPath = line.getOptionValue(OPTION_INPUT); File file = new File(inputPath); FileInputStream fis = new FileInputStream(file); in = new BufferedInputStream(fis); } else { in = new BufferedInputStream(System.in); } OutputStream outNodes = null, outWays = null, outRelations = null; if (line.hasOption(OPTION_OUTPUT_NODES)) { String path = line.getOptionValue(OPTION_OUTPUT_NODES); FileOutputStream fos = new FileOutputStream(path); outNodes = new BufferedOutputStream(fos); } if (line.hasOption(OPTION_OUTPUT_WAYS)) { String path = line.getOptionValue(OPTION_OUTPUT_WAYS); FileOutputStream fos = new FileOutputStream(path); outWays = new BufferedOutputStream(fos); } if (line.hasOption(OPTION_OUTPUT_RELATIONS)) { String path = line.getOptionValue(OPTION_OUTPUT_RELATIONS); FileOutputStream fos = new FileOutputStream(path); outRelations = new BufferedOutputStream(fos); } if (outNodes == null && outWays == null && outRelations == null) { System.out.println("You should specify an output for at least one entity"); System.exit(1); } EntitySplit task = new EntitySplit(in, outNodes, outWays, outRelations); task.execute(); }
From source file:cli.Main.java
public static void main(String[] args) { // Workaround for BKS truststore Security.insertProviderAt(new org.spongycastle.jce.provider.BouncyCastleProvider(), 1); Namespace ns = parseArgs(args); if (ns == null) { System.exit(1);/*from ww w . java2 s . c om*/ } final String username = ns.getString("username"); final Manager m = new Manager(username); if (m.userExists()) { try { m.load(); } catch (Exception e) { System.err.println("Error loading state file \"" + m.getFileName() + "\": " + e.getMessage()); System.exit(2); } } switch (ns.getString("command")) { case "register": if (!m.userHasKeys()) { m.createNewIdentity(); } try { m.register(ns.getBoolean("voice")); } catch (IOException e) { System.err.println("Request verify error: " + e.getMessage()); System.exit(3); } break; case "verify": if (!m.userHasKeys()) { System.err.println("User has no keys, first call register."); System.exit(1); } if (m.isRegistered()) { System.err.println("User registration is already verified"); System.exit(1); } try { m.verifyAccount(ns.getString("verificationCode")); } catch (IOException e) { System.err.println("Verify error: " + e.getMessage()); System.exit(3); } break; case "send": if (!m.isRegistered()) { System.err.println("User is not registered."); System.exit(1); } String messageText = ns.getString("message"); if (messageText == null) { try { messageText = IOUtils.toString(System.in); } catch (IOException e) { System.err.println("Failed to read message from stdin: " + e.getMessage()); System.exit(1); } } final List<String> attachments = ns.getList("attachment"); List<TextSecureAttachment> textSecureAttachments = null; if (attachments != null) { textSecureAttachments = new ArrayList<>(attachments.size()); for (String attachment : attachments) { try { File attachmentFile = new File(attachment); InputStream attachmentStream = new FileInputStream(attachmentFile); final long attachmentSize = attachmentFile.length(); String mime = Files.probeContentType(Paths.get(attachment)); textSecureAttachments .add(new TextSecureAttachmentStream(attachmentStream, mime, attachmentSize, null)); } catch (IOException e) { System.err.println("Failed to add attachment \"" + attachment + "\": " + e.getMessage()); System.err.println("Aborting sending."); System.exit(1); } } } List<TextSecureAddress> recipients = new ArrayList<>(ns.<String>getList("recipient").size()); for (String recipient : ns.<String>getList("recipient")) { try { recipients.add(m.getPushAddress(recipient)); } catch (InvalidNumberException e) { System.err.println("Failed to add recipient \"" + recipient + "\": " + e.getMessage()); System.err.println("Aborting sending."); System.exit(1); } } sendMessage(m, messageText, textSecureAttachments, recipients); break; case "receive": if (!m.isRegistered()) { System.err.println("User is not registered."); System.exit(1); } try { m.receiveMessages(5, true, new ReceiveMessageHandler(m)); } catch (IOException e) { System.err.println("Error while receiving message: " + e.getMessage()); System.exit(3); } catch (AssertionError e) { System.err.println("Failed to receive message (Assertion): " + e.getMessage()); System.err.println(e.getStackTrace()); System.err.println( "If you use an Oracle JRE please check if you have unlimited strength crypto enabled, see README"); System.exit(1); } break; } m.save(); System.exit(0); }
From source file:Main.java
/** Simple command-line based search demo. */ public static void main(String[] args) throws Exception { String usage = "Usage:\tjava SearchFiles [-index dir] [-field f] [-repeat n] [-queries file] [-query string] [-raw] [-paging hitsPerPage]\n\nSee http://lucene.apache.org/core/4_1_0/demo/ for details."; if (args.length > 0 && ("-h".equals(args[0]) || "-help".equals(args[0]))) { System.out.println(usage); System.exit(0);//from w w w .j ava2 s. c o m } String index = "index"; String field = "contents"; String queries = null; int repeat = 0; boolean raw = false; String queryString = null; int hitsPerPage = 10; for (int i = 0; i < args.length; i++) { if ("-index".equals(args[i])) { index = args[i + 1]; i++; } else if ("-field".equals(args[i])) { field = args[i + 1]; i++; } else if ("-queries".equals(args[i])) { queries = args[i + 1]; i++; } else if ("-query".equals(args[i])) { queryString = args[i + 1]; i++; } else if ("-repeat".equals(args[i])) { repeat = Integer.parseInt(args[i + 1]); i++; } else if ("-raw".equals(args[i])) { raw = true; } else if ("-paging".equals(args[i])) { hitsPerPage = Integer.parseInt(args[i + 1]); if (hitsPerPage <= 0) { System.err.println("There must be at least 1 hit per page."); System.exit(1); } i++; } } IndexReader reader = DirectoryReader.open(FSDirectory.open(new File(index))); IndexSearcher searcher = new IndexSearcher(reader); // :Post-Release-Update-Version.LUCENE_XY: Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_4_10_0); BufferedReader in = null; if (queries != null) { in = new BufferedReader(new InputStreamReader(new FileInputStream(queries), StandardCharsets.UTF_8)); } else { in = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8)); } // :Post-Release-Update-Version.LUCENE_XY: QueryParser parser = new QueryParser(Version.LUCENE_4_10_0, field, analyzer); while (true) { if (queries == null && queryString == null) { // prompt the user System.out.println("Enter query: "); } String line = queryString != null ? queryString : in.readLine(); if (line == null || line.length() == -1) { break; } line = line.trim(); if (line.length() == 0) { break; } Query query = parser.parse(line); System.out.println("Searching for: " + query.toString(field)); if (repeat > 0) { // repeat & time as benchmark Date start = new Date(); for (int i = 0; i < repeat; i++) { searcher.search(query, null, 100); } Date end = new Date(); System.out.println("Time: " + (end.getTime() - start.getTime()) + "ms"); } doPagingSearch(in, searcher, query, hitsPerPage, raw, queries == null && queryString == null); if (queryString != null) { break; } } reader.close(); }
From source file:com.mindquarry.jcr.jackrabbit.JackrabbitRMIRepositoryStandalone.java
/** * The main entry point of the application. * //from www . java 2s. co m * @param args the command line arguments */ public static void main(String[] args) throws Exception { JackrabbitRMIRepositoryStandalone repo = new JackrabbitRMIRepositoryStandalone(); CommandLine line = repo.parse(args); if (line != null) { repo.start(line); System.out.println("Please press <enter> to shutdown the server."); System.in.read(); repo.stop(); } }
From source file:com.left8.evs.evs.EvS.java
/** * Main method that provides a simple console input interface for the user, * if she wishes to execute the tool as a .jar executable. * @param args A list of arguments.//from www. j a va2 s. c o m * @throws org.apache.commons.cli.ParseException ParseExcetion */ public static void main(String[] args) throws ParseException { Config config = null; try { config = new Config(); } catch (IOException ex) { Utilities.printMessageln("Configuration file 'config.properties' " + "not in classpath!"); Logger.getLogger(EvS.class.getName()).log(Level.SEVERE, null, ex); System.exit(1); } if (args.length != 0) { //If the user supplied arguments Console console = new Console(args, config); //Read the console showMongoLogging = console.showMongoLogging(); showInlineInfo = console.showInlineInfo(); hasExtCommands = console.hasExternalCommands(); choice = console.getChoiceValue(); } if (!showMongoLogging) { //Stop reporting logging information Logger mongoLogger = Logger.getLogger("org.mongodb.driver"); mongoLogger.setLevel(Level.SEVERE); } System.out.println("\n----EvS----"); if (!hasExtCommands) { System.out.println("Select one of the following options"); System.out.println("1. Run Offline Peak Finding experiments."); System.out.println("2. Run EDCoW experiments."); System.out.println("3. Run each of the above methods without " + "the sentiment annotations."); System.out.println("Any other key to exit."); System.out.println(""); System.out.print("Your choice: "); Scanner keyboard = new Scanner(System.in); choice = keyboard.nextInt(); } switch (choice) { case 1: { //Offline Peak Finding int window = 10; double alpha = 0.85; int taph = 1; int pi = 5; Dataset ds = new Dataset(config); PeakFindingCorpus corpus = new PeakFindingCorpus(config, ds.getTweetList(), ds.getSWH()); corpus.createCorpus(window); List<BinPair<String, Integer>> bins = BinsCreator.createBins(corpus, config, window); PeakFindingSentimentCorpus sCorpus = new PeakFindingSentimentCorpus(corpus); SentimentPeakFindingExperimenter exper = new SentimentPeakFindingExperimenter(sCorpus, bins, alpha, taph, pi, window, config); //Experiment with Taph List<String> lines = exper.experimentUsingTaph(1, 10, 1, 0, showInlineInfo); exper.exportToFile("stanford.txt", lines); lines = exper.experimentUsingTaph(1, 10, 1, 1, showInlineInfo); exper.exportToFile("naive_bayes.txt", lines); lines = exper.experimentUsingTaph(1, 10, 1, 2, showInlineInfo); exper.exportToFile("bayesian_net.txt", lines); //Experiment with Alpha lines = exper.experimentUsingAlpha(0.85, 0.99, 0.01, 0, showInlineInfo); exper.exportToFile("stanford.txt", lines); lines = exper.experimentUsingAlpha(0.85, 0.99, 0.01, 1, showInlineInfo); exper.exportToFile("naive_bayes.txt", lines); lines = exper.experimentUsingAlpha(0.85, 0.99, 0.01, 2, showInlineInfo); exper.exportToFile("bayesian_net.txt", lines); break; } case 2: { //EDCoW Dataset ds = new Dataset(config); SentimentEDCoWCorpus corpus = new SentimentEDCoWCorpus(config, ds.getTweetList(), ds.getSWH(), 10); corpus.getEDCoWCorpus().createCorpus(); corpus.getEDCoWCorpus().setDocTermFreqIdList(); int delta = 5, delta2 = 11, gamma = 6; double minTermSupport = 0.001, maxTermSupport = 0.01; SentimentEDCoWExperimenter exper = new SentimentEDCoWExperimenter(corpus, delta, delta2, gamma, minTermSupport, maxTermSupport, choice, choice, config); //Experiment with delta List<String> lines = exper.experimentUsingDelta(1, 20, 1, 0, showInlineInfo); exper.exportToFile("stanford.txt", lines); lines = exper.experimentUsingDelta(1, 20, 1, 1, showInlineInfo); exper.exportToFile("naive_bayes.txt", lines); lines = exper.experimentUsingDelta(1, 20, 1, 2, showInlineInfo); exper.exportToFile("bayesian_net.txt", lines); //Experiment with gamma lines = exper.experimentUsingGamma(6, 10, 1, 0, showInlineInfo); exper.exportToFile("stanford.txt", lines); lines = exper.experimentUsingGamma(6, 10, 1, 1, showInlineInfo); exper.exportToFile("naive_bayes.txt", lines); lines = exper.experimentUsingGamma(6, 10, 1, 2, showInlineInfo); exper.exportToFile("bayesian_net.txt", lines); break; } case 3: { EDMethodPicker.selectEDMethod(config, showInlineInfo, 0); break; } case 4: { //Directly run OPF EDMethodPicker.selectEDMethod(config, showInlineInfo, 1); break; } case 5: { //Directly run EDCoW EDMethodPicker.selectEDMethod(config, showInlineInfo, 2); break; } default: { System.out.println("Exiting now..."); System.exit(0); } } }
From source file:FileSplitter.java
public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.print("Split? [true/false]: "); boolean split = Boolean.parseBoolean(scan.next()); if (split) {//from www. j ava2s.co m File file = new File("T:/Java/com/power/nb/visual/dist/visual.zip"); FileSplitter splitter = new FileSplitter(file); System.out.println("splitter.split(3): " + splitter.split(3)); } else { File file = new File("T:/Java/com/power/nb/visual/dist/visual.zip.part.0"); FileSplitter splitter = new FileSplitter(file); System.out.println("splitter.unsplit(): " + splitter.unsplit()); } }
From source file:io.apiman.tools.jdbc.ApimanJdbcServer.java
public static void main(String[] args) { try {// www . j a v a 2 s .c o m File dataDir = new File("target/h2"); String url = "jdbc:h2:tcp://localhost:9092/apiman"; if (dataDir.exists()) { FileUtils.deleteDirectory(dataDir); } dataDir.mkdirs(); Server.createTcpServer("-tcpPassword", "sa", "-baseDir", dataDir.getAbsolutePath(), "-tcpPort", "9092", "-tcpAllowOthers").start(); Class.forName("org.h2.Driver"); try (Connection connection = DriverManager.getConnection(url, "sa", "")) { System.out.println("Connection Established: " + connection.getMetaData().getDatabaseProductName() + "/" + connection.getCatalog()); executeUpdate(connection, "CREATE TABLE users ( username varchar(255) NOT NULL, password varchar(255) NOT NULL, PRIMARY KEY (username))"); executeUpdate(connection, "INSERT INTO users (username, password) VALUES ('bwayne', 'ae2efd698aefdf366736a4eda1bc5241f9fbfec7')"); executeUpdate(connection, "INSERT INTO users (username, password) VALUES ('ckent', 'ea59f7ca52a2087c99374caba0ff29be1b2dcdbf')"); executeUpdate(connection, "INSERT INTO users (username, password) VALUES ('ballen', 'ea59f7ca52a2087c99374caba0ff29be1b2dcdbf')"); executeUpdate(connection, "CREATE TABLE roles (rolename varchar(255) NOT NULL, username varchar(255) NOT NULL)"); executeUpdate(connection, "INSERT INTO roles (rolename, username) VALUES ('user', 'bwayne')"); executeUpdate(connection, "INSERT INTO roles (rolename, username) VALUES ('admin', 'bwayne')"); executeUpdate(connection, "INSERT INTO roles (rolename, username) VALUES ('ckent', 'user')"); executeUpdate(connection, "INSERT INTO roles (rolename, username) VALUES ('ballen', 'user')"); } System.out.println("======================================================"); System.out.println("JDBC (H2) server started successfully."); System.out.println(""); System.out.println(" Data: " + dataDir.getAbsolutePath()); System.out.println(" JDBC URL: " + url); System.out.println(" JDBC User: sa"); System.out.println(" JDBC Password: "); System.out.println( " Authentication Query: SELECT * FROM users u WHERE u.username = ? AND u.password = ?"); System.out.println(" Authorization Query: SELECT r.rolename FROM roles r WHERE r.username = ?"); System.out.println("======================================================"); System.out.println(""); System.out.println(""); System.out.println("Press Enter to stop the JDBC server."); new BufferedReader(new InputStreamReader(System.in)).readLine(); System.out.println("Shutting down the JDBC server..."); Server.shutdownTcpServer("tcp://localhost:9092", "", true, true); System.out.println("Done!"); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.bitsofproof.example.Simple.java
public static void main(String[] args) { Security.addProvider(new BouncyCastleProvider()); final CommandLineParser parser = new GnuParser(); final Options gnuOptions = new Options(); gnuOptions.addOption("h", "help", false, "I can't help you yet"); gnuOptions.addOption("s", "server", true, "Server URL"); gnuOptions.addOption("u", "user", true, "User"); gnuOptions.addOption("p", "password", true, "Password"); System.out.println("BOP Bitcoin Server Simple Client 3.5.0 (c) 2013-2014 bits of proof zrt."); CommandLine cl = null;/* ww w . j a va 2 s. c o m*/ String url = null; String user = null; String password = null; try { cl = parser.parse(gnuOptions, args); url = cl.getOptionValue('s'); user = cl.getOptionValue('u'); password = cl.getOptionValue('p'); } catch (org.apache.commons.cli.ParseException e) { e.printStackTrace(); System.exit(1); } if (url == null || user == null || password == null) { System.err.println("Need -s server -u user -p password"); System.exit(1); } BCSAPI api = getServer(url, user, password); try { BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); long start = System.currentTimeMillis(); api.ping(start); System.out.println("Server round trip " + (System.currentTimeMillis() - start) + "ms"); api.addAlertListener(new AlertListener() { @Override public void alert(String s, int severity) { System.err.println("ALERT: " + s); } }); System.out.println("Talking to " + (api.isProduction() ? "PRODUCTION" : "test") + " server"); ConfirmationManager confirmationManager = new ConfirmationManager(); confirmationManager.init(api, 144); System.out.printf("Please enter wallet name: "); String wallet = input.readLine(); SimpleFileWallet w = new SimpleFileWallet(wallet + ".wallet"); TransactionFactory am = null; if (!w.exists()) { System.out.printf("Enter passphrase: "); String passphrase = input.readLine(); System.out.printf("Enter master (empty for new): "); String master = input.readLine(); if (master.equals("")) { w.init(passphrase); w.unlock(passphrase); System.out.printf("First account: "); String account = input.readLine(); am = w.createAccountManager(account); w.lock(); w.persist(); } else { StringTokenizer tokenizer = new StringTokenizer(master, "@"); String key = tokenizer.nextToken(); long since = 0; if (tokenizer.hasMoreElements()) { since = Long.parseLong(tokenizer.nextToken()) * 1000; } w.init(passphrase, ExtendedKey.parse(key), true, since); w.unlock(passphrase); System.out.printf("First account: "); String account = input.readLine(); am = w.createAccountManager(account); w.lock(); w.persist(); w.sync(api); } } else { w = SimpleFileWallet.read(wallet + ".wallet"); w.sync(api); List<String> names = w.getAccountNames(); System.out.println("Accounts:"); System.out.println("---------"); String first = null; for (String name : names) { System.out.println(name); if (first == null) { first = name; } } System.out.println("---------"); am = w.getAccountManager(first); System.out.println("Using account " + first); } confirmationManager.addAccount(am); api.registerTransactionListener(am); while (true) { printMenu(); String answer = input.readLine(); System.out.printf("\n"); if (answer.equals("1")) { System.out.printf("The balance is: " + printBit(am.getBalance()) + "\n"); System.out.printf(" confirmed: " + printBit(am.getConfirmed()) + "\n"); System.out.printf(" receiveing: " + printBit(am.getReceiving()) + "\n"); System.out.printf(" change: " + printBit(am.getChange()) + "\n"); System.out.printf("( sending: " + printBit(am.getSending()) + ")\n"); } else if (answer.equals("2")) { for (Address a : am.getAddresses()) { System.out.printf(a + "\n"); } } else if (answer.equals("3")) { ExtendedKeyAccountManager im = (ExtendedKeyAccountManager) am; System.out.printf( im.getMaster().serialize(api.isProduction()) + "@" + im.getCreated() / 1000 + "\n"); } else if (answer.equals("4")) { System.out.printf("Enter passphrase: "); String passphrase = input.readLine(); w.unlock(passphrase); ExtendedKeyAccountManager im = (ExtendedKeyAccountManager) am; System.out.printf( im.getMaster().serialize(api.isProduction()) + "@" + im.getCreated() / 1000 + "\n"); w.lock(); } else if (answer.equals("5")) { System.out.printf("Enter passphrase: "); String passphrase = input.readLine(); w.unlock(passphrase); System.out.printf("Number of recipients"); Integer nr = Integer.valueOf(input.readLine()); Transaction spend; if (nr.intValue() == 1) { System.out.printf("Receiver address: "); String address = input.readLine(); System.out.printf("amount (Bit): "); long amount = parseBit(input.readLine()); spend = am.pay(Address.fromSatoshiStyle(address), amount); System.out.println("About to send " + printBit(amount) + " to " + address); } else { List<Address> addresses = new ArrayList<>(); List<Long> amounts = new ArrayList<>(); long total = 0; for (int i = 0; i < nr; ++i) { System.out.printf("Receiver address: "); String address = input.readLine(); addresses.add(Address.fromSatoshiStyle(address)); System.out.printf("amount (Bit): "); long amount = parseBit(input.readLine()); amounts.add(amount); total += amount; } spend = am.pay(addresses, amounts); System.out.println("About to send " + printBit(total)); } System.out.println("inputs"); for (TransactionInput in : spend.getInputs()) { System.out.println(in.getSourceHash() + " " + in.getIx()); } System.out.println("outputs"); for (TransactionOutput out : spend.getOutputs()) { System.out.println(out.getOutputAddress() + " " + printBit(out.getValue())); } w.lock(); System.out.printf("Type yes to go: "); if (input.readLine().equals("yes")) { api.sendTransaction(spend); System.out.printf("Sent transaction: " + spend.getHash()); } else { System.out.printf("Nothing happened."); } } else if (answer.equals("6")) { System.out.printf("Address: "); Set<Address> match = new HashSet<Address>(); match.add(Address.fromSatoshiStyle(input.readLine())); api.scanTransactionsForAddresses(match, 0, new TransactionListener() { @Override public boolean process(Transaction t) { System.out.printf("Found transaction: " + t.getHash() + "\n"); return true; } }); } else if (answer.equals("7")) { System.out.printf("Public key: "); ExtendedKey ek = ExtendedKey.parse(input.readLine()); api.scanTransactions(ek, 0, 10, 0, new TransactionListener() { @Override public boolean process(Transaction t) { System.out.printf("Found transaction: " + t.getHash() + "\n"); return true; } }); } else if (answer.equals("a")) { System.out.printf("Enter account name: "); String account = input.readLine(); am = w.getAccountManager(account); api.registerTransactionListener(am); confirmationManager.addAccount(am); } else if (answer.equals("c")) { System.out.printf("Enter account name: "); String account = input.readLine(); System.out.printf("Enter passphrase: "); String passphrase = input.readLine(); w.unlock(passphrase); am = w.createAccountManager(account); System.out.println("using account: " + account); w.lock(); w.persist(); api.registerTransactionListener(am); confirmationManager.addAccount(am); } else if (answer.equals("m")) { System.out.printf("Enter passphrase: "); String passphrase = input.readLine(); w.unlock(passphrase); System.out.println(w.getMaster().serialize(api.isProduction())); System.out.println(w.getMaster().getReadOnly().serialize(true)); w.lock(); } else if (answer.equals("s")) { System.out.printf("Enter private key: "); String key = input.readLine(); ECKeyPair k = ECKeyPair.parseWIF(key); KeyListAccountManager alm = new KeyListAccountManager(); alm.addKey(k); alm.syncHistory(api); Address a = am.getNextReceiverAddress(); Transaction t = alm.pay(a, alm.getBalance(), PaymentOptions.receiverPaysFee); System.out.println("About to sweep " + printBit(alm.getBalance()) + " to " + a); System.out.println("inputs"); for (TransactionInput in : t.getInputs()) { System.out.println(in.getSourceHash() + " " + in.getIx()); } System.out.println("outputs"); for (TransactionOutput out : t.getOutputs()) { System.out.println(out.getOutputAddress() + " " + printBit(out.getValue())); } System.out.printf("Type yes to go: "); if (input.readLine().equals("yes")) { api.sendTransaction(t); System.out.printf("Sent transaction: " + t.getHash()); } else { System.out.printf("Nothing happened."); } } else { System.exit(0); } } } catch (Exception e) { System.err.println("Something went wrong"); e.printStackTrace(); System.exit(1); } }