Example usage for com.google.common.io Resources toString

List of usage examples for com.google.common.io Resources toString

Introduction

In this page you can find the example usage for com.google.common.io Resources toString.

Prototype

public static String toString(URL url, Charset charset) throws IOException 

Source Link

Document

Reads all characters from a URL into a String , using the given character set.

Usage

From source file:org.apache.s4.tools.CreateApp.java

public static void main(String[] args) {

    final CreateAppArgs appArgs = new CreateAppArgs();
    Tools.parseArgs(appArgs, args);//from  w  w  w  . j av a2  s  .  com

    if (new File(appArgs.getAppDir() + "/" + appArgs.appName.get(0)).exists()) {
        System.err.println("There is already a directory called " + appArgs.appName.get(0) + " in the "
                + appArgs.getAppDir()
                + " directory. Please specify another name for your project or specify another parent directory");
        System.exit(1);
    }
    // create project structure
    try {
        createDir(appArgs, "/src/main/java");
        createDir(appArgs, "/src/main/resources");
        createDir(appArgs, "/src/main/java/hello");

        // copy gradlew script (redirecting to s4 gradlew)
        File gradlewTempFile = File.createTempFile("gradlew", "tmp");
        gradlewTempFile.deleteOnExit();
        Files.copy(Resources.newInputStreamSupplier(Resources.getResource("templates/gradlew")),
                gradlewTempFile);
        String gradlewScriptContent = Files.readLines(gradlewTempFile, Charsets.UTF_8,
                new PathsReplacer(appArgs));
        Files.write(gradlewScriptContent, gradlewTempFile, Charsets.UTF_8);
        Files.copy(gradlewTempFile, new File(appArgs.getAppDir() + "/gradlew"));
        new File(appArgs.getAppDir() + "/gradlew").setExecutable(true);

        // copy build file contents
        String buildFileContents = Resources.toString(Resources.getResource("templates/build.gradle"),
                Charsets.UTF_8);
        buildFileContents = buildFileContents.replace("<s4_install_dir>",
                "'" + new File(appArgs.s4ScriptPath).getParent() + "'");
        Files.write(buildFileContents, new File(appArgs.getAppDir() + "/build.gradle"), Charsets.UTF_8);

        // copy lib
        FileUtils.copyDirectory(new File(new File(appArgs.s4ScriptPath).getParentFile(), "lib"),
                new File(appArgs.getAppDir() + "/lib"));

        // update app settings
        String settingsFileContents = Resources.toString(Resources.getResource("templates/settings.gradle"),
                Charsets.UTF_8);
        settingsFileContents = settingsFileContents.replaceFirst("rootProject.name=<project-name>",
                "rootProject.name=\"" + appArgs.appName.get(0) + "\"");
        Files.write(settingsFileContents, new File(appArgs.getAppDir() + "/settings.gradle"), Charsets.UTF_8);
        // copy hello app files
        Files.copy(Resources.newInputStreamSupplier(Resources.getResource("templates/HelloPE.java.txt")),
                new File(appArgs.getAppDir() + "/src/main/java/hello/HelloPE.java"));
        Files.copy(Resources.newInputStreamSupplier(Resources.getResource("templates/HelloApp.java.txt")),
                new File(appArgs.getAppDir() + "/src/main/java/hello/HelloApp.java"));
        // copy hello app adapter
        Files.copy(
                Resources.newInputStreamSupplier(Resources.getResource("templates/HelloInputAdapter.java.txt")),
                new File(appArgs.getAppDir() + "/src/main/java/hello/HelloInputAdapter.java"));

        File s4TmpFile = File.createTempFile("s4Script", "template");
        s4TmpFile.deleteOnExit();
        Files.copy(Resources.newInputStreamSupplier(Resources.getResource("templates/s4")), s4TmpFile);

        // create s4
        String preparedS4Script = Files.readLines(s4TmpFile, Charsets.UTF_8, new PathsReplacer(appArgs));

        File s4Script = new File(appArgs.getAppDir() + "/s4");
        Files.write(preparedS4Script, s4Script, Charsets.UTF_8);
        s4Script.setExecutable(true);

        File readmeTmpFile = File.createTempFile("newApp", "README");
        readmeTmpFile.deleteOnExit();
        Files.copy(Resources.newInputStreamSupplier(Resources.getResource("templates/newApp.README")),
                readmeTmpFile);
        // display contents from readme
        Files.readLines(readmeTmpFile, Charsets.UTF_8, new LineProcessor<Boolean>() {

            @Override
            public boolean processLine(String line) throws IOException {
                if (!line.startsWith("#")) {
                    System.out.println(line.replace("<appDir>", appArgs.getAppDir()));
                }
                return true;
            }

            @Override
            public Boolean getResult() {
                return true;
            }

        });
    } catch (Exception e) {
        logger.error("Could not create project due to [{}]. Please check your configuration.", e.getMessage());
    }
}

From source file:org.smartdeveloperhub.vocabulary.publisher.VocabularyPublisher.java

public static void main(final String... args) throws FileNotFoundException, IOException {
    if (args.length != 1) {
        System.err.printf("Invalid argument number: 1 argument required (%d)%n", args.length);
        System.err.printf("USAGE: %s <path-to-config-file>%n",
                AppAssembler.applicationName(VocabularyPublisher.class));
        System.err.printf(/*from  w w  w. j av a 2 s  .  c  o m*/
                "  <path-to-config-file> : Path Vocabulary Publisher configuration file is available.%n");
        Application.logContext(args);
        System.exit(-1);
    }
    System.out.printf("Vocabulary Publisher%s%n", serviceVersion());
    try {
        final Path configFile = Paths.get(args[0]);
        final PublisherConfig config = ConfigurationFactory.load(
                Resources.toString(configFile.toUri().toURL(), StandardCharsets.UTF_8), PublisherConfig.class);
        System.out.printf("- Base URI: %s%n", config.getBase());
        System.out.printf("- Server..: %s:%s%n", config.getServer().getHost(), config.getServer().getPort());
        System.out.printf("- Source directory: %s%n", config.getRoot().toAbsolutePath());
        setup(config);
    } catch (final InvalidPathException e) {
        System.err.printf("%s is not a valid root path (%s)%n", args[0], e.getMessage());
        System.exit(-2);
    } catch (final IOException e) {
        System.err.printf("Could not explore modules (%s)%n", e.getMessage());
        System.exit(-3);
    } catch (final RuntimeException e) {
        System.err.println("Unexpected publisher failure\n. Full stacktrace follows");
        e.printStackTrace(System.err);
        System.exit(-4);
    }
}

From source file:com.google.sakuracoin.tools.WalletTool.java

