Example usage for java.lang String equals

List of usage examples for java.lang String equals

Introduction

In this page you can find the example usage for java.lang String equals.

Prototype

public boolean equals(Object anObject) 

Source Link

Document

Compares this string to the specified object.

Usage

From source file:Unsigned.java

public static void main(String[] args) {
    String result;
    BinaryFormat format = new BinaryFormat();
    format.setDivider(" ");

    // byte//from   w w  w. jav  a  2 s .c  o  m
    byte bNumber = 0x33;
    result = format.format(bNumber);
    if (result.equals("0 0 1 1 0 0 1 1")) {
        System.out.print("Success => ");
    } else {
        System.out.print("FAILURE => ");
    }
    System.out.println("Byte: " + bNumber + " (" + result + ")");

    // byte
    bNumber = (byte) 0x85;
    result = format.format(bNumber);
    if (result.equals("1 0 0 0 0 1 0 1")) {
        System.out.print("Success => ");
    } else {
        System.out.print("FAILURE => ");
    }
    System.out.println("Byte: " + bNumber + " (" + result + ")");

    // short
    short sNumber = (short) 0xa2b6;
    result = format.format(sNumber);
    if (result.equals("1 0 1 0 0 0 1 0 1 0 1 1 0 1 1 0")) {
        System.out.print("Success => ");
    } else {
        System.out.print("FAILURE => ");
    }
    System.out.println("Byte: " + sNumber + " (" + result + ")");

    // int
    format.setDivider("");
    int iNumber = (int) 0x4321fedc;
    result = format.format(iNumber);
    if (result.equals("01000011001000011111111011011100")) {
        System.out.print("Success => ");
    } else {
        System.out.print("FAILURE => ");
    }
    System.out.println("Byte: " + iNumber + " (" + result + ")");

    // long
    format.setDivider("");
    long lNumber = (long) 0x4321fedc4321fedcL;
    result = format.format(lNumber);
    if (result.equals("0100001100100001111111101101110001000011001000011111111011011100")) {
        System.out.print("Success => ");
    } else {
        System.out.print("FAILURE => ");
    }
    System.out.println("Byte: " + lNumber + " (" + result + ")");
}

From source file:cz.cuni.mff.ufal.dspace.app.MoveItems.java

/**
 * main method to run the MoveItems action
 * //from www  .  ja va2s .c o  m
 * @param argv
 *            the command line arguments given
 * @throws SQLException
 */
public static void main(String[] argv) throws SQLException {
    // Create an options object and populate it
    CommandLineParser parser = new PosixParser();

    Options options = new Options();

    options.addOption("l", "list", false, "list collections");
    options.addOption("s", "source", true, "source collection ID");
    options.addOption("t", "target", true, "target collection ID");
    options.addOption("i", "inherit", false, "inherit target collection privileges (default false)");
    options.addOption("h", "help", false, "help");

    // Parse the command line arguments
    CommandLine line;
    try {
        line = parser.parse(options, argv);
    } catch (ParseException pe) {
        System.err.println("Error parsing command line arguments: " + pe.getMessage());
        System.exit(1);
        return;
    }

    if (line.hasOption('h') || line.getOptions().length == 0) {
        printHelp(options, 0);
    }

    // Create a context
    Context context;
    try {
        context = new Context();
        context.turnOffAuthorisationSystem();
    } catch (Exception e) {
        System.err.println("Unable to create a new DSpace Context: " + e.getMessage());
        System.exit(1);
        return;
    }

    if (line.hasOption('l')) {
        listCollections(context);
        System.exit(0);
    }

    // Check a filename is given
    if (!line.hasOption('s')) {
        System.err.println("Required parameter -s missing!");
        printHelp(options, 1);
    }

    Boolean inherit;

    // Check a filename is given
    if (line.hasOption('i')) {
        inherit = true;
    } else {
        inherit = false;
    }

    String sourceCollectionIdParam = line.getOptionValue('s');
    Integer sourceCollectionId = null;

    if (sourceCollectionIdParam.matches("\\d+")) {
        sourceCollectionId = Integer.valueOf(sourceCollectionIdParam);
    } else {
        System.err.println("Invalid argument for parameter -s: " + sourceCollectionIdParam);
        printHelp(options, 1);
    }

    // Check source collection ID is given
    if (!line.hasOption('t')) {
        System.err.println("Required parameter -t missing!");
        printHelp(options, 1);
    }
    String targetCollectionIdParam = line.getOptionValue('t');
    Integer targetCollectionId = null;

    if (targetCollectionIdParam.matches("\\d+")) {
        targetCollectionId = Integer.valueOf(targetCollectionIdParam);
    } else {
        System.err.println("Invalid argument for parameter -t: " + targetCollectionIdParam);
        printHelp(options, 1);
    }

    // Check target collection ID is given
    if (targetCollectionIdParam.equals(sourceCollectionIdParam)) {
        System.err.println("Source collection id and target collection id must differ");
        printHelp(options, 1);
    }

    try {

        moveItems(context, sourceCollectionId, targetCollectionId, inherit);

        // Finish off and tidy up
        context.restoreAuthSystemState();
        context.complete();
    } catch (Exception e) {
        context.abort();
        System.err.println("Error committing changes to database: " + e.getMessage());
        System.err.println("Aborting most recent changes.");
        System.exit(1);
    }
}

From source file:Counter.java