public static void main(String[] args) throws Exception {
    OptionParser parser = new OptionParser();
    parser.accepts("help");
    parser.accepts("force");
    parser.accepts("debuglog");
    OptionSpec<String> walletFileName = parser.accepts("wallet").withRequiredArg().defaultsTo("wallet");
    OptionSpec<NetworkEnum> netFlag = parser.accepts("net").withOptionalArg().ofType(NetworkEnum.class)
            .defaultsTo(NetworkEnum.PROD);
    dateFlag = parser.accepts("date").withRequiredArg().ofType(Date.class)
            .withValuesConvertedBy(DateConverter.datePattern("yyyy/MM/dd"));
    OptionSpec<WaitForEnum> waitForFlag = parser.accepts("waitfor").withRequiredArg().ofType(WaitForEnum.class);
    OptionSpec<ValidationMode> modeFlag = parser.accepts("mode").withRequiredArg().ofType(ValidationMode.class)
            .defaultsTo(ValidationMode.SPV);
    OptionSpec<String> chainFlag = parser.accepts("chain").withRequiredArg();
    // For addkey/delkey.
    parser.accepts("pubkey").withRequiredArg();
    parser.accepts("privkey").withRequiredArg();
    parser.accepts("addr").withRequiredArg();
    parser.accepts("peers").withRequiredArg();
    OptionSpec<String> outputFlag = parser.accepts("output").withRequiredArg();
    parser.accepts("value").withRequiredArg();
    parser.accepts("fee").withRequiredArg();
    unixtimeFlag = parser.accepts("unixtime").withRequiredArg().ofType(Integer.class);
    OptionSpec<String> conditionFlag = parser.accepts("condition").withRequiredArg();
    parser.accepts("locktime").withRequiredArg();
    parser.accepts("allow-unconfirmed");
    parser.accepts("offline");
    parser.accepts("ignore-mandatory-extensions");
    OptionSpec<String> passwordFlag = parser.accepts("password").withRequiredArg();
    options = parser.parse(args);//from   ww  w .  j  a  v a 2 s.  c o  m

    final String HELP_TEXT = Resources.toString(WalletTool.class.getResource("wallet-tool-help.txt"),
            Charsets.UTF_8);

    if (args.length == 0 || options.has("help") || options.nonOptionArguments().size() < 1) {
        System.out.println(HELP_TEXT);
        return;
    }

    ActionEnum action;
    try {
        String actionStr = options.nonOptionArguments().get(0);
        actionStr = actionStr.toUpperCase().replace("-", "_");
        action = ActionEnum.valueOf(actionStr);
    } catch (IllegalArgumentException e) {
        System.err.println("Could not understand action name " + options.nonOptionArguments().get(0));
        return;
    }

    if (options.has("debuglog")) {
        BriefLogFormatter.init();
        log.info("Starting up ...");
    } else {
        // Disable logspam unless there is a flag.
        java.util.logging.Logger logger = LogManager.getLogManager().getLogger("");
        logger.setLevel(Level.SEVERE);
    }
    switch (netFlag.value(options)) {
    case PROD:
        params = MainNetParams.get();
        chainFileName = new File("prodnet.chain");
        break;
    case TEST:
        params = TestNet3Params.get();
        chainFileName = new File("testnet.chain");
        break;
    case REGTEST:
        params = RegTestParams.get();
        chainFileName = new File("regtest.chain");
        break;
    default:
        throw new RuntimeException("Unreachable.");
    }
    mode = modeFlag.value(options);

    // Allow the user to override the name of the chain used.
    if (options.has(chainFlag)) {
        chainFileName = new File(chainFlag.value(options));
    }

    if (options.has("condition")) {
        condition = new Condition(conditionFlag.value(options));
    }

    if (options.has(passwordFlag)) {
        password = passwordFlag.value(options);
    }

    walletFile = new File(walletFileName.value(options));
    if (action == ActionEnum.CREATE) {
        createWallet(options, params, walletFile);
        return; // We're done.
    }
    if (!walletFile.exists()) {
        System.err.println("Specified wallet file " + walletFile + " does not exist. Try wallet-tool --wallet="
                + walletFile + " create");
        return;
    }

    if (action == ActionEnum.RAW_DUMP) {
        // Just parse the protobuf and print, then bail out. Don't try and do a real deserialization. This is
        // useful mostly for investigating corrupted wallets.
        FileInputStream stream = new FileInputStream(walletFile);
        try {
            Protos.Wallet proto = WalletProtobufSerializer.parseToProto(stream);
            System.out.println(proto.toString());
            return;
        } finally {
            stream.close();
        }
    }

    try {
        WalletProtobufSerializer loader = new WalletProtobufSerializer();
        if (options.has("ignore-mandatory-extensions"))
            loader.setRequireMandatoryExtensions(false);
        wallet = loader.readWallet(new BufferedInputStream(new FileInputStream(walletFile)));
        if (!wallet.getParams().equals(params)) {
            System.err.println("Wallet does not match requested network parameters: "
                    + wallet.getParams().getId() + " vs " + params.getId());
            return;
        }
    } catch (Exception e) {
        System.err.println("Failed to load wallet '" + walletFile + "': " + e.getMessage());
        e.printStackTrace();
        return;
    }

    // What should we do?
    switch (action) {
    case DUMP:
        dumpWallet();
        break;
    case ADD_KEY:
        addKey();
        break;
    case ADD_ADDR:
        addAddr();
        break;
    case DELETE_KEY:
        deleteKey();
        break;
    case RESET:
        reset();
        break;
    case SYNC:
        syncChain();
        break;
    case SEND:
        if (!options.has(outputFlag)) {
            System.err.println("You must specify at least one --output=addr:value.");
            return;
        }
        BigInteger fee = BigInteger.ZERO;
        if (options.has("fee")) {
            fee = Utils.toNanoCoins((String) options.valueOf("fee"));
        }
        String lockTime = null;
        if (options.has("locktime")) {
            lockTime = (String) options.valueOf("locktime");
        }
        boolean allowUnconfirmed = options.has("allow-unconfirmed");
        send(outputFlag.values(options), fee, lockTime, allowUnconfirmed);
        break;
    }

    if (!wallet.isConsistent()) {
        System.err.println("************** WALLET IS INCONSISTENT *****************");
        return;
    }

    saveWallet(walletFile);

    if (options.has(waitForFlag)) {
        WaitForEnum value;
        try {
            value = waitForFlag.value(options);
        } catch (Exception e) {
            System.err.println("Could not understand the --waitfor flag: Valid options are WALLET_TX, BLOCK, "
                    + "BALANCE and EVER");
            return;
        }
        wait(value);
        if (!wallet.isConsistent()) {
            System.err.println("************** WALLET IS INCONSISTENT *****************");
            return;
        }
        saveWallet(walletFile);
    }
    shutdown();
}

From source file:com.google.vertcoin.tools.WalletTool.java

public static void main(String[] args) throws Exception {
    OptionParser parser = new OptionParser();
    parser.accepts("help");
    parser.accepts("force");
    parser.accepts("debuglog");
    OptionSpec<String> walletFileName = parser.accepts("wallet").withRequiredArg().defaultsTo("wallet");
    OptionSpec<NetworkEnum> netFlag = parser.accepts("net").withOptionalArg().ofType(NetworkEnum.class)
            .defaultsTo(NetworkEnum.PROD);
    dateFlag = parser.accepts("date").withRequiredArg().ofType(Date.class)
            .withValuesConvertedBy(DateConverter.datePattern("yyyy/MM/dd"));
    OptionSpec<WaitForEnum> waitForFlag = parser.accepts("waitfor").withRequiredArg().ofType(WaitForEnum.class);
    OptionSpec<ValidationMode> modeFlag = parser.accepts("mode").withRequiredArg().ofType(ValidationMode.class)
            .defaultsTo(ValidationMode.SPV);
    OptionSpec<String> chainFlag = parser.accepts("chain").withRequiredArg();
    // For addkey/delkey.
    parser.accepts("pubkey").withRequiredArg();
    parser.accepts("privkey").withRequiredArg();
    parser.accepts("addr").withRequiredArg();
    parser.accepts("peers").withRequiredArg();
    OptionSpec<String> outputFlag = parser.accepts("output").withRequiredArg();
    parser.accepts("value").withRequiredArg();
    parser.accepts("fee").withRequiredArg();
    unixtimeFlag = parser.accepts("unixtime").withRequiredArg().ofType(Integer.class);
    OptionSpec<String> conditionFlag = parser.accepts("condition").withRequiredArg();
    parser.accepts("locktime").withRequiredArg();
    parser.accepts("allow-unconfirmed");
    parser.accepts("offline");
    parser.accepts("ignore-mandatory-extensions");
    OptionSpec<String> passwordFlag = parser.accepts("password").withRequiredArg();
    OptionSpec<String> paymentRequestLocation = parser.accepts("payment-request").withRequiredArg();
    parser.accepts("no-pki");
    options = parser.parse(args);/*from w ww  . j  a  va2  s. c  o m*/

    final String HELP_TEXT = Resources.toString(WalletTool.class.getResource("wallet-tool-help.txt"),
            Charsets.UTF_8);

    if (args.length == 0 || options.has("help") || options.nonOptionArguments().size() < 1) {
        System.out.println(HELP_TEXT);
        return;
    }

    ActionEnum action;
    try {
        String actionStr = options.nonOptionArguments().get(0);
        actionStr = actionStr.toUpperCase().replace("-", "_");
        action = ActionEnum.valueOf(actionStr);
    } catch (IllegalArgumentException e) {
        System.err.println("Could not understand action name " + options.nonOptionArguments().get(0));
        return;
    }

    if (options.has("debuglog")) {
        BriefLogFormatter.init();
        log.info("Starting up ...");
    } else {
        // Disable logspam unless there is a flag.
        java.util.logging.Logger logger = LogManager.getLogManager().getLogger("");
        logger.setLevel(Level.SEVERE);
    }
    switch (netFlag.value(options)) {
    case PROD:
        params = MainNetParams.get();
        chainFileName = new File("prodnet.chain");
        break;
    case TEST:
        params = TestNet3Params.get();
        chainFileName = new File("testnet.chain");
        break;
    case REGTEST:
        params = RegTestParams.get();
        chainFileName = new File("regtest.chain");
        break;
    default:
        throw new RuntimeException("Unreachable.");
    }
    mode = modeFlag.value(options);

    // Allow the user to override the name of the chain used.
    if (options.has(chainFlag)) {
        chainFileName = new File(chainFlag.value(options));
    }

    if (options.has("condition")) {
        condition = new Condition(conditionFlag.value(options));
    }

    if (options.has(passwordFlag)) {
        password = passwordFlag.value(options);
    }

    walletFile = new File(walletFileName.value(options));
    if (action == ActionEnum.CREATE) {
        createWallet(options, params, walletFile);
        return; // We're done.
    }
    if (!walletFile.exists()) {
        System.err.println("Specified wallet file " + walletFile + " does not exist. Try wallet-tool --wallet="
                + walletFile + " create");
        return;
    }

    if (action == ActionEnum.RAW_DUMP) {
        // Just parse the protobuf and print, then bail out. Don't try and do a real deserialization. This is
        // useful mostly for investigating corrupted wallets.
        FileInputStream stream = new FileInputStream(walletFile);
        try {
            Protos.Wallet proto = WalletProtobufSerializer.parseToProto(stream);
            System.out.println(proto.toString());
            return;
        } finally {
            stream.close();
        }
    }

    try {
        WalletProtobufSerializer loader = new WalletProtobufSerializer();
        if (options.has("ignore-mandatory-extensions"))
            loader.setRequireMandatoryExtensions(false);
        wallet = loader.readWallet(new BufferedInputStream(new FileInputStream(walletFile)));
        if (!wallet.getParams().equals(params)) {
            System.err.println("Wallet does not match requested network parameters: "
                    + wallet.getParams().getId() + " vs " + params.getId());
            return;
        }
    } catch (Exception e) {
        System.err.println("Failed to load wallet '" + walletFile + "': " + e.getMessage());
        e.printStackTrace();
        return;
    }

    // What should we do?
    switch (action) {
    case DUMP:
        dumpWallet();
        break;
    case ADD_KEY:
        addKey();
        break;
    case ADD_ADDR:
        addAddr();
        break;
    case DELETE_KEY:
        deleteKey();
        break;
    case RESET:
        reset();
        break;
    case SYNC:
        syncChain();
        break;
    case SEND:
        if (options.has(paymentRequestLocation) && options.has(outputFlag)) {
            System.err.println("--payment-request and --output cannot be used together.");
            return;
        } else if (options.has(outputFlag)) {
            BigInteger fee = BigInteger.ZERO;
            if (options.has("fee")) {
                fee = Utils.toNanoCoins((String) options.valueOf("fee"));
            }
            String lockTime = null;
            if (options.has("locktime")) {
                lockTime = (String) options.valueOf("locktime");
            }
            boolean allowUnconfirmed = options.has("allow-unconfirmed");
            send(outputFlag.values(options), fee, lockTime, allowUnconfirmed);
        } else if (options.has(paymentRequestLocation)) {
            sendPaymentRequest(paymentRequestLocation.value(options), !options.has("no-pki"));
        } else {
            System.err.println("You must specify a --payment-request or at least one --output=addr:value.");
            return;
        }
        break;
    }

    if (!wallet.isConsistent()) {
        System.err.println("************** WALLET IS INCONSISTENT *****************");
        return;
    }

    saveWallet(walletFile);

    if (options.has(waitForFlag)) {
        WaitForEnum value;
        try {
            value = waitForFlag.value(options);
        } catch (Exception e) {
            System.err.println("Could not understand the --waitfor flag: Valid options are WALLET_TX, BLOCK, "
                    + "BALANCE and EVER");
            return;
        }
        wait(value);
        if (!wallet.isConsistent()) {
            System.err.println("************** WALLET IS INCONSISTENT *****************");
            return;
        }
        saveWallet(walletFile);
    }
    shutdown();
}

From source file:com.google.sha1coin.tools.WalletTool.java

public static void main(String[] args) throws Exception {
    OptionParser parser = new OptionParser();
    parser.accepts("help");
    parser.accepts("force");
    parser.accepts("debuglog");
    OptionSpec<String> walletFileName = parser.accepts("wallet").withRequiredArg().defaultsTo("wallet");
    seedFlag = parser.accepts("seed").withRequiredArg();
    watchFlag = parser.accepts("watchkey").withRequiredArg();
    OptionSpec<NetworkEnum> netFlag = parser.accepts("net").withOptionalArg().ofType(NetworkEnum.class)
            .defaultsTo(NetworkEnum.PROD);
    dateFlag = parser.accepts("date").withRequiredArg().ofType(Date.class)
            .withValuesConvertedBy(DateConverter.datePattern("yyyy/MM/dd"));
    OptionSpec<WaitForEnum> waitForFlag = parser.accepts("waitfor").withRequiredArg().ofType(WaitForEnum.class);
    OptionSpec<ValidationMode> modeFlag = parser.accepts("mode").withRequiredArg().ofType(ValidationMode.class)
            .defaultsTo(ValidationMode.SPV);
    OptionSpec<String> chainFlag = parser.accepts("chain").withRequiredArg();
    // For addkey/delkey.
    parser.accepts("pubkey").withRequiredArg();
    parser.accepts("privkey").withRequiredArg();
    parser.accepts("addr").withRequiredArg();
    parser.accepts("peers").withRequiredArg();
    xpubkeysFlag = parser.accepts("xpubkeys").withRequiredArg();
    OptionSpec<String> outputFlag = parser.accepts("output").withRequiredArg();
    parser.accepts("value").withRequiredArg();
    parser.accepts("fee").withRequiredArg();
    unixtimeFlag = parser.accepts("unixtime").withRequiredArg().ofType(Integer.class);
    OptionSpec<String> conditionFlag = parser.accepts("condition").withRequiredArg();
    parser.accepts("locktime").withRequiredArg();
    parser.accepts("allow-unconfirmed");
    parser.accepts("offline");
    parser.accepts("ignore-mandatory-extensions");
    lookaheadSize = parser.accepts("lookahead-size").withRequiredArg().ofType(Integer.class);
    OptionSpec<String> passwordFlag = parser.accepts("password").withRequiredArg();
    OptionSpec<String> paymentRequestLocation = parser.accepts("payment-request").withRequiredArg();
    parser.accepts("no-pki");
    parser.accepts("tor");
    options = parser.parse(args);//from  w w  w  . j a v a 2s  .c o  m

    final String HELP_TEXT = Resources.toString(WalletTool.class.getResource("wallet-tool-help.txt"),
            Charsets.UTF_8);

    if (args.length == 0 || options.has("help") || options.nonOptionArguments().size() < 1
            || options.nonOptionArguments().contains("help")) {
        System.out.println(HELP_TEXT);
        return;
    }

    ActionEnum action;
    try {
        String actionStr = options.nonOptionArguments().get(0);
        actionStr = actionStr.toUpperCase().replace("-", "_");
        action = ActionEnum.valueOf(actionStr);
    } catch (IllegalArgumentException e) {
        System.err.println("Could not understand action name " + options.nonOptionArguments().get(0));
        return;
    }

    if (options.has("debuglog")) {
        BriefLogFormatter.init();
        log.info("Starting up ...");
    } else {
        // Disable logspam unless there is a flag.
        java.util.logging.Logger logger = LogManager.getLogManager().getLogger("");
        logger.setLevel(Level.SEVERE);
    }
    switch (netFlag.value(options)) {
    case PROD:
        params = MainNetParams.get();
        chainFileName = new File("prodnet.chain");
        break;
    case TEST:
        params = TestNet3Params.get();
        chainFileName = new File("testnet.chain");
        break;
    case REGTEST:
        params = RegTestParams.get();
        chainFileName = new File("regtest.chain");
        break;
    default:
        throw new RuntimeException("Unreachable.");
    }
    mode = modeFlag.value(options);

    // Allow the user to override the name of the chain used.
    if (options.has(chainFlag)) {
        chainFileName = new File(chainFlag.value(options));
    }

    if (options.has("condition")) {
        condition = new Condition(conditionFlag.value(options));
    }

    if (options.has(passwordFlag)) {
        password = passwordFlag.value(options);
    }

    walletFile = new File(walletFileName.value(options));
    if (action == ActionEnum.CREATE) {
        createWallet(options, params, walletFile);
        return; // We're done.
    }
    if (!walletFile.exists()) {
        System.err.println("Specified wallet file " + walletFile + " does not exist. Try wallet-tool --wallet="
                + walletFile + " create");
        return;
    }

    if (action == ActionEnum.RAW_DUMP) {
        // Just parse the protobuf and print, then bail out. Don't try and do a real deserialization. This is
        // useful mostly for investigating corrupted wallets.
        FileInputStream stream = new FileInputStream(walletFile);
        try {
            Protos.Wallet proto = WalletProtobufSerializer.parseToProto(stream);
            System.out.println(proto.toString());
            return;
        } finally {
            stream.close();
        }
    }

    InputStream walletInputStream = null;
    try {
        WalletProtobufSerializer loader = new WalletProtobufSerializer();
        if (options.has("ignore-mandatory-extensions"))
            loader.setRequireMandatoryExtensions(false);
        walletInputStream = new BufferedInputStream(new FileInputStream(walletFile));
        wallet = loader.readWallet(walletInputStream);
        if (!wallet.getParams().equals(params)) {
            System.err.println("Wallet does not match requested network parameters: "
                    + wallet.getParams().getId() + " vs " + params.getId());
            return;
        }
    } catch (Exception e) {
        System.err.println("Failed to load wallet '" + walletFile + "': " + e.getMessage());
        e.printStackTrace();
        return;
    } finally {
        if (walletInputStream != null) {
            walletInputStream.close();
        }
    }

    // What should we do?
    switch (action) {
    case DUMP:
        dumpWallet();
        break;
    case ADD_KEY:
        addKey();
        break;
    case ADD_ADDR:
        addAddr();
        break;
    case DELETE_KEY:
        deleteKey();
        break;
    case RESET:
        reset();
        break;
    case SYNC:
        syncChain();
        break;
    case SEND:
        if (options.has(paymentRequestLocation) && options.has(outputFlag)) {
            System.err.println("--payment-request and --output cannot be used together.");
            return;
        } else if (options.has(outputFlag)) {
            Coin fee = Coin.ZERO;
            if (options.has("fee")) {
                fee = parseCoin((String) options.valueOf("fee"));
            }
            String lockTime = null;
            if (options.has("locktime")) {
                lockTime = (String) options.valueOf("locktime");
            }
            boolean allowUnconfirmed = options.has("allow-unconfirmed");
            send(outputFlag.values(options), fee, lockTime, allowUnconfirmed);
        } else if (options.has(paymentRequestLocation)) {
            sendPaymentRequest(paymentRequestLocation.value(options), !options.has("no-pki"));
        } else {
            System.err.println("You must specify a --payment-request or at least one --output=addr:value.");
            return;
        }
        break;
    case ENCRYPT:
        encrypt();
        break;
    case DECRYPT:
        decrypt();
        break;
    case MARRY:
        marry();
        break;
    case ROTATE:
        rotate();
        break;
    }

    if (!wallet.isConsistent()) {
        System.err.println("************** WALLET IS INCONSISTENT *****************");
        return;
    }

    saveWallet(walletFile);

    if (options.has(waitForFlag)) {
        WaitForEnum value;
        try {
            value = waitForFlag.value(options);
        } catch (Exception e) {
            System.err.println("Could not understand the --waitfor flag: Valid options are WALLET_TX, BLOCK, "
                    + "BALANCE and EVER");
            return;
        }
        wait(value);
        if (!wallet.isConsistent()) {
            System.err.println("************** WALLET IS INCONSISTENT *****************");
            return;
        }
        saveWallet(walletFile);
    }
    shutdown();
}