/** Main program entry point. */
public static void main(String argv[]) {

    // is there anything to do?
    if (argv.length == 0) {
        printUsage();//  w w  w. j  av  a  2s  .  c  o  m
        System.exit(1);
    }

    // variables
    Counter counter = new Counter();
    PrintWriter out = new PrintWriter(System.out);
    ParserWrapper parser = null;
    int repetition = DEFAULT_REPETITION;
    boolean namespaces = DEFAULT_NAMESPACES;
    boolean validation = DEFAULT_VALIDATION;
    boolean schemaValidation = DEFAULT_SCHEMA_VALIDATION;
    boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING;
    boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS;
    boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS;
    boolean dynamicValidation = DEFAULT_DYNAMIC_VALIDATION;
    boolean xincludeProcessing = DEFAULT_XINCLUDE;
    boolean xincludeFixupBaseURIs = DEFAULT_XINCLUDE_FIXUP_BASE_URIS;
    boolean xincludeFixupLanguage = DEFAULT_XINCLUDE_FIXUP_LANGUAGE;

    // process arguments
    for (int i = 0; i < argv.length; i++) {
        String arg = argv[i];
        if (arg.startsWith("-")) {
            String option = arg.substring(1);
            if (option.equals("p")) {
                // get parser name
                if (++i == argv.length) {
                    System.err.println("error: Missing argument to -p option.");
                }
                String parserName = argv[i];

                // create parser
                try {
                    parser = (ParserWrapper) Class.forName(parserName).newInstance();
                } catch (Exception e) {
                    parser = null;
                    System.err.println("error: Unable to instantiate parser (" + parserName + ")");
                }
                continue;
            }
            if (option.equals("x")) {
                if (++i == argv.length) {
                    System.err.println("error: Missing argument to -x option.");
                    continue;
                }
                String number = argv[i];
                try {
                    int value = Integer.parseInt(number);
                    if (value < 1) {
                        System.err.println("error: Repetition must be at least 1.");
                        continue;
                    }
                    repetition = value;
                } catch (NumberFormatException e) {
                    System.err.println("error: invalid number (" + number + ").");
                }
                continue;
            }
            if (option.equalsIgnoreCase("n")) {
                namespaces = option.equals("n");
                continue;
            }
            if (option.equalsIgnoreCase("v")) {
                validation = option.equals("v");
                continue;
            }
            if (option.equalsIgnoreCase("s")) {
                schemaValidation = option.equals("s");
                continue;
            }
            if (option.equalsIgnoreCase("f")) {
                schemaFullChecking = option.equals("f");
                continue;
            }
            if (option.equalsIgnoreCase("hs")) {
                honourAllSchemaLocations = option.equals("hs");
                continue;
            }
            if (option.equalsIgnoreCase("va")) {
                validateAnnotations = option.equals("va");
                continue;
            }
            if (option.equalsIgnoreCase("dv")) {
                dynamicValidation = option.equals("dv");
                continue;
            }
            if (option.equalsIgnoreCase("xi")) {
                xincludeProcessing = option.equals("xi");
                continue;
            }
            if (option.equalsIgnoreCase("xb")) {
                xincludeFixupBaseURIs = option.equals("xb");
                continue;
            }
            if (option.equalsIgnoreCase("xl")) {
                xincludeFixupLanguage = option.equals("xl");
                continue;
            }
            if (option.equals("h")) {
                printUsage();
                continue;
            }
        }

        // use default parser?
        if (parser == null) {

            // create parser
            try {
                parser = (ParserWrapper) Class.forName(DEFAULT_PARSER_NAME).newInstance();
            } catch (Exception e) {
                System.err.println("error: Unable to instantiate parser (" + DEFAULT_PARSER_NAME + ")");
                continue;
            }
        }

        // set parser features
        try {
            parser.setFeature(NAMESPACES_FEATURE_ID, namespaces);
        } catch (SAXException e) {
            System.err.println("warning: Parser does not support feature (" + NAMESPACES_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(VALIDATION_FEATURE_ID, validation);
        } catch (SAXException e) {
            System.err.println("warning: Parser does not support feature (" + VALIDATION_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(SCHEMA_VALIDATION_FEATURE_ID, schemaValidation);
        } catch (SAXException e) {
            System.err
                    .println("warning: Parser does not support feature (" + SCHEMA_VALIDATION_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
        } catch (SAXException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
        } catch (SAXException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        }
        try {
            parser.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
        } catch (SAXException e) {
            System.err.println("warning: Parser does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        }
        try {
            parser.setFeature(DYNAMIC_VALIDATION_FEATURE_ID, dynamicValidation);
        } catch (SAXException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + DYNAMIC_VALIDATION_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(XINCLUDE_FEATURE_ID, xincludeProcessing);
        } catch (SAXException e) {
            System.err.println("warning: Parser does not support feature (" + XINCLUDE_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID, xincludeFixupBaseURIs);
        } catch (SAXException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID, xincludeFixupLanguage);
        } catch (SAXException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID + ")");
        }

        // parse file
        try {
            long beforeParse = System.currentTimeMillis();
            Document document = null;
            for (int j = 0; j < repetition; j++) {
                document = parser.parse(arg);
            }
            long afterParse = System.currentTimeMillis();
            long parse = afterParse - beforeParse;

            ParserWrapper.DocumentInfo documentInfo = parser.getDocumentInfo();
            counter.setDocumentInfo(documentInfo);

            long beforeTraverse1 = System.currentTimeMillis();
            counter.count(document);
            long afterTraverse1 = System.currentTimeMillis();
            long traverse1 = afterTraverse1 - beforeTraverse1;

            long beforeTraverse2 = System.currentTimeMillis();
            counter.count(document);
            long afterTraverse2 = System.currentTimeMillis();
            long traverse2 = afterTraverse2 - beforeTraverse2;
            counter.printResults(out, arg, parse, traverse1, traverse2, repetition);
        } catch (SAXParseException e) {
            // ignore
        } catch (Exception e) {
            System.err.println("error: Parse error occurred - " + e.getMessage());
            Exception se = e;
            if (e instanceof SAXException) {
                se = ((SAXException) e).getException();
            }
            if (se != null)
                se.printStackTrace(System.err);
            else
                e.printStackTrace(System.err);
        }
    }

}

From source file:herddb.server.ServerMain.java

public static void main(String... args) {
    try {/*  w  w  w . ja  v a2  s.  com*/
        LOG.log(Level.INFO, "Starting HerdDB version {0}", herddb.utils.Version.getVERSION());
        Properties configuration = new Properties();

        boolean configFileFromParameter = false;
        for (int i = 0; i < args.length; i++) {
            String arg = args[i];
            if (!arg.startsWith("-")) {
                File configFile = new File(args[i]).getAbsoluteFile();
                LOG.log(Level.INFO, "Reading configuration from {0}", configFile);
                try (InputStreamReader reader = new InputStreamReader(new FileInputStream(configFile),
                        StandardCharsets.UTF_8)) {
                    configuration.load(reader);
                }
                configFileFromParameter = true;
            } else if (arg.equals("--use-env")) {
                System.getenv().forEach((key, value) -> {
                    System.out.println("Considering env as system property " + key + " -> " + value);
                    System.setProperty(key, value);
                });
            } else if (arg.startsWith("-D")) {
                int equals = arg.indexOf('=');
                if (equals > 0) {
                    String key = arg.substring(2, equals);
                    String value = arg.substring(equals + 1);
                    System.setProperty(key, value);
                }
            }
        }
        if (!configFileFromParameter) {
            File configFile = new File("conf/server.properties").getAbsoluteFile();
            LOG.log(Level.INFO, "Reading configuration from {0}", configFile);
            if (configFile.isFile()) {
                try (InputStreamReader reader = new InputStreamReader(new FileInputStream(configFile),
                        StandardCharsets.UTF_8)) {
                    configuration.load(reader);
                }
            }
        }

        System.getProperties().forEach((k, v) -> {
            String key = k + "";
            if (!key.startsWith("java") && !key.startsWith("user")) {
                configuration.put(k, v);
            }
        });

        LogManager.getLogManager().readConfiguration();

        Runtime.getRuntime().addShutdownHook(new Thread("ctrlc-hook") {

            @Override
            public void run() {
                System.out.println("Ctrl-C trapped. Shutting down");
                ServerMain _brokerMain = runningInstance;
                if (_brokerMain != null) {
                    _brokerMain.close();
                }
            }

        });
        runningInstance = new ServerMain(configuration);
        runningInstance.start();

        runningInstance.join();

    } catch (Throwable t) {
        t.printStackTrace();
        System.exit(1);
    }
}

From source file:com.github.chrbayer84.keybits.KeyBits.java

/**
 * @param args/*  w  w w  .  ja v  a2s.  co m*/
 */
public static void main(String[] args) throws Exception {
    int number_of_addresses = 1;
    int depth = 1;

    String usage = "java -jar KeyBits.jar [options]";
    // create parameters which can be chosen
    Option help = new Option("h", "print this message");
    Option verbose = new Option("v", "verbose");
    Option exprt = new Option("e", "export public key to blockchain");
    Option imprt = OptionBuilder.withArgName("string").hasArg()
            .withDescription("import public key from blockchain").create("i");

    Option blockchain_address = OptionBuilder.withArgName("string").hasArg().withDescription("bitcoin address")
            .create("a");
    Option create_wallet = OptionBuilder.withArgName("file name").hasArg().withDescription("create wallet")
            .create("c");
    Option update_wallet = OptionBuilder.withArgName("file name").hasArg().withDescription("update wallet")
            .create("u");
    Option balance_wallet = OptionBuilder.withArgName("file name").hasArg()
            .withDescription("return balance of wallet").create("b");
    Option show_wallet = OptionBuilder.withArgName("file name").hasArg()
            .withDescription("show content of wallet").create("w");
    Option send_coins = OptionBuilder.withArgName("file name").hasArg().withDescription("send satoshis")
            .create("s");
    Option monitor_pending = OptionBuilder.withArgName("file name").hasArg()
            .withDescription("monitor pending transactions of wallet").create("p");
    Option monitor_depth = OptionBuilder.withArgName("file name").hasArg()
            .withDescription("monitor transaction depths of wallet").create("d");
    Option number = OptionBuilder.withArgName("integer").hasArg()
            .withDescription("in combination with -c, -d, -r or -s").create("n");
    Option reset = OptionBuilder.withArgName("file name").hasArg().withDescription("reset wallet").create("r");

    Options options = new Options();

    options.addOption(help);
    options.addOption(verbose);
    options.addOption(imprt);
    options.addOption(exprt);

    options.addOption(blockchain_address);
    options.addOption(create_wallet);
    options.addOption(update_wallet);
    options.addOption(balance_wallet);
    options.addOption(show_wallet);
    options.addOption(send_coins);
    options.addOption(monitor_pending);
    options.addOption(monitor_depth);
    options.addOption(number);
    options.addOption(reset);

    BasicParser parser = new BasicParser();
    CommandLine cmd = null;

    String header = "This is KeyBits v0.01b.1412953962" + System.getProperty("line.separator");
    // show help if wrong usage
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        printHelp(usage, options, header);
    }

    if (cmd.getOptions().length == 0)
        printHelp(usage, options, header);

    if (cmd.hasOption("h"))
        printHelp(usage, options, header);

    if (cmd.hasOption("v"))
        System.out.println(header);

    if (cmd.hasOption("c") && cmd.hasOption("n"))
        number_of_addresses = new Integer(cmd.getOptionValue("n")).intValue();

    if (cmd.hasOption("d") && cmd.hasOption("n"))
        depth = new Integer(cmd.getOptionValue("n")).intValue();

    String checkpoints_file_name = "checkpoints";
    if (!new File(checkpoints_file_name).exists())
        checkpoints_file_name = null;

    // ---------------------------------------------------------------------

    if (cmd.hasOption("c")) {
        String wallet_file_name = cmd.getOptionValue("c");

        String passphrase = HelpfulStuff.insertPassphrase("enter password for " + wallet_file_name);
        if (!new File(wallet_file_name).exists()) {
            String passphrase_ = HelpfulStuff.reInsertPassphrase("enter password for " + wallet_file_name);

            if (!passphrase.equals(passphrase_)) {
                System.out.println("passwords do not match");
                System.exit(0);
            }
        }

        MyWallet.createWallet(wallet_file_name, wallet_file_name + ".chain", number_of_addresses, passphrase);
        System.exit(0);
    }

    if (cmd.hasOption("u")) {
        String wallet_file_name = cmd.getOptionValue("u");
        MyWallet.updateWallet(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name);
        System.exit(0);
    }

    if (cmd.hasOption("b")) {
        String wallet_file_name = cmd.getOptionValue("b");
        System.out.println(
                MyWallet.getBalanceOfWallet(wallet_file_name, wallet_file_name + ".chain").longValue());
        System.exit(0);
    }

    if (cmd.hasOption("w")) {
        String wallet_file_name = cmd.getOptionValue("w");
        System.out.println(MyWallet.showContentOfWallet(wallet_file_name, wallet_file_name + ".chain"));
        System.exit(0);
    }

    if (cmd.hasOption("p")) {
        System.out.println("monitoring of pending transactions ... ");
        String wallet_file_name = cmd.getOptionValue("p");
        MyWallet.monitorPendingTransactions(wallet_file_name, wallet_file_name + ".chain",
                checkpoints_file_name);
        System.exit(0);
    }

    if (cmd.hasOption("d")) {
        System.out.println("monitoring of transaction depth ... ");
        String wallet_file_name = cmd.getOptionValue("d");
        MyWallet.monitorTransactionDepth(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name,
                depth);
        System.exit(0);
    }

    if (cmd.hasOption("r") && cmd.hasOption("n")) {
        long epoch = new Long(cmd.getOptionValue("n"));
        System.out.println("resetting wallet ... ");
        String wallet_file_name = cmd.getOptionValue("r");

        File chain_file = (new File(wallet_file_name + ".chain"));
        if (chain_file.exists())
            chain_file.delete();

        MyWallet.setCreationTime(wallet_file_name, epoch);
        MyWallet.updateWallet(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name);

        System.exit(0);
    }

    if (cmd.hasOption("s") && cmd.hasOption("a") && cmd.hasOption("n")) {
        String wallet_file_name = cmd.getOptionValue("s");
        String address = cmd.getOptionValue("a");
        Integer amount = new Integer(cmd.getOptionValue("n"));

        String wallet_passphrase = HelpfulStuff.insertPassphrase("enter password for " + wallet_file_name);
        MyWallet.sendCoins(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name, address,
                new BigInteger(amount + ""), wallet_passphrase);

        System.out.println("waiting ...");
        Thread.sleep(10000);
        System.out.println("monitoring of transaction depth ... ");
        MyWallet.monitorTransactionDepth(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name,
                1);
        System.out.println("transaction fixed in blockchain with depth " + depth);
        System.exit(0);
    }

    // ----------------------------------------------------------------------------------------
    //                                  creates public key
    // ----------------------------------------------------------------------------------------

    GnuPGP gpg = new GnuPGP();

    if (cmd.hasOption("e")) {
        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
        String line = null;
        StringBuffer sb = new StringBuffer();
        while ((line = input.readLine()) != null)
            sb.append(line + "\n");

        PGPPublicKeyRing public_key_ring = gpg.getDearmored(sb.toString());
        //System.out.println(gpg.showPublicKeys(public_key_ring));

        byte[] public_key_ring_encoded = gpg.getEncoded(public_key_ring);

        String[] addresses = (new Encoding()).encodePublicKey(public_key_ring_encoded);
        //         System.out.println(gpg.showPublicKey(gpg.getDecoded(encoding.decodePublicKey(addresses))));

        // file names for message
        String public_key_file_name = Long.toHexString(public_key_ring.getPublicKey().getKeyID()) + ".wallet";
        String public_key_wallet_file_name = public_key_file_name;
        String public_key_chain_file_name = public_key_wallet_file_name + ".chain";

        // hier muss dass passwort noch nach encodeAddresses weitergeleitet werden da sonst zweimal abfrage
        String public_key_wallet_passphrase = HelpfulStuff
                .insertPassphrase("enter password for " + public_key_wallet_file_name);
        if (!new File(public_key_wallet_file_name).exists()) {
            String public_key_wallet_passphrase_ = HelpfulStuff
                    .reInsertPassphrase("enter password for " + public_key_wallet_file_name);

            if (!public_key_wallet_passphrase.equals(public_key_wallet_passphrase_)) {
                System.out.println("passwords do not match");
                System.exit(0);
            }
        }

        MyWallet.createWallet(public_key_wallet_file_name, public_key_chain_file_name, 1,
                public_key_wallet_passphrase);
        MyWallet.updateWallet(public_key_wallet_file_name, public_key_chain_file_name, checkpoints_file_name);
        String public_key_address = MyWallet.getAddress(public_key_wallet_file_name, public_key_chain_file_name,
                0);
        System.out.println("address of public key: " + public_key_address);

        // 10000 additional satoshis for sending transaction to address of recipient of message and 10000 for fees
        KeyBits.encodeAddresses(public_key_wallet_file_name, public_key_chain_file_name, checkpoints_file_name,
                addresses, 2 * SendRequest.DEFAULT_FEE_PER_KB.intValue(), depth, public_key_wallet_passphrase);
    }

    if (cmd.hasOption("i")) {
        String location = cmd.getOptionValue("i");

        String[] addresses = null;
        if (location.indexOf(",") > -1) {
            String[] locations = location.split(",");
            addresses = MyWallet.getAddressesFromBlockAndTransaction("main.wallet", "main.wallet.chain",
                    checkpoints_file_name, locations[0], locations[1]);
        } else {
            addresses = BlockchainDotInfo.getKeys(location);
        }

        byte[] encoded = (new Encoding()).decodePublicKey(addresses);
        PGPPublicKeyRing public_key_ring = gpg.getDecoded(encoded);

        System.out.println(gpg.getArmored(public_key_ring));

        System.exit(0);
    }
}

From source file:com.clustercontrol.infra.util.JschUtil.java

public static void main(String args[]) {
    ModuleNodeResult result = null;//from w ww .  j av  a  2 s . c om
    String user = "root";
    String pass = "";
    String keypath = null;
    String passphrase = "";
    String host = "";
    String orgFilename = "build.xml"; // HinemosManager???
    int port = 22;
    int timeout = 5 * 1000;

    // 
    System.out.println(HinemosTime.getDateString() + " === exec command ===");
    result = execCommand(user, pass, host, port, timeout, "hostname", CommandModuleInfo.MESSAGE_SIZE, keypath,
            passphrase);
    System.out.println(HinemosTime.getDateString() + " result, ok/ng="
            + (result.getResult() == OkNgConstant.TYPE_OK ? "OK" : "NG") + ", message=" + result.getMessage());

    // ?
    System.out.println(HinemosTime.getDateString() + " === send file ===");
    String remoteFilename = orgFilename + ".remoteaaa";
    result = sendFile(user, pass, host, port, timeout, ".", orgFilename, ".", remoteFilename, "hinemos", "0644",
            true, keypath, passphrase);
    System.out.println(HinemosTime.getDateString() + " result, ok/ng="
            + (result.getResult() == OkNgConstant.TYPE_OK ? "OK" : "NG") + ", message=" + result.getMessage());

    // ?
    System.out.println(HinemosTime.getDateString() + " === receive file ===");
    String localFilename = orgFilename + ".local";
    result = recvFile(user, pass, host, port, timeout, ".", remoteFilename, ".", localFilename, "hinemos",
            "0644", keypath, passphrase);
    System.out.println(HinemosTime.getDateString() + " result, ok/ng="
            + (result.getResult() == OkNgConstant.TYPE_OK ? "OK" : "NG") + ", message=" + result.getMessage());

    // ?MD5Sum??
    System.out.println(HinemosTime.getDateString() + " === compare ===");
    long orgFilesize = new File(orgFilename).length();
    long newfilesize = new File(localFilename).length();
    if (orgFilesize == newfilesize) {
        String orgCheckSum = FileTransferModuleInfo.getCheckSum(orgFilename);
        String newCheckSum = FileTransferModuleInfo.getCheckSum(localFilename);
        if (orgCheckSum.equals(newCheckSum)) {
            System.out.println(HinemosTime.getDateString() + " result, ok/ng=OK, size=" + orgFilesize);
        } else {
            System.out.println(HinemosTime.getDateString() + " result, ok/ng=NG, org.checksum=" + orgCheckSum
                    + ", new.checksum=" + newCheckSum);
        }
    } else {
        System.out.println(HinemosTime.getDateString() + " result, ok/ng=NG, org.size=" + orgFilesize
                + ", new.size=" + newfilesize);
    }
}

From source file:com.netscape.cmstools.CMCSharedToken.java

public static void main(String args[]) throws Exception {
    boolean isVerificationMode = false; // developer debugging only

    Options options = createOptions();// w w w  . j  a v a  2  s  . c  o  m
    CommandLine cmd = null;

    try {
        CommandLineParser parser = new PosixParser();
        cmd = parser.parse(options, args);

    } catch (Exception e) {
        printError(e.getMessage());
        System.exit(1);
    }

    if (cmd.hasOption("help")) {
        printHelp();
        System.exit(0);
    }

    boolean verbose = cmd.hasOption("v");

    String databaseDir = cmd.getOptionValue("d", ".");
    String passphrase = cmd.getOptionValue("s");
    if (passphrase == null) {
        printError("Missing passphrase");
        System.exit(1);
    }
    if (verbose) {
        System.out.println("passphrase String = " + passphrase);
        System.out.println("passphrase UTF-8 bytes = ");
        System.out.println(Arrays.toString(passphrase.getBytes("UTF-8")));
    }
    String tokenName = cmd.getOptionValue("h");
    String tokenPassword = cmd.getOptionValue("p");

    String issuanceProtCertFilename = cmd.getOptionValue("b");
    String issuanceProtCertNick = cmd.getOptionValue("n");
    String output = cmd.getOptionValue("o");

    try {
        CryptoManager.initialize(databaseDir);

        CryptoManager manager = CryptoManager.getInstance();

        CryptoToken token = CryptoUtil.getKeyStorageToken(tokenName);
        tokenName = token.getName();
        manager.setThreadToken(token);

        Password password = new Password(tokenPassword.toCharArray());
        token.login(password);

        X509Certificate issuanceProtCert = null;
        if (issuanceProtCertFilename != null) {
            if (verbose)
                System.out.println("Loading issuance protection certificate");
            String encoded = new String(Files.readAllBytes(Paths.get(issuanceProtCertFilename)));
            byte[] issuanceProtCertData = Cert.parseCertificate(encoded);

            issuanceProtCert = manager.importCACertPackage(issuanceProtCertData);
            if (verbose)
                System.out.println("issuance protection certificate imported");
        } else {
            // must have issuance protection cert nickname if file not provided
            if (verbose)
                System.out.println("Getting cert by nickname: " + issuanceProtCertNick);
            if (issuanceProtCertNick == null) {
                System.out.println(
                        "Invallid command: either nickname or PEM file must be provided for Issuance Protection Certificate");
                System.exit(1);
            }
            issuanceProtCert = getCertificate(tokenName, issuanceProtCertNick);
        }

        EncryptionAlgorithm encryptAlgorithm = EncryptionAlgorithm.AES_128_CBC_PAD;
        KeyWrapAlgorithm wrapAlgorithm = KeyWrapAlgorithm.RSA;

        if (verbose)
            System.out.println("Generating session key");
        SymmetricKey sessionKey = CryptoUtil.generateKey(token, KeyGenAlgorithm.AES, 128, null, true);

        if (verbose)
            System.out.println("Encrypting passphrase");
        byte iv[] = { 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1 };
        byte[] secret_data = CryptoUtil.encryptUsingSymmetricKey(token, sessionKey,
                passphrase.getBytes("UTF-8"), encryptAlgorithm, new IVParameterSpec(iv));

        if (verbose)
            System.out.println("Wrapping session key with issuance protection cert");
        byte[] issuanceProtWrappedSessionKey = CryptoUtil.wrapUsingPublicKey(token,
                issuanceProtCert.getPublicKey(), sessionKey, wrapAlgorithm);

        // final_data takes this format:
        // SEQUENCE {
        //     encryptedSession OCTET STRING,
        //     encryptedPrivate OCTET STRING
        // }

        DerOutputStream tmp = new DerOutputStream();

        tmp.putOctetString(issuanceProtWrappedSessionKey);
        tmp.putOctetString(secret_data);
        DerOutputStream out = new DerOutputStream();
        out.write(DerValue.tag_Sequence, tmp);

        byte[] final_data = out.toByteArray();
        String final_data_b64 = Utils.base64encode(final_data, true);
        if (final_data_b64 != null) {
            System.out.println("\nEncrypted Secret Data:");
            System.out.println(final_data_b64);
        } else
            System.out.println("Failed to produce final data");

        if (output != null) {
            System.out.println("\nStoring Base64 secret data into " + output);
            try (FileWriter fout = new FileWriter(output)) {
                fout.write(final_data_b64);
            }
        }

        if (isVerificationMode) { // developer use only
            PrivateKey wrappingKey = null;
            if (issuanceProtCertNick != null)
                wrappingKey = (org.mozilla.jss.crypto.PrivateKey) getPrivateKey(tokenName,
                        issuanceProtCertNick);
            else
                wrappingKey = CryptoManager.getInstance().findPrivKeyByCert(issuanceProtCert);

            System.out.println("\nVerification begins...");
            byte[] wrapped_secret_data = Utils.base64decode(final_data_b64);
            DerValue wrapped_val = new DerValue(wrapped_secret_data);
            // val.tag == DerValue.tag_Sequence
            DerInputStream wrapped_in = wrapped_val.data;
            DerValue wrapped_dSession = wrapped_in.getDerValue();
            byte wrapped_session[] = wrapped_dSession.getOctetString();
            System.out.println("wrapped session key retrieved");
            DerValue wrapped_dPassphrase = wrapped_in.getDerValue();
            byte wrapped_passphrase[] = wrapped_dPassphrase.getOctetString();
            System.out.println("wrapped passphrase retrieved");

            SymmetricKey ver_session = CryptoUtil.unwrap(token, SymmetricKey.AES, 128,
                    SymmetricKey.Usage.UNWRAP, wrappingKey, wrapped_session, wrapAlgorithm);
            byte[] ver_passphrase = CryptoUtil.decryptUsingSymmetricKey(token, new IVParameterSpec(iv),
                    wrapped_passphrase, ver_session, encryptAlgorithm);

            String ver_spassphrase = new String(ver_passphrase, "UTF-8");

            CryptoUtil.obscureBytes(ver_passphrase, "random");

            System.out.println("ver_passphrase String = " + ver_spassphrase);
            System.out.println("ver_passphrase UTF-8 bytes = ");
            System.out.println(Arrays.toString(ver_spassphrase.getBytes("UTF-8")));

            if (ver_spassphrase.equals(passphrase))
                System.out.println("Verification success!");
            else
                System.out.println("Verification failure! ver_spassphrase=" + ver_spassphrase);
        }

    } catch (Exception e) {
        if (verbose)
            e.printStackTrace();
        printError(e.getMessage());
        System.exit(1);
    }
}

From source file:com.ibm.watson.app.common.tools.services.classifier.TrainClassifier.java

public static void main(String[] args) throws Exception {
    Option urlOption = createOption(URL_OPTION, URL_OPTION_LONG, true,
            "The absolute URL of the NL classifier service to connect to. If omitted, the default will be used ("
                    + DEFAULT_URL + ")",
            false, "url");
    Option usernameOption = createOption(USERNAME_OPTION, USERNAME_OPTION_LONG, true,
            "The username to use during authentication to the NL classifier service", true, "username");
    Option passwordOption = createOption(PASSWORD_OPTION, PASSWORD_OPTION_LONG, true,
            "The password to use during authentication to the NL classifier service", true, "password");
    Option fileOption = createOption(FILE_OPTION, FILE_OPTION_LONG, true,
            "The filepath to be used as training data", false, "file");
    Option deleteOption = createOption(DELETE_OPTION, DELETE_OPTION_LONG, false,
            "If specified, the classifier instance will be deleted if training is not successful");

    final Options options = buildOptions(urlOption, usernameOption, passwordOption, fileOption, deleteOption);

    CommandLine cmd;/*from  w w w  .  ja  v a  2  s.c om*/
    try {
        CommandLineParser parser = new GnuParser();
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.err.println(MessageKey.AQWEGA14016E_could_not_parse_cmd_line_args_1.getMessage(e.getMessage())
                .getFormattedMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(120, "java " + TrainClassifier.class.getName(), null, options, null);
        return;
    }

    final String url = cmd.hasOption(URL_OPTION) ? cmd.getOptionValue(URL_OPTION) : DEFAULT_URL;
    final String username = cmd.getOptionValue(USERNAME_OPTION).trim();
    final String password = cmd.getOptionValue(PASSWORD_OPTION).trim();

    if (username.isEmpty() || password.isEmpty()) {
        throw new IllegalArgumentException(
                MessageKey.AQWEGA14014E_username_and_password_cannot_empty.getMessage().getFormattedMessage());
    }

    final NLClassifierRestClient client = new NLClassifierRestClient(url, username, password);

    listClassifiers(client);
    System.out.println(MessageKey.AQWEGA10012I_h_help.getMessage().getFormattedMessage());

    String userInput;
    boolean exit = false;
    NLClassifier classifier = null;
    boolean isTraining = false;

    if (cmd.hasOption(FILE_OPTION)) {
        // File option was specified, go directly to training
        classifier = train(client, cmd.getOptionValue(FILE_OPTION));
        isTraining = true;
    }

    try (final Scanner scanner = new Scanner(System.in)) {
        while (!exit) {
            System.out.print("> ");
            userInput = scanner.nextLine().trim();

            if (userInput.equals("q") || userInput.equals("quit") || userInput.equals("exit")) {
                exit = true;
            } else if (userInput.equals("h") || userInput.equals("help")) {
                printHelp();
            } else if (userInput.equals("l") || userInput.equals("list")) {
                listClassifiers(client);
            } else if (userInput.equals("t") || userInput.equals("train")) {
                if (!isTraining) {
                    System.out.print("Enter filename: ");
                    String filename = scanner.nextLine().trim();
                    classifier = train(client, filename);
                    isTraining = true;
                } else {
                    System.err.println(MessageKey.AQWEGA10013I_t_cannot_used_during_training.getMessage()
                            .getFormattedMessage());
                }
            } else if (userInput.equals("s") || userInput.equals("status")) {
                if (isTraining) {
                    exit = getStatus(client, classifier, cmd.hasOption(DELETE_OPTION));
                } else {
                    System.err.println(MessageKey.AQWEGA10014I_s_can_used_during_training.getMessage()
                            .getFormattedMessage());
                }
            } else if (userInput.equals("c") || userInput.equals("classify")) {
                if (classifier != null && classifier.getStatus().equals(Status.AVAILABLE)) {
                    isTraining = false;
                    System.out.print(MessageKey.AQWEGA10015I_text_classify.getMessage().getFormattedMessage());
                    String text = scanner.nextLine().trim();
                    classify(client, classifier, text);
                } else {
                    System.err.println(MessageKey.AQWEGA10016I_c_can_used_after_training_has_completed
                            .getMessage().getFormattedMessage());
                }
            } else {
                System.err.println(
                        MessageKey.AQWEGA14017E_unknown_command_1.getMessage(userInput).getFormattedMessage());
            }
            Thread.sleep(100); // Give the out / err consoles time to battle it out before printing the command prompt
        }
    }
}

From source file:com.linkedin.cubert.io.rubix.RubixFile.java

public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException,
        ParseException, InstantiationException, IllegalAccessException {
    final int VERBOSE_NUM_ROWS = 4;

    Options options = new Options();

    options.addOption("h", "help", false, "shows this message");
    options.addOption("v", "verbose", false, "print summary and first few rows of each block");
    options.addOption("m", "metadata", false, "show the metadata");
    options.addOption("d", "dump", false,
            "dump the contents of the rubix file. Use -f for specifying format, and -o for specifying "
                    + "output location");
    options.addOption("f", "format", true, "the data format for dumping data (AVRO or TEXT). Default: TEXT");
    options.addOption("e", "extract", true,
            "Extract one or more rubix blocks starting from the given blockId. Use -e blockId,numBlocks "
                    + "for specifying the blocks to be extracted. Use -o for specifying output location");
    options.addOption("o", true, "Store the output at the specified location");

    CommandLineParser parser = new BasicParser();

    // parse the command line arguments
    CommandLine line = parser.parse(options, args);

    // show the help message
    if (line.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(//from w  ww  . j a va  2 s . co m
                "RubixFile <rubix file or dir> [options]\nIf no options are provided, print a summary of the blocks.",
                options);
        return;
    }

    // validate provided options
    if (line.hasOption("d") && line.hasOption("e")) {
        System.err.println("Cannot dump (-d) and extract (-e) at the same time!");
        return;
    }

    // obtain the list of rubix files
    String[] files = line.getArgs();
    if (files == null || files.length == 0) {
        System.err.println("Rubix file not specified");
        return;
    }

    Configuration conf = new JobConf();
    FileSystem fs = FileSystem.get(conf);

    Path path = new Path(files[0]);
    FileStatus[] allFiles;

    FileStatus status = fs.getFileStatus(path);
    if (status.isDir()) {
        allFiles = RubixFile.getRubixFiles(path, fs);
    } else {
        allFiles = new FileStatus[] { status };
    }

    // walk over all files and extract the trailer section
    List<RubixFile<Tuple, Object>> rfiles = new ArrayList<RubixFile<Tuple, Object>>();

    for (FileStatus s : allFiles) {
        Path p = s.getPath();

        RubixFile<Tuple, Object> rfile = new RubixFile<Tuple, Object>(conf, p);

        // if printing meta data information.. exit after first file (since all files
        // have the same meta data)
        if (line.hasOption("m")) {
            rfile.getKeyData();

            System.out.println(new ObjectMapper().writer().writeValueAsString(rfile.metadataJson));
            break;
        }

        rfiles.add(rfile);
    }

    // dump the data
    if (line.hasOption("d")) {
        String format = line.getOptionValue("f");
        if (format == null)
            format = "TEXT";

        format = format.trim().toUpperCase();

        if (format.equals("AVRO")) {
            // dumpAvro(rfiles, line.getOptionValue("o"));
            throw new UnsupportedOperationException(
                    "Dumping to avro is not currently supporting. Please write a Cubert (map-only) script to store data in avro format");
        } else if (format.equals("TEXT")) {
            if (line.hasOption("o")) {
                System.err.println("Dumping TEXT format data *into a file* is not currently supported");
                return;
            }
            dumpText(rfiles, line.getOptionValue("o"), Integer.MAX_VALUE);
        } else {
            System.err.println("Invalid format [" + format + "] for dumping. Please use AVRO or TEXT");
            return;
        }
    }
    // extract arguments: -e blockId,numBlocks(contiguous) -o ouputLocation
    else if (line.hasOption("e")) {
        String extractArguments = line.getOptionValue("e");
        String outputLocation;
        if (line.hasOption("o")) {
            outputLocation = line.getOptionValue("o");
        } else {
            System.err.println("Need to specify the location to store the output");
            return;
        }
        long blockId;
        int numBlocks = 1;
        if (extractArguments.contains(",")) {
            String[] splitExtractArgs = extractArguments.split(",");
            blockId = Long.parseLong(splitExtractArgs[0]);
            numBlocks = Integer.parseInt(splitExtractArgs[1]);
        } else {
            blockId = Long.parseLong(extractArguments);
        }

        extract(rfiles, blockId, numBlocks, outputLocation);
    } else
    // print summary
    {
        dumpText(rfiles, null, line.hasOption("v") ? VERBOSE_NUM_ROWS : 0);
    }
}

From source file:RedPenRunner.java

public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("h", "help", false, "help");
    options.addOption("v", "version", false, "print the version information and exit");

    OptionBuilder.withLongOpt("port");
    OptionBuilder.withDescription("port number");
    OptionBuilder.hasArg();//from w w  w  . jav  a  2  s .co m
    OptionBuilder.withArgName("PORT");
    options.addOption(OptionBuilder.create("p"));

    OptionBuilder.withLongOpt("key");
    OptionBuilder.withDescription("stop key");
    OptionBuilder.hasArg();
    OptionBuilder.withArgName("STOP_KEY");
    options.addOption(OptionBuilder.create("k"));

    OptionBuilder.withLongOpt("conf");
    OptionBuilder.withDescription("configuration file");
    OptionBuilder.hasArg();
    OptionBuilder.withArgName("CONFIG_FILE");
    options.addOption(OptionBuilder.create("c"));

    OptionBuilder.withLongOpt("lang");
    OptionBuilder.withDescription("Language of error messages");
    OptionBuilder.hasArg();
    OptionBuilder.withArgName("LANGUAGE");
    options.addOption(OptionBuilder.create("L"));

    CommandLineParser parser = new BasicParser();
    CommandLine commandLine = null;

    try {
        commandLine = parser.parse(options, args);
    } catch (Exception e) {
        printHelp(options);
        System.exit(-1);
    }

    int portNum = 8080;
    String language = "en";
    if (commandLine.hasOption("h")) {
        printHelp(options);
        System.exit(0);
    }
    if (commandLine.hasOption("v")) {
        System.out.println(RedPen.VERSION);
        System.exit(0);
    }
    if (commandLine.hasOption("p")) {
        portNum = Integer.parseInt(commandLine.getOptionValue("p"));
    }
    if (commandLine.hasOption("L")) {
        language = commandLine.getOptionValue("L");
    }
    if (isPortTaken(portNum)) {
        System.err.println("port is taken...");
        System.exit(1);
    }

    // set language
    if (language.equals("ja")) {
        Locale.setDefault(new Locale("ja", "JA"));
    } else {
        Locale.setDefault(new Locale("en", "EN"));
    }

    final String contextPath = System.getProperty("redpen.home", "/");

    Server server = new Server(portNum);
    ProtectionDomain domain = RedPenRunner.class.getProtectionDomain();
    URL location = domain.getCodeSource().getLocation();

    HandlerList handlerList = new HandlerList();
    if (commandLine.hasOption("key")) {
        // Add Shutdown handler only when STOP_KEY is specified
        ShutdownHandler shutdownHandler = new ShutdownHandler(commandLine.getOptionValue("key"));
        handlerList.addHandler(shutdownHandler);
    }

    WebAppContext webapp = new WebAppContext();
    webapp.setContextPath(contextPath);
    if (location.toExternalForm().endsWith("redpen-server/target/classes/")) {
        // use redpen-server/target/redpen-server instead, because target/classes doesn't contain web resources.
        webapp.setWar(location.toExternalForm() + "../redpen-server/");
    } else {
        webapp.setWar(location.toExternalForm());
    }
    if (commandLine.hasOption("c")) {
        webapp.setInitParameter("redpen.conf.path", commandLine.getOptionValue("c"));
    }

    handlerList.addHandler(webapp);
    server.setHandler(handlerList);

    server.start();
    server.join();
}