From source file:com.ligerzero459.paycoin.tools.WalletTool.java

public static void main(String[] args) throws Exception {
    OptionParser parser = new OptionParser();
    parser.accepts("help");
    parser.accepts("force");
    parser.accepts("debuglog");
    OptionSpec<String> walletFileName = parser.accepts("wallet").withRequiredArg().defaultsTo("wallet");
    seedFlag = parser.accepts("seed").withRequiredArg();
    watchFlag = parser.accepts("watchkey").withRequiredArg();
    OptionSpec<NetworkEnum> netFlag = parser.accepts("net").withOptionalArg().ofType(NetworkEnum.class)
            .defaultsTo(NetworkEnum.PROD);
    dateFlag = parser.accepts("date").withRequiredArg().ofType(Date.class)
            .withValuesConvertedBy(DateConverter.datePattern("yyyy/MM/dd"));
    OptionSpec<WaitForEnum> waitForFlag = parser.accepts("waitfor").withRequiredArg().ofType(WaitForEnum.class);
    OptionSpec<ValidationMode> modeFlag = parser.accepts("mode").withRequiredArg().ofType(ValidationMode.class)
            .defaultsTo(ValidationMode.SPV);
    OptionSpec<String> chainFlag = parser.accepts("chain").withRequiredArg();
    // For addkey/delkey.
    parser.accepts("pubkey").withRequiredArg();
    parser.accepts("privkey").withRequiredArg();
    parser.accepts("addr").withRequiredArg();
    parser.accepts("peers").withRequiredArg();
    xpubkeysFlag = parser.accepts("xpubkeys").withRequiredArg();
    OptionSpec<String> outputFlag = parser.accepts("output").withRequiredArg();
    parser.accepts("value").withRequiredArg();
    parser.accepts("fee").withRequiredArg();
    unixtimeFlag = parser.accepts("unixtime").withRequiredArg().ofType(Integer.class);
    OptionSpec<String> conditionFlag = parser.accepts("condition").withRequiredArg();
    parser.accepts("locktime").withRequiredArg();
    parser.accepts("allow-unconfirmed");
    parser.accepts("offline");
    parser.accepts("ignore-mandatory-extensions");
    lookaheadSize = parser.accepts("lookahead-size").withRequiredArg().ofType(Integer.class);
    OptionSpec<String> passwordFlag = parser.accepts("password").withRequiredArg();
    OptionSpec<String> paymentRequestLocation = parser.accepts("payment-request").withRequiredArg();
    parser.accepts("no-pki");
    parser.accepts("tor");
    parser.accepts("dump-privkeys");
    options = parser.parse(args);//from w  ww  .j  a v a 2 s .c o  m

    final String HELP_TEXT = Resources.toString(WalletTool.class.getResource("wallet-tool-help.txt"),
            Charsets.UTF_8);

    if (args.length == 0 || options.has("help") || options.nonOptionArguments().size() < 1
            || options.nonOptionArguments().contains("help")) {
        System.out.println(HELP_TEXT);
        return;
    }

    ActionEnum action;
    try {
        String actionStr = options.nonOptionArguments().get(0);
        actionStr = actionStr.toUpperCase().replace("-", "_");
        action = ActionEnum.valueOf(actionStr);
    } catch (IllegalArgumentException e) {
        System.err.println("Could not understand action name " + options.nonOptionArguments().get(0));
        return;
    }

    if (options.has("debuglog")) {
        BriefLogFormatter.init();
        log.info("Starting up ...");
    } else {
        // Disable logspam unless there is a flag.
        java.util.logging.Logger logger = LogManager.getLogManager().getLogger("");
        logger.setLevel(Level.SEVERE);
    }
    switch (netFlag.value(options)) {
    case PROD:
        params = MainNetParams.get();
        chainFileName = new File("prodnet.chain");
        break;
    default:
        throw new RuntimeException("Unreachable.");
    }
    mode = modeFlag.value(options);

    // Allow the user to override the name of the chain used.
    if (options.has(chainFlag)) {
        chainFileName = new File(chainFlag.value(options));
    }

    if (options.has("condition")) {
        condition = new Condition(conditionFlag.value(options));
    }

    if (options.has(passwordFlag)) {
        password = passwordFlag.value(options);
    }

    walletFile = new File(walletFileName.value(options));
    if (action == ActionEnum.CREATE) {
        createWallet(options, params, walletFile);
        return; // We're done.
    }
    if (!walletFile.exists()) {
        System.err.println("Specified wallet file " + walletFile + " does not exist. Try wallet-tool --wallet="
                + walletFile + " create");
        return;
    }

    if (action == ActionEnum.RAW_DUMP) {
        // Just parse the protobuf and print, then bail out. Don't try and do a real deserialization. This is
        // useful mostly for investigating corrupted wallets.
        FileInputStream stream = new FileInputStream(walletFile);
        try {
            Protos.Wallet proto = WalletProtobufSerializer.parseToProto(stream);
            proto = attemptHexConversion(proto);
            System.out.println(proto.toString());
            return;
        } finally {
            stream.close();
        }
    }

    InputStream walletInputStream = null;
    try {
        WalletProtobufSerializer loader = new WalletProtobufSerializer();
        if (options.has("ignore-mandatory-extensions"))
            loader.setRequireMandatoryExtensions(false);
        walletInputStream = new BufferedInputStream(new FileInputStream(walletFile));
        wallet = loader.readWallet(walletInputStream);
        if (!wallet.getParams().equals(params)) {
            System.err.println("Wallet does not match requested network parameters: "
                    + wallet.getParams().getId() + " vs " + params.getId());
            return;
        }
    } catch (Exception e) {
        System.err.println("Failed to load wallet '" + walletFile + "': " + e.getMessage());
        e.printStackTrace();
        return;
    } finally {
        if (walletInputStream != null) {
            walletInputStream.close();
        }
    }

    // What should we do?
    switch (action) {
    case DUMP:
        dumpWallet();
        break;
    case ADD_KEY:
        addKey();
        break;
    case ADD_ADDR:
        addAddr();
        break;
    case DELETE_KEY:
        deleteKey();
        break;
    case RESET:
        reset();
        break;
    case SYNC:
        syncChain();
        break;
    case SEND:
        if (options.has(paymentRequestLocation) && options.has(outputFlag)) {
            System.err.println("--payment-request and --output cannot be used together.");
            return;
        } else if (options.has(outputFlag)) {
            Coin fee = Coin.ZERO;
            if (options.has("fee")) {
                fee = parseCoin((String) options.valueOf("fee"));
            }
            String lockTime = null;
            if (options.has("locktime")) {
                lockTime = (String) options.valueOf("locktime");
            }
            boolean allowUnconfirmed = options.has("allow-unconfirmed");
            send(outputFlag.values(options), fee, lockTime, allowUnconfirmed);
        } else if (options.has(paymentRequestLocation)) {
            sendPaymentRequest(paymentRequestLocation.value(options), !options.has("no-pki"));
        } else {
            System.err.println("You must specify a --payment-request or at least one --output=addr:value.");
            return;
        }
        break;
    case ENCRYPT:
        encrypt();
        break;
    case DECRYPT:
        decrypt();
        break;
    case MARRY:
        marry();
        break;
    case ROTATE:
        rotate();
        break;
    }

    if (!wallet.isConsistent()) {
        System.err.println("************** WALLET IS INCONSISTENT *****************");
        return;
    }

    saveWallet(walletFile);

    if (options.has(waitForFlag)) {
        WaitForEnum value;
        try {
            value = waitForFlag.value(options);
        } catch (Exception e) {
            System.err.println("Could not understand the --waitfor flag: Valid options are WALLET_TX, BLOCK, "
                    + "BALANCE and EVER");
            return;
        }
        wait(value);
        if (!wallet.isConsistent()) {
            System.err.println("************** WALLET IS INCONSISTENT *****************");
            return;
        }
        saveWallet(walletFile);
    }
    shutdown();
}

From source file:org.neoscoinj.tools.WalletTool.java

public static void main(String[] args) throws Exception {
    OptionParser parser = new OptionParser();
    parser.accepts("help");
    parser.accepts("force");
    parser.accepts("debuglog");
    OptionSpec<String> walletFileName = parser.accepts("wallet").withRequiredArg().defaultsTo("wallet");
    seedFlag = parser.accepts("seed").withRequiredArg();
    watchFlag = parser.accepts("watchkey").withRequiredArg();
    OptionSpec<NetworkEnum> netFlag = parser.accepts("net").withOptionalArg().ofType(NetworkEnum.class)
            .defaultsTo(NetworkEnum.MAIN);
    dateFlag = parser.accepts("date").withRequiredArg().ofType(Date.class)
            .withValuesConvertedBy(DateConverter.datePattern("yyyy/MM/dd"));
    OptionSpec<WaitForEnum> waitForFlag = parser.accepts("waitfor").withRequiredArg().ofType(WaitForEnum.class);
    OptionSpec<ValidationMode> modeFlag = parser.accepts("mode").withRequiredArg().ofType(ValidationMode.class)
            .defaultsTo(ValidationMode.SPV);
    OptionSpec<String> chainFlag = parser.accepts("chain").withRequiredArg();
    // For addkey/delkey.
    parser.accepts("pubkey").withRequiredArg();
    parser.accepts("privkey").withRequiredArg();
    parser.accepts("addr").withRequiredArg();
    parser.accepts("peers").withRequiredArg();
    xpubkeysFlag = parser.accepts("xpubkeys").withRequiredArg();
    OptionSpec<String> outputFlag = parser.accepts("output").withRequiredArg();
    parser.accepts("value").withRequiredArg();
    parser.accepts("fee").withRequiredArg();
    unixtimeFlag = parser.accepts("unixtime").withRequiredArg().ofType(Long.class);
    OptionSpec<String> conditionFlag = parser.accepts("condition").withRequiredArg();
    parser.accepts("locktime").withRequiredArg();
    parser.accepts("allow-unconfirmed");
    parser.accepts("offline");
    parser.accepts("ignore-mandatory-extensions");
    lookaheadSize = parser.accepts("lookahead-size").withRequiredArg().ofType(Integer.class);
    OptionSpec<String> passwordFlag = parser.accepts("password").withRequiredArg();
    OptionSpec<String> paymentRequestLocation = parser.accepts("payment-request").withRequiredArg();
    parser.accepts("no-pki");
    parser.accepts("tor");
    parser.accepts("dump-privkeys");
    options = parser.parse(args);//from w  ww  . j  ava2s  .c  o  m

    final String HELP_TEXT = Resources.toString(WalletTool.class.getResource("wallet-tool-help.txt"),
            Charsets.UTF_8);

    if (args.length == 0 || options.has("help") || options.nonOptionArguments().size() < 1
            || options.nonOptionArguments().contains("help")) {
        System.out.println(HELP_TEXT);
        return;
    }

    ActionEnum action;
    try {
        String actionStr = options.nonOptionArguments().get(0);
        actionStr = actionStr.toUpperCase().replace("-", "_");
        action = ActionEnum.valueOf(actionStr);
    } catch (IllegalArgumentException e) {
        System.err.println("Could not understand action name " + options.nonOptionArguments().get(0));
        return;
    }

    if (options.has("debuglog")) {
        BriefLogFormatter.init();
        log.info("Starting up ...");
    } else {
        // Disable logspam unless there is a flag.
        java.util.logging.Logger logger = LogManager.getLogManager().getLogger("");
        logger.setLevel(Level.SEVERE);
    }
    switch (netFlag.value(options)) {
    case MAIN:
    case PROD:
        params = MainNetParams.get();
        chainFileName = new File("mainnet.chain");
        break;
    case TEST:
        params = TestNet3Params.get();
        chainFileName = new File("testnet.chain");
        break;
    case REGTEST:
        params = RegTestParams.get();
        chainFileName = new File("regtest.chain");
        break;
    default:
        throw new RuntimeException("Unreachable.");
    }
    mode = modeFlag.value(options);

    // Allow the user to override the name of the chain used.
    if (options.has(chainFlag)) {
        chainFileName = new File(chainFlag.value(options));
    }

    if (options.has("condition")) {
        condition = new Condition(conditionFlag.value(options));
    }

    if (options.has(passwordFlag)) {
        password = passwordFlag.value(options);
    }

    walletFile = new File(walletFileName.value(options));
    if (action == ActionEnum.CREATE) {
        createWallet(options, params, walletFile);
        return; // We're done.
    }
    if (!walletFile.exists()) {
        System.err.println("Specified wallet file " + walletFile + " does not exist. Try wallet-tool --wallet="
                + walletFile + " create");
        return;
    }

    if (action == ActionEnum.RAW_DUMP) {
        // Just parse the protobuf and print, then bail out. Don't try and do a real deserialization. This is
        // useful mostly for investigating corrupted wallets.
        FileInputStream stream = new FileInputStream(walletFile);
        try {
            Protos.Wallet proto = WalletProtobufSerializer.parseToProto(stream);
            proto = attemptHexConversion(proto);
            System.out.println(proto.toString());
            return;
        } finally {
            stream.close();
        }
    }

    InputStream walletInputStream = null;
    try {
        WalletProtobufSerializer loader = new WalletProtobufSerializer();
        if (options.has("ignore-mandatory-extensions"))
            loader.setRequireMandatoryExtensions(false);
        walletInputStream = new BufferedInputStream(new FileInputStream(walletFile));
        wallet = loader.readWallet(walletInputStream);
        if (!wallet.getParams().equals(params)) {
            System.err.println("Wallet does not match requested network parameters: "
                    + wallet.getParams().getId() + " vs " + params.getId());
            return;
        }
    } catch (Exception e) {
        System.err.println("Failed to load wallet '" + walletFile + "': " + e.getMessage());
        e.printStackTrace();
        return;
    } finally {
        if (walletInputStream != null) {
            walletInputStream.close();
        }
    }

    // What should we do?
    switch (action) {
    case DUMP:
        dumpWallet();
        break;
    case ADD_KEY:
        addKey();
        break;
    case ADD_ADDR:
        addAddr();
        break;
    case DELETE_KEY:
        deleteKey();
        break;
    case RESET:
        reset();
        break;
    case SYNC:
        syncChain();
        break;
    case SEND:
        if (options.has(paymentRequestLocation) && options.has(outputFlag)) {
            System.err.println("--payment-request and --output cannot be used together.");
            return;
        } else if (options.has(outputFlag)) {
            Coin fee = Coin.ZERO;
            if (options.has("fee")) {
                fee = parseCoin((String) options.valueOf("fee"));
            }
            String lockTime = null;
            if (options.has("locktime")) {
                lockTime = (String) options.valueOf("locktime");
            }
            boolean allowUnconfirmed = options.has("allow-unconfirmed");
            send(outputFlag.values(options), fee, lockTime, allowUnconfirmed);
        } else if (options.has(paymentRequestLocation)) {
            sendPaymentRequest(paymentRequestLocation.value(options), !options.has("no-pki"));
        } else {
            System.err.println("You must specify a --payment-request or at least one --output=addr:value.");
            return;
        }
        break;
    case ENCRYPT:
        encrypt();
        break;
    case DECRYPT:
        decrypt();
        break;
    case MARRY:
        marry();
        break;
    case ROTATE:
        rotate();
        break;
    }

    if (!wallet.isConsistent()) {
        System.err.println("************** WALLET IS INCONSISTENT *****************");
        return;
    }

    saveWallet(walletFile);

    if (options.has(waitForFlag)) {
        WaitForEnum value;
        try {
            value = waitForFlag.value(options);
        } catch (Exception e) {
            System.err.println("Could not understand the --waitfor flag: Valid options are WALLET_TX, BLOCK, "
                    + "BALANCE and EVER");
            return;
        }
        wait(value);
        if (!wallet.isConsistent()) {
            System.err.println("************** WALLET IS INCONSISTENT *****************");
            return;
        }
        saveWallet(walletFile);
    }
    shutdown();
}

From source file:com.matthewmitchell.nubitsj.tools.WalletTool.java

public static void main(String[] args) throws Exception {
    OptionParser parser = new OptionParser();
    parser.accepts("help");
    parser.accepts("force");
    parser.accepts("debuglog");
    OptionSpec<String> walletFileName = parser.accepts("wallet").withRequiredArg().defaultsTo("wallet");
    seedFlag = parser.accepts("seed").withRequiredArg();
    watchFlag = parser.accepts("watchkey").withRequiredArg();
    OptionSpec<NetworkEnum> netFlag = parser.accepts("net").withOptionalArg().ofType(NetworkEnum.class)
            .defaultsTo(NetworkEnum.PROD);
    dateFlag = parser.accepts("date").withRequiredArg().ofType(Date.class)
            .withValuesConvertedBy(DateConverter.datePattern("yyyy/MM/dd"));
    OptionSpec<WaitForEnum> waitForFlag = parser.accepts("waitfor").withRequiredArg().ofType(WaitForEnum.class);
    OptionSpec<ValidationMode> modeFlag = parser.accepts("mode").withRequiredArg().ofType(ValidationMode.class)
            .defaultsTo(ValidationMode.SPV);
    OptionSpec<String> chainFlag = parser.accepts("chain").withRequiredArg();
    // For addkey/delkey.
    parser.accepts("pubkey").withRequiredArg();
    parser.accepts("privkey").withRequiredArg();
    parser.accepts("addr").withRequiredArg();
    parser.accepts("peers").withRequiredArg();
    xpubkeysFlag = parser.accepts("xpubkeys").withRequiredArg();
    OptionSpec<String> outputFlag = parser.accepts("output").withRequiredArg();
    parser.accepts("value").withRequiredArg();
    parser.accepts("fee").withRequiredArg();
    unixtimeFlag = parser.accepts("unixtime").withRequiredArg().ofType(Integer.class);
    OptionSpec<String> conditionFlag = parser.accepts("condition").withRequiredArg();
    parser.accepts("locktime").withRequiredArg();
    parser.accepts("allow-unconfirmed");
    parser.accepts("offline");
    parser.accepts("ignore-mandatory-extensions");
    lookaheadSize = parser.accepts("lookahead-size").withRequiredArg().ofType(Integer.class);
    OptionSpec<String> passwordFlag = parser.accepts("password").withRequiredArg();
    OptionSpec<String> paymentRequestLocation = parser.accepts("payment-request").withRequiredArg();
    parser.accepts("no-pki");
    parser.accepts("tor");
    parser.accepts("dump-privkeys");
    options = parser.parse(args);/* w  w  w  . j ava  2  s  .  c  om*/

    final String HELP_TEXT = Resources.toString(WalletTool.class.getResource("wallet-tool-help.txt"),
            Charsets.UTF_8);

    if (args.length == 0 || options.has("help") || options.nonOptionArguments().size() < 1
            || options.nonOptionArguments().contains("help")) {
        System.out.println(HELP_TEXT);
        return;
    }

    ActionEnum action;
    try {
        String actionStr = options.nonOptionArguments().get(0);
        actionStr = actionStr.toUpperCase().replace("-", "_");
        action = ActionEnum.valueOf(actionStr);
    } catch (IllegalArgumentException e) {
        System.err.println("Could not understand action name " + options.nonOptionArguments().get(0));
        return;
    }

    if (options.has("debuglog")) {
        BriefLogFormatter.init();
        log.info("Starting up ...");
    } else {
        // Disable logspam unless there is a flag.
        java.util.logging.Logger logger = LogManager.getLogManager().getLogger("");
        logger.setLevel(Level.SEVERE);
    }
    switch (netFlag.value(options)) {
    case PROD:
        params = MainNetParams.get();
        chainFileName = new File("prodnet.chain");
        break;
    case TEST:
        params = TestNet3Params.get();
        chainFileName = new File("testnet.chain");
        break;
    case REGTEST:
        params = RegTestParams.get();
        chainFileName = new File("regtest.chain");
        break;
    default:
        throw new RuntimeException("Unreachable.");
    }
    mode = modeFlag.value(options);

    // Allow the user to override the name of the chain used.
    if (options.has(chainFlag)) {
        chainFileName = new File(chainFlag.value(options));
    }

    if (options.has("condition")) {
        condition = new Condition(conditionFlag.value(options));
    }

    if (options.has(passwordFlag)) {
        password = passwordFlag.value(options);
    }

    walletFile = new File(walletFileName.value(options));
    if (action == ActionEnum.CREATE) {
        createWallet(options, params, walletFile);
        return; // We're done.
    }
    if (!walletFile.exists()) {
        System.err.println("Specified wallet file " + walletFile + " does not exist. Try wallet-tool --wallet="
                + walletFile + " create");
        return;
    }

    if (action == ActionEnum.RAW_DUMP) {
        // Just parse the protobuf and print, then bail out. Don't try and do a real deserialization. This is
        // useful mostly for investigating corrupted wallets.
        FileInputStream stream = new FileInputStream(walletFile);
        try {
            Protos.Wallet proto = WalletProtobufSerializer.parseToProto(stream);
            proto = attemptHexConversion(proto);
            System.out.println(proto.toString());
            return;
        } finally {
            stream.close();
        }
    }

    InputStream walletInputStream = null;
    try {
        WalletProtobufSerializer loader = new WalletProtobufSerializer();
        if (options.has("ignore-mandatory-extensions"))
            loader.setRequireMandatoryExtensions(false);
        walletInputStream = new BufferedInputStream(new FileInputStream(walletFile));
        wallet = loader.readWallet(walletInputStream);
        if (!wallet.getParams().equals(params)) {
            System.err.println("Wallet does not match requested network parameters: "
                    + wallet.getParams().getId() + " vs " + params.getId());
            return;
        }
    } catch (Exception e) {
        System.err.println("Failed to load wallet '" + walletFile + "': " + e.getMessage());
        e.printStackTrace();
        return;
    } finally {
        if (walletInputStream != null) {
            walletInputStream.close();
        }
    }

    // What should we do?
    switch (action) {
    case DUMP:
        dumpWallet();
        break;
    case ADD_KEY:
        addKey();
        break;
    case ADD_ADDR:
        addAddr();
        break;
    case DELETE_KEY:
        deleteKey();
        break;
    case RESET:
        reset();
        break;
    case SYNC:
        syncChain();
        break;
    case SEND:
        if (options.has(paymentRequestLocation) && options.has(outputFlag)) {
            System.err.println("--payment-request and --output cannot be used together.");
            return;
        } else if (options.has(outputFlag)) {
            Coin fee = Coin.ZERO;
            if (options.has("fee")) {
                fee = parseCoin((String) options.valueOf("fee"));
            }
            String lockTime = null;
            if (options.has("locktime")) {
                lockTime = (String) options.valueOf("locktime");
            }
            boolean allowUnconfirmed = options.has("allow-unconfirmed");
            send(outputFlag.values(options), fee, lockTime, allowUnconfirmed);
        } else if (options.has(paymentRequestLocation)) {
            sendPaymentRequest(paymentRequestLocation.value(options), !options.has("no-pki"));
        } else {
            System.err.println("You must specify a --payment-request or at least one --output=addr:value.");
            return;
        }
        break;
    case ENCRYPT:
        encrypt();
        break;
    case DECRYPT:
        decrypt();
        break;
    case MARRY:
        marry();
        break;
    case ROTATE:
        rotate();
        break;
    }

    if (!wallet.isConsistent()) {
        System.err.println("************** WALLET IS INCONSISTENT *****************");
        return;
    }

    saveWallet(walletFile);

    if (options.has(waitForFlag)) {
        WaitForEnum value;
        try {
            value = waitForFlag.value(options);
        } catch (Exception e) {
            System.err.println("Could not understand the --waitfor flag: Valid options are WALLET_TX, BLOCK, "
                    + "BALANCE and EVER");
            return;
        }
        wait(value);
        if (!wallet.isConsistent()) {
            System.err.println("************** WALLET IS INCONSISTENT *****************");
            return;
        }
        saveWallet(walletFile);
    }
    shutdown();
}

From source file:com.dogecoin.dogecoinj.tools.WalletTool.java

public static void main(String[] args) throws Exception {
    OptionParser parser = new OptionParser();
    parser.accepts("help");
    parser.accepts("force");
    parser.accepts("debuglog");
    OptionSpec<String> walletFileName = parser.accepts("wallet").withRequiredArg().defaultsTo("wallet");
    seedFlag = parser.accepts("seed").withRequiredArg();
    watchFlag = parser.accepts("watchkey").withRequiredArg();
    OptionSpec<NetworkEnum> netFlag = parser.accepts("net").withOptionalArg().ofType(NetworkEnum.class)
            .defaultsTo(NetworkEnum.MAIN);
    dateFlag = parser.accepts("date").withRequiredArg().ofType(Date.class)
            .withValuesConvertedBy(DateConverter.datePattern("yyyy/MM/dd"));
    OptionSpec<WaitForEnum> waitForFlag = parser.accepts("waitfor").withRequiredArg().ofType(WaitForEnum.class);
    OptionSpec<ValidationMode> modeFlag = parser.accepts("mode").withRequiredArg().ofType(ValidationMode.class)
            .defaultsTo(ValidationMode.SPV);
    OptionSpec<String> chainFlag = parser.accepts("chain").withRequiredArg();
    // For addkey/delkey.
    parser.accepts("pubkey").withRequiredArg();
    parser.accepts("privkey").withRequiredArg();
    parser.accepts("addr").withRequiredArg();
    parser.accepts("peers").withRequiredArg();
    xpubkeysFlag = parser.accepts("xpubkeys").withRequiredArg();
    OptionSpec<String> outputFlag = parser.accepts("output").withRequiredArg();
    parser.accepts("value").withRequiredArg();
    parser.accepts("fee").withRequiredArg();
    unixtimeFlag = parser.accepts("unixtime").withRequiredArg().ofType(Long.class);
    OptionSpec<String> conditionFlag = parser.accepts("condition").withRequiredArg();
    parser.accepts("locktime").withRequiredArg();
    parser.accepts("allow-unconfirmed");
    parser.accepts("offline");
    parser.accepts("ignore-mandatory-extensions");
    lookaheadSize = parser.accepts("lookahead-size").withRequiredArg().ofType(Integer.class);
    OptionSpec<String> passwordFlag = parser.accepts("password").withRequiredArg();
    OptionSpec<String> paymentRequestLocation = parser.accepts("payment-request").withRequiredArg();
    parser.accepts("no-pki");
    parser.accepts("tor");
    parser.accepts("dump-privkeys");
    options = parser.parse(args);/*  w w  w  .ja  va2  s  .  c  o m*/

    final String HELP_TEXT = Resources.toString(WalletTool.class.getResource("wallet-tool-help.txt"),
            Charsets.UTF_8);

    if (args.length == 0 || options.has("help") || options.nonOptionArguments().size() < 1
            || options.nonOptionArguments().contains("help")) {
        System.out.println(HELP_TEXT);
        return;
    }

    ActionEnum action;
    try {
        String actionStr = options.nonOptionArguments().get(0);
        actionStr = actionStr.toUpperCase().replace("-", "_");
        action = ActionEnum.valueOf(actionStr);
    } catch (IllegalArgumentException e) {
        System.err.println("Could not understand action name " + options.nonOptionArguments().get(0));
        return;
    }

    if (options.has("debuglog")) {
        BriefLogFormatter.init();
        log.info("Starting up ...");
    } else {
        // Disable logspam unless there is a flag.
        java.util.logging.Logger logger = LogManager.getLogManager().getLogger("");
        logger.setLevel(Level.SEVERE);
    }
    switch (netFlag.value(options)) {
    case MAIN:
    case PROD:
        params = MainNetParams.get();
        chainFileName = new File("mainnet.chain");
        break;
    case TEST:
        params = TestNet3Params.get();
        chainFileName = new File("testnet.chain");
        break;
    case REGTEST:
        params = RegTestParams.get();
        chainFileName = new File("regtest.chain");
        break;
    default:
        throw new RuntimeException("Unreachable.");
    }
    mode = modeFlag.value(options);

    // Allow the user to override the name of the chain used.
    if (options.has(chainFlag)) {
        chainFileName = new File(chainFlag.value(options));
    }

    if (options.has("condition")) {
        condition = new Condition(conditionFlag.value(options));
    }

    if (options.has(passwordFlag)) {
        password = passwordFlag.value(options);
    }

    walletFile = new File(walletFileName.value(options));
    if (action == ActionEnum.CREATE) {
        createWallet(options, params, walletFile);
        return; // We're done.
    }
    if (!walletFile.exists()) {
        System.err.println("Specified wallet file " + walletFile + " does not exist. Try wallet-tool --wallet="
                + walletFile + " create");
        return;
    }

    if (action == ActionEnum.RAW_DUMP) {
        // Just parse the protobuf and print, then bail out. Don't try and do a real deserialization. This is
        // useful mostly for investigating corrupted wallets.
        FileInputStream stream = new FileInputStream(walletFile);
        try {
            Protos.Wallet proto = WalletProtobufSerializer.parseToProto(stream);
            proto = attemptHexConversion(proto);
            System.out.println(proto.toString());
            return;
        } finally {
            stream.close();
        }
    }

    InputStream walletInputStream = null;
    try {
        WalletProtobufSerializer loader = new WalletProtobufSerializer();
        if (options.has("ignore-mandatory-extensions"))
            loader.setRequireMandatoryExtensions(false);
        walletInputStream = new BufferedInputStream(new FileInputStream(walletFile));
        wallet = loader.readWallet(walletInputStream);
        if (!wallet.getParams().equals(params)) {
            System.err.println("Wallet does not match requested network parameters: "
                    + wallet.getParams().getId() + " vs " + params.getId());
            return;
        }
    } catch (Exception e) {
        System.err.println("Failed to load wallet '" + walletFile + "': " + e.getMessage());
        e.printStackTrace();
        return;
    } finally {
        if (walletInputStream != null) {
            walletInputStream.close();
        }
    }

    // What should we do?
    switch (action) {
    case DUMP:
        dumpWallet();
        break;
    case ADD_KEY:
        addKey();
        break;
    case ADD_ADDR:
        addAddr();
        break;
    case DELETE_KEY:
        deleteKey();
        break;
    case CURRENT_RECEIVE_ADDR:
        currentReceiveAddr();
        break;
    case RESET:
        reset();
        break;
    case SYNC:
        syncChain();
        break;
    case SEND:
        if (options.has(paymentRequestLocation) && options.has(outputFlag)) {
            System.err.println("--payment-request and --output cannot be used together.");
            return;
        } else if (options.has(outputFlag)) {
            Coin fee = Coin.ZERO;
            if (options.has("fee")) {
                fee = parseCoin((String) options.valueOf("fee"));
            }
            String lockTime = null;
            if (options.has("locktime")) {
                lockTime = (String) options.valueOf("locktime");
            }
            boolean allowUnconfirmed = options.has("allow-unconfirmed");
            send(outputFlag.values(options), fee, lockTime, allowUnconfirmed);
        } else if (options.has(paymentRequestLocation)) {
            sendPaymentRequest(paymentRequestLocation.value(options), !options.has("no-pki"));
        } else {
            System.err.println("You must specify a --payment-request or at least one --output=addr:value.");
            return;
        }
        break;
    case ENCRYPT:
        encrypt();
        break;
    case DECRYPT:
        decrypt();
        break;
    case MARRY:
        marry();
        break;
    case ROTATE:
        rotate();
        break;
    }

    if (!wallet.isConsistent()) {
        System.err.println("************** WALLET IS INCONSISTENT *****************");
        return;
    }

    saveWallet(walletFile);

    if (options.has(waitForFlag)) {
        WaitForEnum value;
        try {
            value = waitForFlag.value(options);
        } catch (Exception e) {
            System.err.println("Could not understand the --waitfor flag: Valid options are WALLET_TX, BLOCK, "
                    + "BALANCE and EVER");
            return;
        }
        wait(value);
        if (!wallet.isConsistent()) {
            System.err.println("************** WALLET IS INCONSISTENT *****************");
            return;
        }
        saveWallet(walletFile);
    }
    shutdown();
}

From source file:com.matthewmitchell.peercoinj.tools.WalletTool.java

public static void main(String[] args) throws Exception {
    OptionParser parser = new OptionParser();
    parser.accepts("help");
    parser.accepts("force");
    parser.accepts("debuglog");
    OptionSpec<String> walletFileName = parser.accepts("wallet").withRequiredArg().defaultsTo("wallet");
    seedFlag = parser.accepts("seed").withRequiredArg();
    watchFlag = parser.accepts("watchkey").withRequiredArg();
    OptionSpec<NetworkEnum> netFlag = parser.accepts("net").withOptionalArg().ofType(NetworkEnum.class)
            .defaultsTo(NetworkEnum.PROD);
    dateFlag = parser.accepts("date").withRequiredArg().ofType(Date.class)
            .withValuesConvertedBy(DateConverter.datePattern("yyyy/MM/dd"));
    OptionSpec<WaitForEnum> waitForFlag = parser.accepts("waitfor").withRequiredArg().ofType(WaitForEnum.class);
    OptionSpec<ValidationMode> modeFlag = parser.accepts("mode").withRequiredArg().ofType(ValidationMode.class)
            .defaultsTo(ValidationMode.SPV);
    OptionSpec<String> chainFlag = parser.accepts("chain").withRequiredArg();
    OptionSpec<String> validHashFlag = parser.accepts("validhashes").withRequiredArg();
    // For addkey/delkey.
    parser.accepts("pubkey").withRequiredArg();
    parser.accepts("privkey").withRequiredArg();
    parser.accepts("addr").withRequiredArg();
    parser.accepts("peers").withRequiredArg();
    xpubkeysFlag = parser.accepts("xpubkeys").withRequiredArg();
    OptionSpec<String> outputFlag = parser.accepts("output").withRequiredArg();
    parser.accepts("value").withRequiredArg();
    parser.accepts("fee").withRequiredArg();
    unixtimeFlag = parser.accepts("unixtime").withRequiredArg().ofType(Integer.class);
    OptionSpec<String> conditionFlag = parser.accepts("condition").withRequiredArg();
    parser.accepts("locktime").withRequiredArg();
    parser.accepts("allow-unconfirmed");
    parser.accepts("offline");
    parser.accepts("ignore-mandatory-extensions");
    lookaheadSize = parser.accepts("lookahead-size").withRequiredArg().ofType(Integer.class);
    OptionSpec<String> passwordFlag = parser.accepts("password").withRequiredArg();
    OptionSpec<String> paymentRequestLocation = parser.accepts("payment-request").withRequiredArg();
    parser.accepts("no-pki");
    parser.accepts("tor");
    parser.accepts("dump-privkeys");
    options = parser.parse(args);//from   w ww  .  j a va 2  s .c  om

    final String HELP_TEXT = Resources.toString(WalletTool.class.getResource("wallet-tool-help.txt"),
            Charsets.UTF_8);

    if (args.length == 0 || options.has("help") || options.nonOptionArguments().size() < 1
            || options.nonOptionArguments().contains("help")) {
        System.out.println(HELP_TEXT);
        return;
    }

    ActionEnum action;
    try {
        String actionStr = options.nonOptionArguments().get(0);
        actionStr = actionStr.toUpperCase().replace("-", "_");
        action = ActionEnum.valueOf(actionStr);
    } catch (IllegalArgumentException e) {
        System.err.println("Could not understand action name " + options.nonOptionArguments().get(0));
        return;
    }

    if (options.has("debuglog")) {
        BriefLogFormatter.init();
        log.info("Starting up ...");
    } else {
        // Disable logspam unless there is a flag.
        java.util.logging.Logger logger = LogManager.getLogManager().getLogger("");
        logger.setLevel(Level.SEVERE);
    }
    switch (netFlag.value(options)) {
    case PROD:
        params = MainNetParams.get();
        chainFileName = new File("prodnet.chain");
        validHashFile = new File("validhashes.dat");
        break;
    default:
        throw new RuntimeException("Unreachable.");
    }
    mode = modeFlag.value(options);

    // Allow the user to override the name of the chain used.
    if (options.has(chainFlag)) {
        chainFileName = new File(chainFlag.value(options));
    }

    if (options.has(validHashFlag)) {
        validHashFile = new File(validHashFlag.value(options));
    }

    if (options.has("condition")) {
        condition = new Condition(conditionFlag.value(options));
    }

    if (options.has(passwordFlag)) {
        password = passwordFlag.value(options);
    }

    walletFile = new File(walletFileName.value(options));
    if (action == ActionEnum.CREATE) {
        createWallet(options, params, walletFile);
        return; // We're done.
    }
    if (!walletFile.exists()) {
        System.err.println("Specified wallet file " + walletFile + " does not exist. Try wallet-tool --wallet="
                + walletFile + " create");
        return;
    }

    if (action == ActionEnum.RAW_DUMP) {
        // Just parse the protobuf and print, then bail out. Don't try and do a real deserialization. This is
        // useful mostly for investigating corrupted wallets.
        FileInputStream stream = new FileInputStream(walletFile);
        try {
            Protos.Wallet proto = WalletProtobufSerializer.parseToProto(stream);
            proto = attemptHexConversion(proto);
            System.out.println(proto.toString());
            return;
        } finally {
            stream.close();
        }
    }

    InputStream walletInputStream = null;
    try {
        WalletProtobufSerializer loader = new WalletProtobufSerializer();
        if (options.has("ignore-mandatory-extensions"))
            loader.setRequireMandatoryExtensions(false);
        walletInputStream = new BufferedInputStream(new FileInputStream(walletFile));
        wallet = loader.readWallet(walletInputStream);
        if (!wallet.getParams().equals(params)) {
            System.err.println("Wallet does not match requested network parameters: "
                    + wallet.getParams().getId() + " vs " + params.getId());
            return;
        }
    } catch (Exception e) {
        System.err.println("Failed to load wallet '" + walletFile + "': " + e.getMessage());
        e.printStackTrace();
        return;
    } finally {
        if (walletInputStream != null) {
            walletInputStream.close();
        }
    }

    // What should we do?
    switch (action) {
    case DUMP:
        dumpWallet();
        break;
    case ADD_KEY:
        addKey();
        break;
    case ADD_ADDR:
        addAddr();
        break;
    case DELETE_KEY:
        deleteKey();
        break;
    case RESET:
        reset();
        break;
    case SYNC:
        syncChain();
        break;
    case SEND:
        if (options.has(paymentRequestLocation) && options.has(outputFlag)) {
            System.err.println("--payment-request and --output cannot be used together.");
            return;
        } else if (options.has(outputFlag)) {
            Coin fee = Coin.ZERO;
            if (options.has("fee")) {
                fee = parseCoin((String) options.valueOf("fee"));
            }
            String lockTime = null;
            if (options.has("locktime")) {
                lockTime = (String) options.valueOf("locktime");
            }
            boolean allowUnconfirmed = options.has("allow-unconfirmed");
            send(outputFlag.values(options), fee, lockTime, allowUnconfirmed);
        } else if (options.has(paymentRequestLocation)) {
            sendPaymentRequest(paymentRequestLocation.value(options), !options.has("no-pki"));
        } else {
            System.err.println("You must specify a --payment-request or at least one --output=addr:value.");
            return;
        }
        break;
    case ENCRYPT:
        encrypt();
        break;
    case DECRYPT:
        decrypt();
        break;
    case MARRY:
        marry();
        break;
    case ROTATE:
        rotate();
        break;
    }

    if (!wallet.isConsistent()) {
        System.err.println("************** WALLET IS INCONSISTENT *****************");
        return;
    }

    saveWallet(walletFile);

    if (options.has(waitForFlag)) {
        WaitForEnum value;
        try {
            value = waitForFlag.value(options);
        } catch (Exception e) {
            System.err.println("Could not understand the --waitfor flag: Valid options are WALLET_TX, BLOCK, "
                    + "BALANCE and EVER");
            return;
        }
        wait(value);
        if (!wallet.isConsistent()) {
            System.err.println("************** WALLET IS INCONSISTENT *****************");
            return;
        }
        saveWallet(walletFile);
    }
    shutdown();
}