Example usage for org.apache.commons.cli ParseException toString

List of usage examples for org.apache.commons.cli ParseException toString

Introduction

In this page you can find the example usage for org.apache.commons.cli ParseException toString.

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:com.netscape.cms.servlet.test.ConfigurationTest.java

public static void main(String args[]) throws Exception {
    String host = null;/*from   w  ww  . j a  v  a 2  s .com*/
    String port = null;
    String cstype = null;
    String token_pwd = null;
    String db_dir = "./";
    String protocol = "https";
    String pin = null;
    String extCertFile = null;
    int testnum = 1;

    // parse command line arguments
    Options options = new Options();
    options.addOption("t", true, "Subsystem type");
    options.addOption("h", true, "Hostname of the CS subsystem");
    options.addOption("p", true, "Port of the CS subsystem");
    options.addOption("w", true, "Token password");
    options.addOption("d", true, "Directory for tokendb");
    options.addOption("s", true, "preop pin");
    options.addOption("e", true, "File for externally signed signing cert");
    options.addOption("x", true, "Test number");

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

        if (cmd.hasOption("t")) {
            cstype = cmd.getOptionValue("t");
        } else {
            System.err.println("Error: no subsystem type provided.");
            usage(options);
        }

        if (cmd.hasOption("h")) {
            host = cmd.getOptionValue("h");
        } else {
            System.err.println("Error: no hostname provided.");
            usage(options);
        }

        if (cmd.hasOption("p")) {
            port = cmd.getOptionValue("p");
        } else {
            System.err.println("Error: no port provided");
            usage(options);
        }

        if (cmd.hasOption("w")) {
            token_pwd = cmd.getOptionValue("w");
        } else {
            System.err.println("Error: no token password provided");
            usage(options);
        }

        if (cmd.hasOption("d")) {
            db_dir = cmd.getOptionValue("d");
        }

        if (cmd.hasOption("s")) {
            pin = cmd.getOptionValue("s");
        }

        if (cmd.hasOption("e")) {
            extCertFile = cmd.getOptionValue("e");
        }

        if (cmd.hasOption("x")) {
            testnum = Integer.parseInt(cmd.getOptionValue("x"));
        }
    } catch (ParseException e) {
        System.err.println("Error in parsing command line options: " + e.getMessage());
        usage(options);
    }

    // Initialize token
    try {
        CryptoManager.initialize(db_dir);
    } catch (AlreadyInitializedException e) {
        // it is ok if it is already initialized
    } catch (Exception e) {
        System.out.println("INITIALIZATION ERROR: " + e.toString());
        System.exit(1);
    }

    // log into token
    CryptoManager manager = null;
    CryptoToken token = null;
    try {
        manager = CryptoManager.getInstance();
        token = manager.getInternalKeyStorageToken();
        Password password = new Password(token_pwd.toCharArray());
        try {
            token.login(password);
        } catch (Exception e) {
            System.out.println("login Exception: " + e.toString());
            if (!token.isLoggedIn()) {
                token.initPassword(password, password);
            }
        }
    } catch (Exception e) {
        System.out.println("Exception in logging into token:" + e.toString());
    }

    SystemConfigClient client = null;
    try {
        ClientConfig config = new ClientConfig();
        config.setServerURL(protocol + "://" + host + ":" + port);

        client = new SystemConfigClient(new PKIClient(config, null), cstype);
    } catch (URISyntaxException e1) {
        e1.printStackTrace();
        System.exit(1);
    }

    ConfigurationRequest data = null;
    switch (testnum) {
    case 1:
        data = constructCAData(host, port, pin, db_dir, token_pwd, token);
        break;
    case 2:
        data = constructCloneCAData(host, port, pin, db_dir, token_pwd, token);
        break;
    case 3:
        data = constructKRAData(host, port, pin, db_dir, token_pwd, token);
        break;
    case 4:
        data = constructOCSPData(host, port, pin, db_dir, token_pwd, token);
        break;
    case 5:
        data = constructTKSData(host, port, pin, db_dir, token_pwd, token);
        break;
    case 6:
        data = constructSubCAData(host, port, pin, db_dir, token_pwd, token);
        break;
    case 7:
        data = constructExternalCADataPart1(host, port, pin, db_dir, token_pwd, token);
        break;
    case 8:
        data = constructExternalCADataPart2(host, port, pin, db_dir, token_pwd, token, extCertFile);
        break;
    default:
        System.out.println("Invalid test");
        System.exit(1);
    }

    ConfigurationResponse response = client.configure(data);

    System.out.println("adminCert: " + response.getAdminCert().getCert());
    List<SystemCertData> certs = response.getSystemCerts();
    Iterator<SystemCertData> iterator = certs.iterator();
    while (iterator.hasNext()) {
        SystemCertData cdata = iterator.next();
        System.out.println("tag: " + cdata.getTag());
        System.out.println("cert: " + cdata.getCert());
        System.out.println("request: " + cdata.getRequest());
    }

}

From source file:com.netscape.cms.servlet.test.DRMTest.java

public static void main(String args[]) throws InvalidKeyException, NoSuchAlgorithmException,
        InvalidKeySpecException, SignatureException, IOException {
    String host = null;// www . j av a  2s . com
    String port = null;
    String token_pwd = null;
    String db_dir = "./";
    String protocol = "http";
    String clientCertNickname = "KRA Administrator of Instance pki-kra's SjcRedhat Domain ID";

    // parse command line arguments
    Options options = new Options();
    options.addOption("h", true, "Hostname of the DRM");
    options.addOption("p", true, "Port of the DRM");
    options.addOption("w", true, "Token password");
    options.addOption("d", true, "Directory for tokendb");
    options.addOption("s", true, "Attempt Optional Secure SSL connection");
    options.addOption("c", true, "Optional SSL Client cert Nickname");

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

        if (cmd.hasOption("h")) {
            host = cmd.getOptionValue("h");
        } else {
            System.err.println("Error: no hostname provided.");
            usage(options);
        }

        if (cmd.hasOption("p")) {
            port = cmd.getOptionValue("p");
        } else {
            System.err.println("Error: no port provided");
            usage(options);
        }

        if (cmd.hasOption("w")) {
            token_pwd = cmd.getOptionValue("w");
        } else {
            System.err.println("Error: no token password provided");
            usage(options);
        }

        if (cmd.hasOption("d")) {
            db_dir = cmd.getOptionValue("d");
        }

        if (cmd.hasOption("s")) {
            if (cmd.getOptionValue("s") != null && cmd.getOptionValue("s").equals("true")) {
                protocol = "https";
            }
        }

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

            if (nick != null && protocol.equals("https")) {
                clientCertNickname = nick;
            }
        }

    } catch (ParseException e) {
        System.err.println("Error in parsing command line options: " + e.getMessage());
        usage(options);
    }

    // used for crypto operations
    byte iv[] = { 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1 };

    try {
        iv = genIV(8);
    } catch (Exception e) {
        log("Can't generate initialization vector use default: " + e.toString());
    }

    // used for wrapping to send data to DRM
    String transportCert = null;

    // Data to be archived
    SymmetricKey vek = null;
    String passphrase = null;

    // Session keys and passphrases for recovery
    SymmetricKey sessionKey = null;
    byte[] wrappedRecoveryKey = null;
    String recoveryPassphrase = null;
    byte[] wrappedRecoveryPassphrase = null;

    // retrieved data (should match archived data)
    byte[] encryptedData = null;
    String recoveredKey = null;

    // various ids used in recovery/archival operations
    KeyId keyId = null;
    String clientKeyId = null;
    RequestId recoveryRequestId = null;

    // Variables for data structures from calls
    KeyRequestResponse requestResponse = null;
    Key keyData = null;
    KeyInfo keyInfo = null;

    // Initialize token
    try {
        CryptoManager.initialize(db_dir);
    } catch (AlreadyInitializedException e) {
        // it is ok if it is already initialized
    } catch (Exception e) {
        log("INITIALIZATION ERROR: " + e.toString());
        System.exit(1);
    }

    // Set base URI and get client

    KRAClient client;
    SystemCertClient systemCertClient;
    KeyClient keyClient;
    NSSCryptoProvider nssCrypto;
    try {
        ClientConfig config = new ClientConfig();
        config.setServerURI(protocol + "://" + host + ":" + port + "/kra");
        config.setCertNickname(clientCertNickname);
        config.setCertDatabase(db_dir);
        config.setCertPassword(token_pwd);
        nssCrypto = new NSSCryptoProvider(config);

        client = new KRAClient(new PKIClient(config, nssCrypto));
        systemCertClient = (SystemCertClient) client.getClient("systemcert");
        keyClient = (KeyClient) client.getClient("key");

    } catch (Exception e) {
        e.printStackTrace();
        return;
    }

    // Test 1: Get transport certificate from DRM
    transportCert = systemCertClient.getTransportCert().getEncoded();
    transportCert = transportCert.substring(CertData.HEADER.length(), transportCert.indexOf(CertData.FOOTER));
    keyClient.setTransportCert(transportCert);

    log("Transport Cert retrieved from DRM: " + transportCert);

    // Test 2: Get list of completed key archival requests
    log("\n\nList of completed archival requests");
    KeyRequestInfoCollection list = keyClient.listRequests("complete", "securityDataEnrollment");
    if (list.getTotal() == 0) {
        log("No requests found");
    } else {
        Iterator<KeyRequestInfo> iter = list.getEntries().iterator();
        while (iter.hasNext()) {
            KeyRequestInfo info = iter.next();
            printRequestInfo(info);
        }
    }

    // Test 3: Get list of key recovery requests
    log("\n\nList of completed recovery requests");
    KeyRequestInfoCollection list2 = keyClient.listRequests("complete", "securityDataRecovery");
    if (list2.getTotal() == 0) {
        log("No requests found");
    } else {
        Iterator<KeyRequestInfo> iter2 = list2.getEntries().iterator();
        while (iter2.hasNext()) {
            KeyRequestInfo info = iter2.next();
            printRequestInfo(info);
        }
    }

    // Test 4: Generate and archive a symmetric key
    log("Archiving symmetric key");
    clientKeyId = "UUID: 123-45-6789 VEK " + Calendar.getInstance().getTime().toString();
    try {
        vek = nssCrypto.generateSessionKey();
        byte[] encoded = nssCrypto.createPKIArchiveOptions(transportCert, vek, null,
                KeyRequestResource.DES3_ALGORITHM, 0, iv);

        KeyRequestResponse info = keyClient.archivePKIOptions(clientKeyId,
                KeyRequestResource.SYMMETRIC_KEY_TYPE, KeyRequestResource.DES3_ALGORITHM, 0, encoded);
        log("Archival Results:");
        printRequestInfo(info.getRequestInfo());
        keyId = info.getKeyId();
    } catch (Exception e) {
        log("Exception in archiving symmetric key:" + e.getMessage());
        e.printStackTrace();
    }

    //Test 5: Get keyId for active key with client ID

    log("Getting key ID for symmetric key");
    keyInfo = keyClient.getActiveKeyInfo(clientKeyId);
    printKeyInfo(keyInfo);
    KeyId keyId2 = keyInfo.getKeyId();
    if (keyId2 == null) {
        log("No archived key found");
    } else {
        log("Archived Key found: " + keyId);
    }

    if (!keyId.equals(keyId2)) {
        log("Error: key ids from search and archival do not match");
    } else {
        log("Success: keyids from search and archival match.");
    }

    // Test 6: Submit a recovery request for the symmetric key using a session key
    log("Submitting a recovery request for the  symmetric key using session key");
    try {
        sessionKey = nssCrypto.generateSessionKey();
        wrappedRecoveryKey = CryptoUtil.wrapSymmetricKey(nssCrypto.getManager(), nssCrypto.getToken(),
                transportCert, sessionKey);
        keyData = keyClient.retrieveKey(keyId, wrappedRecoveryKey);
    } catch (Exception e) {
        log("Exception in recovering symmetric key using session key: " + e.getMessage());
    }

    encryptedData = keyData.getEncryptedData();

    try {
        recoveredKey = Utils.base64encode(nssCrypto.unwrapWithSessionKey(encryptedData, sessionKey,
                KeyRequestResource.DES3_ALGORITHM, keyData.getNonceData()));
    } catch (Exception e) {
        log("Exception in unwrapping key: " + e.toString());
        e.printStackTrace();
    }

    if (!recoveredKey.equals(Utils.base64encode(vek.getEncoded()))) {
        log("Error: recovered and archived keys do not match!");
    } else {
        log("Success: recoverd and archived keys match!");
    }

    // Test 7: Submit a recovery request for the symmetric key using a passphrase
    log("Submitting a recovery request for the  symmetric key using a passphrase");
    recoveryPassphrase = "Gimme me keys please";

    try {
        sessionKey = nssCrypto.generateSessionKey();
        wrappedRecoveryPassphrase = nssCrypto.wrapWithSessionKey(recoveryPassphrase, iv, sessionKey,
                KeyRequestResource.DES3_ALGORITHM);
        wrappedRecoveryKey = nssCrypto.wrapSessionKeyWithTransportCert(sessionKey, transportCert);

        keyData = keyClient.retrieveKeyUsingWrappedPassphrase(keyId, wrappedRecoveryKey,
                wrappedRecoveryPassphrase, iv);
    } catch (Exception e) {
        log("Exception in recovering symmetric key using passphrase" + e.toString());
        e.printStackTrace();
    }

    encryptedData = keyData.getEncryptedData();

    try {
        recoveredKey = Utils.base64encode(nssCrypto.unwrapWithPassphrase(encryptedData, recoveryPassphrase));
    } catch (Exception e) {
        log("Error: unable to unwrap key using passphrase");
        e.printStackTrace();
    }

    if (recoveredKey == null || !recoveredKey.equals(Utils.base64encode(vek.getEncoded()))) {
        log("Error: recovered and archived keys do not match!");
    } else {
        log("Success: recovered and archived keys do match!");
    }

    passphrase = "secret12345";
    // Test 8: Generate and archive a passphrase
    clientKeyId = "UUID: 123-45-6789 RKEK " + Calendar.getInstance().getTime().toString();
    try {
        requestResponse = keyClient.archivePassphrase(clientKeyId, passphrase);

        log("Archival Results:");
        printRequestInfo(requestResponse.getRequestInfo());
        keyId = requestResponse.getKeyId();
    } catch (Exception e) {
        log("Exception in archiving symmetric key:" + e.toString());
        e.printStackTrace();
    }

    //Test 9: Get keyId for active passphrase with client ID
    log("Getting key ID for passphrase");
    keyInfo = keyClient.getActiveKeyInfo(clientKeyId);
    printKeyInfo(keyInfo);
    keyId2 = keyInfo.getKeyId();
    if (keyId2 == null) {
        log("No archived key found");
    } else {
        log("Archived Key found: " + keyId);
    }

    if (!keyId.equals(keyId2)) {
        log("Error: key ids from search and archival do not match");
    } else {
        log("Success: key ids from search and archival do match!");
    }

    // Test 10: Submit a recovery request for the passphrase using a session key
    log("Submitting a recovery request for the passphrase using session key");
    sessionKey = null;
    wrappedRecoveryKey = null;
    try {
        keyData = keyClient.retrieveKeyByPassphrase(keyId, recoveryPassphrase);
    } catch (Exception e) {
        log("Exception in recovering passphrase using session key: " + e.getMessage());
    }
    encryptedData = keyData.getEncryptedData();
    try {
        recoveredKey = new String(nssCrypto.unwrapWithPassphrase(encryptedData, recoveryPassphrase), "UTF-8");
    } catch (Exception e) {
        log("Exception in unwrapping key: " + e.toString());
        e.printStackTrace();
    }

    if (recoveredKey == null || !recoveredKey.equals(passphrase)) {
        log("Error: recovered and archived passphrases do not match!");
    } else {
        log("Success: recovered and archived passphrases do match!");
    }

    // Test 11: Submit a recovery request for the passphrase using a passphrase
    try {
        sessionKey = nssCrypto.generateSessionKey();
        wrappedRecoveryKey = nssCrypto.wrapSessionKeyWithTransportCert(sessionKey, transportCert);
        wrappedRecoveryPassphrase = nssCrypto.wrapWithSessionKey(recoveryPassphrase, iv, sessionKey,
                KeyRequestResource.DES3_ALGORITHM);
        keyData = keyClient.retrieveKeyUsingWrappedPassphrase(keyId, wrappedRecoveryKey,
                wrappedRecoveryPassphrase, iv);
    } catch (Exception e1) {
        e1.printStackTrace();
        System.out.println("Test 17: " + e1.getMessage());
        System.exit(-1);
    }
    encryptedData = keyData.getEncryptedData();
    try {
        recoveredKey = new String(nssCrypto.unwrapWithPassphrase(encryptedData, recoveryPassphrase), "UTF-8");
    } catch (Exception e) {
        log("Error: cannot unwrap key using passphrase");
        e.printStackTrace();
    }

    if (recoveredKey == null || !recoveredKey.equals(passphrase)) {
        log("Error: recovered and archived passphrases do not match!");
    } else {
        log("Success: recovered and archived passphrases do match!");
    }

    // Test 12: Get key
    log("Getting passphrase: " + keyId);
    try {
        keyData = keyClient.retrieveKeyByPassphrase(keyId, recoveryPassphrase);
    } catch (Exception e1) {
        e1.printStackTrace();
    }
    encryptedData = keyData.getEncryptedData();
    try {
        recoveredKey = new String(nssCrypto.unwrapWithPassphrase(encryptedData, recoveryPassphrase), "UTF-8");
    } catch (Exception e) {
        log("Error: Can't unwrap recovered key using passphrase");
        e.printStackTrace();
    }

    if (recoveredKey == null || !recoveredKey.equals(passphrase)) {
        log("Error: recovered and archived passphrases do not match!");
    } else {
        log("Success: recovered and archived passphrases do match!");
    }

    // Test 13: Get non-existent request
    RequestId requestId = new RequestId("0xabcdef");
    log("Getting non-existent request: " + requestId.toHexString());
    try {
        keyClient.getRequestInfo(requestId);
        log("Error: getting non-existent request does not throw an exception");
    } catch (RequestNotFoundException e) {
        log("Success: getting non-existent request throws an exception: " + e.getMessage() + " ("
                + e.getRequestId().toHexString() + ")");
    }

    // Test 14: Request x509 key recovery
    // This test requires to retrieve keyId and matching certificate
    // from installed instances of CA and DRM
    String keyID = "1";
    String b64Certificate = "MIIC+TCCAeGgAwIBAgIBDDANBgkqhkiG9w0BAQsFADBOMSswKQYDVQQKDCJ1c2Vy"
            + "c3lzLnJlZGhhdC5jb20gU2VjdXJpdHkgRG9tYWluMR8wHQYDVQQDDBZDQSBTaWdu"
            + "aW5nIENlcnRpZmljYXRlMB4XDTEzMTAyNTE5MzQwM1oXDTE0MDQyMzE5MzQwM1ow"
            + "EzERMA8GCgmSJomT8ixkAQEMAXgwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGB"
            + "ALhLfGmKvxFsKXPh49q1QsluXU3WlyS1XnpDLgOAhgTNgO4sG6CpPdv6hZYIvQBb"
            + "ZQ5bhuML+NXK+Q+EIiNk1cUTxgL3a30sPzy6QaFWxwM8i4uXm4nCBYv7T+n4V6/O"
            + "xHIM2Ch/dviAb3vz+M9trErv9t+d2H8jNXT3sHuDb/kvAgMBAAGjgaAwgZ0wHwYD"
            + "VR0jBBgwFoAUh1cxWFRY+nMsx4odQQI1GqyFxP8wSwYIKwYBBQUHAQEEPzA9MDsG"
            + "CCsGAQUFBzABhi9odHRwOi8vZG9ndGFnMjAudXNlcnN5cy5yZWRoYXQuY29tOjgw"
            + "ODAvY2Evb2NzcDAOBgNVHQ8BAf8EBAMCBSAwHQYDVR0lBBYwFAYIKwYBBQUHAwIG"
            + "CCsGAQUFBwMEMA0GCSqGSIb3DQEBCwUAA4IBAQCvmbUzQOouE2LgQQcKfmgwwJMJ"
            + "9tMrPwDUtyFdaIFoPL4uZaujSscaN4IWK2r5vIMJ65jwYCI7sI9En2ZfO28J9dQj"
            + "lpqu6TaJ+xtaMk7OvXpVB7lJk73HAttMGjETlkoq/6EjxcugmJsDqVD0b2tO7Vd0"
            + "hroBe2uPDHM2ASewZF415lUcRh0URtmxSazTInbyxpmy1wgSJQ0C6fMCeT+hUFlA"
            + "0P4k1TIprapGVq7FpKcqlhK2gTBfTSnoO7gmXG/9MxJiYpb/Aph8ptXq6quHz1Mj"
            + "greWr3xTsy6gF2yphUEkGHh4v22XvK+FLx9Jb6zloMWA2GG9gpUpvMnl1fH4";

    log("Requesting X509 key recovery.");
    recoveryRequestId = keyClient.recoverKey(new KeyId(keyID), null, null, null, b64Certificate)
            .getRequestInfo().getRequestId();
    log("Requesting X509 key recovery request: " + recoveryRequestId);

    // Test 55: Approve x509 key recovery
    log("Approving X509 key recovery request: " + recoveryRequestId);
    keyClient.approveRequest(recoveryRequestId);

    // Test 16: Recover x509 key
    log("Recovering X509 key based on request: " + recoveryRequestId);
    try {
        // KeyData recoveredX509Key = client.recoverKey(recoveryRequestId, "netscape");
        // log("Success: X509Key recovered: "+ recoveredX509Key.getP12Data());
    } catch (RequestNotFoundException e) {
        log("Error: recovering X509Key");
    }

    // Test 1: Get transport certificate from DRM
    transportCert = systemCertClient.getTransportCert().getEncoded();
    transportCert = transportCert.substring(CertData.HEADER.length(), transportCert.indexOf(CertData.FOOTER));

    log("Transport Cert retrieved from DRM: " + transportCert);

    // Test 17: Get list of completed key archival requests
    log("\n\nList of completed archival requests");
    list = keyClient.listRequests("complete", IRequest.SYMKEY_GENERATION_REQUEST);
    if (list.getTotal() == 0) {
        log("No requests found");
    } else {
        Iterator<KeyRequestInfo> iter = list.getEntries().iterator();
        while (iter.hasNext()) {
            KeyRequestInfo info = iter.next();
            printRequestInfo(info);
        }
    }

    // test 18: Generate symmetric key
    clientKeyId = "Symmetric Key #1234f " + Calendar.getInstance().getTime().toString();
    List<String> usages = new ArrayList<String>();
    usages.add(SymKeyGenerationRequest.DECRYPT_USAGE);
    usages.add(SymKeyGenerationRequest.ENCRYPT_USAGE);
    KeyRequestResponse genKeyResponse = keyClient.generateSymmetricKey(clientKeyId,
            KeyRequestResource.AES_ALGORITHM, 128, usages, null);
    printRequestInfo(genKeyResponse.getRequestInfo());
    keyId = genKeyResponse.getKeyId();

    // test 19: Get keyId for active key with client ID
    log("Getting key ID for symmetric key");
    keyInfo = keyClient.getActiveKeyInfo(clientKeyId);
    printKeyInfo(keyInfo);
    keyId2 = keyInfo.getKeyId();
    if (keyId2 == null) {
        log("No archived key found");
    } else {
        log("Archived Key found: " + keyId);
    }

    if (!keyId.equals(keyId2)) {
        log("Error: key ids from search and archival do not match");
    } else {
        log("Success: keyids from search and archival match.");
    }

    // Test 20: Submit a recovery request for the symmetric key using a session key
    log("Submitting a recovery request for the  symmetric key using session key");
    try {
        sessionKey = nssCrypto.generateSessionKey();
        wrappedRecoveryKey = nssCrypto.wrapSessionKeyWithTransportCert(sessionKey, transportCert);
        keyData = keyClient.retrieveKey(keyId, wrappedRecoveryKey);
    } catch (Exception e) {
        log("Exception in recovering symmetric key using session key: " + e.getMessage());
    }

    encryptedData = keyData.getEncryptedData();

    try {
        recoveredKey = new String(nssCrypto.unwrapWithSessionKey(encryptedData, sessionKey,
                KeyRequestResource.DES3_ALGORITHM, keyData.getNonceData()));
    } catch (Exception e) {
        log("Exception in unwrapping key: " + e.toString());
        e.printStackTrace();
    }

    // test 21: Generate symmetric key - invalid algorithm
    try {
        genKeyResponse = keyClient.generateSymmetricKey("Symmetric Key #1235", "AFS", 128, usages, null);
    } catch (Exception e) {
        log("Exception: " + e);
    }

    // test 22: Generate symmetric key - invalid key size
    try {
        genKeyResponse = keyClient.generateSymmetricKey("Symmetric Key #1236", "AES", 0, usages, null);
    } catch (Exception e) {
        log("Exception: " + e);
    }

    // test 23: Generate symmetric key - usages not defined
    try {
        genKeyResponse = keyClient.generateSymmetricKey("Symmetric Key #1236", "DES", 56, null, null);
    } catch (Exception e) {
        log("Exception: " + e);
    }

    // Test 24: Generate and archive a symmetric key of type AES
    log("Archiving symmetric key");
    clientKeyId = "UUID: 123-45-6789 VEK " + Calendar.getInstance().getTime().toString();
    try {
        vek = nssCrypto.generateSymmetricKey(KeyRequestResource.AES_ALGORITHM, 128);

        byte[] encoded = CryptoUtil.createPKIArchiveOptions(nssCrypto.getManager(), nssCrypto.getToken(),
                transportCert, vek, null, KeyGenAlgorithm.DES3, 0, new IVParameterSpec(iv));

        KeyRequestResponse response = keyClient.archivePKIOptions(clientKeyId,
                KeyRequestResource.SYMMETRIC_KEY_TYPE, KeyRequestResource.AES_ALGORITHM, 128, encoded);
        log("Archival Results:");
        printRequestInfo(response.getRequestInfo());
        keyId = response.getKeyId();
    } catch (Exception e) {
        log("Exception in archiving symmetric key:" + e.getMessage());
        e.printStackTrace();
    }

    //Test 25: Get keyId for active key with client ID
    log("Getting key ID for symmetric key");
    keyInfo = keyClient.getActiveKeyInfo(clientKeyId);
    printKeyInfo(keyInfo);
    keyId2 = keyInfo.getKeyId();
    if (keyId2 == null) {
        log("No archived key found");
    } else {
        log("Archived Key found: " + keyId);
    }

    if (!keyId.equals(keyId2)) {
        log("Error: key ids from search and archival do not match");
    } else {
        log("Success: keyids from search and archival match.");
    }

    // Test 26: Submit a recovery request for the symmetric key
    log("Submitting a recovery request for the  symmetric key without using session key");
    try {
        keyData = keyClient.retrieveKey(keyId);
    } catch (Exception e) {
        log("Exception in recovering symmetric key using session key: " + e.getMessage());
    }

    // Since no session key is provided externally, the retrieveKey method
    // generates a session key, wraps it with transport cert and completes the request.
    // The encrypted data is then unwrapped using the temporary session key and set to
    // the attribute privateData.
    recoveredKey = Utils.base64encode(keyData.getData());

    if (!recoveredKey.equals(Utils.base64encode(vek.getEncoded()))) {
        log("Error: recovered and archived keys do not match!");
    } else {
        log("Success: recoverd and archived keys match!");
    }

    // Test 27: Get key info
    log("getting key info for existing key");
    printKeyInfo(keyClient.getKeyInfo(keyId));

    //Test 28: Modify status
    log("modify the key status");
    keyClient.modifyKeyStatus(keyId, KeyResource.KEY_STATUS_INACTIVE);
    keyInfo = keyClient.getKeyInfo(keyId);
    printKeyInfo(keyInfo);

    //Test 29:  Confirm no more active keys with this ID
    log("look for active keys with this id");
    clientKeyId = keyInfo.getClientKeyID();
    try {
        keyInfo = keyClient.getActiveKeyInfo(clientKeyId);
        printKeyInfo(keyInfo);
    } catch (ResourceNotFoundException e) {
        log("Success: ResourceNotFound exception thrown: " + e);
    }

    // Test asymmetric key generation.

    String[] algs = { "RSA", "DSA" };
    for (int i = 0; i < algs.length; i++) {
        // Test 30: Generate Asymmetric keys - RSA key
        System.out.println("\nTesting asymmetric key generation for algorithm " + algs[i]);
        clientKeyId = "AsymKey #" + Calendar.getInstance().getTimeInMillis();
        usages.clear();
        usages.add(AsymKeyGenerationRequest.SIGN);
        usages.add(AsymKeyGenerationRequest.VERIFY);
        KeyRequestResponse response = keyClient.generateAsymmetricKey(clientKeyId, algs[i], 1024, usages, null);
        printRequestInfo(response.getRequestInfo());
        System.out.println();

        // Test 31: Get information of the newly generated asymmetric keys
        System.out.println("Fetch information of the newly generated asymmetric keys.");
        System.out.println();
        KeyInfo info = keyClient.getKeyInfo(response.getKeyId());
        printKeyInfo(info);
        System.out.println();

        // Test 32: Retrieve private key data
        System.out.println("Retrieving and verifying the generated private key.");
        try {
            keyData = keyClient.retrieveKey(response.getKeyId());
        } catch (Exception e) {
            log("Exception retrieving the private key data.");
            e.printStackTrace();
        }

        // Test 33: Verify the generated key pair.
        if (isKeyPairValid(algs[i], keyData.getData(), info.getPublicKey())) {
            log("The key pair generated using " + algs[i] + " algorithm is valid.");
        } else {
            log("The key pair generated using " + algs[i] + " algorithm is invalid.");
        }
        System.out.println();
    }

    // Test 34:
}

From source file:com.yhfudev.SimulatorForSelfStabilizing.java

public static void main(String[] args) {
    // command line lib: apache CLI http://commons.apache.org/proper/commons-cli/
    // command line arguments:
    //  -- input file
    //  -- output line to a csv file
    //  -- algorithm: Ding's linear or randomized

    // single thread parsing ...
    Options options = new Options();
    options.addOption("h", false, "print this message");
    //heuristic//from  ww w . j a  va 2  s  .  c  o m
    options.addOption("u", false, "(rand) heuristic on");
    options.addOption("y", true, "show the graph with specified delay (ms)");
    options.addOption("i", true, "the input file name");
    options.addOption("o", true, "the results is save to a attachable output cvs file");
    options.addOption("l", true, "the graph activities trace log file name");
    options.addOption("s", true, "save the graph to a file");
    options.addOption("a", true, "the algorithm name, ding or rand");
    // options specified to generator
    options.addOption("g", true,
            "the graph generator algorithm name: fan1l, fan2l, rand, doro, flower, watt, lobster");
    options.addOption("n", true, "the number of nodes");
    options.addOption("d", true, "(rand) the node degree (max)");
    options.addOption("f", false, "(rand) if the degree value is fix or not");
    options.addOption("p", true, "(watt) the probability of beta");

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        e.printStackTrace();
        return;
    }
    if (cmd.hasOption("h")) {
        showHelp(options);
        return;
    }

    int delay_time = 0;
    if (cmd.hasOption("y")) {
        delay_time = Integer.parseInt(cmd.getOptionValue("y"));
    }

    String sFileName = null;
    sFileName = null;
    FileWriter writer = null;
    if (cmd.hasOption("o")) {
        sFileName = cmd.getOptionValue("o");
    }
    if ((null != sFileName) && (!"".equals(sFileName))) {
        try {
            writer = new FileWriter(sFileName, true); // true: append
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Error: unable to open the output file " + sFileName);
            return;
        }
    }
    FileWriter wrGraph = null;
    sFileName = null;
    if (cmd.hasOption("s")) {
        sFileName = cmd.getOptionValue("s");
    }
    if ((null != sFileName) && (!"".equals(sFileName))) {
        try {
            wrGraph = new FileWriter(sFileName, true); // true: append
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Error: unable to open the saveGraph file " + sFileName);
            return;
        }
    }

    sFileName = null;
    if (cmd.hasOption("i")) {
        sFileName = cmd.getOptionValue("i");
    }
    String genname = null;
    if (cmd.hasOption("g")) {
        genname = cmd.getOptionValue("g");
    }
    if ((null == genname) && (null == sFileName)) {
        System.out.println("Error: not specify the input file or graph generator");
        showHelp(options);
        return;
    }
    if ((null != genname) && (null != sFileName)) {
        System.out.println("Error: do not specify the input file and graph generator at the same time");
        showHelp(options);
        return;
    }

    if (delay_time > 0) {
        // create and display a graph
        System.setProperty("org.graphstream.ui.renderer", "org.graphstream.ui.j2dviewer.J2DGraphRenderer");
    }

    Graph graph = new SingleGraph("test");
    //graph.setNullAttributesAreErrors(true); // to throw an exception instead of returning null (in getAttribute()).
    if (delay_time > 0) {
        graph.addAttribute("ui.quality");
        graph.addAttribute("ui.antialias");
        graph.addAttribute("ui.stylesheet", "url(data/selfstab-mwcds.css);");
        graph.display();
    }

    // save the trace to file
    FileSinkDGS dgs = null;
    if (cmd.hasOption("l")) {
        dgs = new FileSinkDGS();
        graph.addSink(dgs);
        try {
            dgs.begin(cmd.getOptionValue("l"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    Generator generator = null;
    if (null != sFileName) {
        System.out.println("DEBUG: the input file=" + sFileName);
        FileSource source = new FileSourceDGS();
        source.addSink(graph);
        int count_edge_error = 0;
        try {
            //source.begin("data/selfstab-mwcds.dgs"); // Ding's paper example
            //source.begin("data/selfstab-ds.dgs");    // DS example
            //source.begin("data/selfstab-doro-1002.dgs"); // DorogovtsevMendes
            //source.begin("data/selfstab-rand-p10-10002.dgs"); // random connected graph with degree = 10% nodes
            //source.begin("data/selfstab-rand-f5-34.dgs"); // random connected graph with degree = 5
            source.begin(sFileName);
            while (true) {
                try {
                    if (false == source.nextEvents()) {
                        break;
                    }
                } catch (EdgeRejectedException e) {
                    // ignore
                    count_edge_error++;
                    System.out.println("DEBUG: adding edge error: " + e.toString());
                }
                if (delay_time > 0) {
                    delay(delay_time);
                }
            }
            source.end();
            //} catch (InterruptedException e) {
            //    e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("DEBUG: END read from source. # of edges ignored=" + count_edge_error);
    } else {
        // assert (genname != null);

        // graph generator
        //generator = new ChvatalGenerator(); // fix size
        //generator = new FullGenerator(); // full connected, 2 steps,1 node in dominate set
        //generator = new GridGenerator(); // only one result
        //generator = new HypercubeGenerator(); // one result
        //generator = new IncompleteGridGenerator(); // error
        //generator = new PetersenGraphGenerator(); // fix size
        //generator = new PointsOfInterestGenerator(); // error
        //generator = new RandomEuclideanGenerator(); // linear algo endless loop
        //generator = new RandomFixedDegreeDynamicGraphGenerator(); //
        //generator = new RandomGenerator(); //
        //generator = new URLGenerator("http://www.cnbeta.com"); //
        //generator = new WikipediaGenerator("Antarctica"); // no end

        //generator = new DorogovtsevMendesGenerator(); // ok
        //generator = new FlowerSnarkGenerator(); // ok
        //generator = new WattsStrogatzGenerator(maxSteps, 30, 0.5); // small world, ok
        //generator = new LobsterGenerator(); // tree like, ok

        int i;
        int n = 12; // the number of nodes
        if (cmd.hasOption("n")) {
            n = Integer.parseInt(cmd.getOptionValue("n"));
        }
        int d = 3; // the degree of nodes
        if (cmd.hasOption("d")) {
            d = Integer.parseInt(cmd.getOptionValue("d"));
        }
        boolean isFix = false;
        if (cmd.hasOption("f")) {
            isFix = true;
        }
        if ("".equals(genname)) {
            System.out.println("Error: not set generator name");
            return;
        } else if ("fan1l".equals(genname)) {
            generator = new FanGenerator();
        } else if ("fan2l".equals(genname)) {
            generator = new Fan2lGenerator(graph, d);
        } else if ("doro".equals(genname)) {
            generator = new DorogovtsevMendesGenerator();
        } else if ("flower".equals(genname)) {
            generator = new FlowerSnarkGenerator();
        } else if ("lobster".equals(genname)) {
            generator = new LobsterGenerator();
        } else if ("rand".equals(genname)) {
            generator = new ConnectionGenerator(graph, d, false, isFix);
        } else if ("watt".equals(genname)) {
            // WattsStrogatzGenerator(n,k,beta)
            // a ring of n nodes
            // each node is connected to its k nearest neighbours, k must be even
            // n >> k >> log(n) >> 1
            // beta being a probability it must be between 0 and 1.
            int k;
            double beta = 0.5;
            if (cmd.hasOption("p")) {
                beta = Double.parseDouble(cmd.getOptionValue("p"));
            }
            k = (n / 20) * 2;
            if (k < 2) {
                k = 2;
            }
            if (n < 2 * 6) {
                n = 2 * 6;
            }
            generator = new WattsStrogatzGenerator(n, k, beta);
        }
        /*int listf5[][] = {
        {12, 5},
        {34, 5},
        {102, 5},
        {318, 5},
        {1002, 5},
        {3164, 5},
        {10002, 5},
        };
        int listp3[][] = {
        {12, 2},
        {34, 2},
        {102, 3},
        {318, 9},
        {1002, 30},
        {3164, 90},
        {10002, 300},
        };
        int listp10[][] = {
        {12, 2},
        {34, 3},
        {102, 10},
        {318, 32},
        {1002, 100},
        {3164, 316},
        {10002, 1000},
        };
        i = 6;
        maxSteps = listf5[i][0];
        int degree = listf5[i][1];
        generator = new ConnectionGenerator(graph, degree, false, true);
        */
        generator.addSink(graph);
        generator.begin();
        for (i = 1; i < n; i++) {
            generator.nextEvents();
        }
        generator.end();
        delay(500);
    }

    if (cmd.hasOption("a")) {
        SinkAlgorithm algorithm = null;
        String algo = "rand";
        algo = cmd.getOptionValue("a");
        if ("ding".equals(algo)) {
            algorithm = new SelfStabilizingMWCDSLinear();
        } else if ("ds".equals(algo)) {
            algorithm = new SelfStabilizingDSLinear();
        } else {
            algorithm = new SelfStabilizingMWCDSRandom();
        }
        algorithm.init(graph);
        algorithm.setSource("0");
        if (delay_time > 0) {
            algorithm.setAnimationDelay(delay_time);
        }
        if (cmd.hasOption("u")) {
            algorithm.heuristicOn(true);
        } else {
            algorithm.heuristicOn(false);
        }
        algorithm.compute();

        GraphVerificator verificator = new MWCDSGraphVerificator();
        if (verificator.verify(graph)) {
            System.out.println("DEBUG: PASS MWCDSGraphVerificator verficiation.");
        } else {
            System.out.println("DEBUG: FAILED MWCDSGraphVerificator verficiation!");
        }

        if (null != writer) {
            AlgorithmResult result = algorithm.getResult();
            result.SaveTo(writer);
            try {
                writer.flush();
                writer.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        algorithm.terminate();
    }

    if (null != generator) {
        generator.removeSink(graph);
    }
    if (dgs != null) {
        graph.removeSink(dgs);
        try {
            dgs.end();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    if (null != wrGraph) {
        try {
            saveGraph(graph, wrGraph);
            wrGraph.flush();
            wrGraph.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

From source file:maps.OptionsHandler.java

static void applyOptions(String[] args) {
    try {/*ww  w  .  jav  a 2s. c o  m*/
        CommandLineParser parser = new DefaultParser();
        CommandLine cmd = parser.parse(options, args);
        checkOptions(cmd);
    } catch (ParseException e) {
        System.err.println("Error in options: " + e.toString());
        printHelpOption();
    }
}

From source file:by.stub.Main.java

private static void parseCommandLineArgs(final String[] args) {
    try {//  www.  j  ava 2  s.co  m
        CommandLineInterpreter.parseCommandLine(args);
    } catch (final ParseException ex) {
        final String msg = String.format("Could not parse provided command line arguments, error: %s",
                ex.toString());

        throw new Stubby4JException(msg);
    }
}

From source file:io.github.azagniotov.stubby4j.Main.java

private static void parseCommandLineArgs(final String[] args) {
    try {/*from  w ww .j  a  v a2  s. c  o  m*/
        commandLineInterpreter.parseCommandLine(args);
    } catch (final ParseException ex) {
        final String msg = String.format("Could not parse provided command line arguments, error: %s",
                ex.toString());

        throw new Stubby4JException(msg);
    }
}

From source file:com.linkedin.helix.mock.relay.DummyRelayProcess.java

public static CommandLine processCommandLineArgs(String[] cliArgs) throws Exception {
    CommandLineParser cliParser = new GnuParser();
    Options cliOptions = constructCommandLineOptions();
    CommandLine cmd = null;/*from   ww  w . j  a v  a  2s. c  o  m*/

    try {
        return cliParser.parse(cliOptions, cliArgs);
    } catch (ParseException pe) {
        System.err.println("CommandLineClient: failed to parse command-line options: " + pe.toString());
        printUsage(cliOptions);
        System.exit(1);
    }
    return null;
}

From source file:com.linkedin.helix.webapp.RestAdminApplication.java

public static void processCommandLineArgs(String[] cliArgs) throws Exception {
    CommandLineParser cliParser = new GnuParser();
    Options cliOptions = constructCommandLineOptions();
    CommandLine cmd = null;/* w w w  .j a v  a  2 s .co  m*/

    try {
        cmd = cliParser.parse(cliOptions, cliArgs);
    } catch (ParseException pe) {
        System.err.println("RestAdminApplication: failed to parse command-line options: " + pe.toString());
        printUsage(cliOptions);
        System.exit(1);
    }
    int port = DEFAULT_PORT;
    if (cmd.hasOption(HELP)) {
        printUsage(cliOptions);
        return;
    } else if (cmd.hasOption(PORT)) {
        port = Integer.parseInt(cmd.getOptionValue(PORT));
    }

    HelixAdminWebApp app = new HelixAdminWebApp(cmd.getOptionValue(ZKSERVERADDRESS), port);
    app.start();
    try {
        Thread.currentThread().join();
    } finally {
        app.stop();
    }
}

From source file:com.linkedin.helix.mock.storage.MockHealthReportParticipant.java

public static CommandLine processCommandLineArgs(String[] cliArgs) throws Exception {
    CommandLineParser cliParser = new GnuParser();
    Options cliOptions = constructCommandLineOptions();

    try {//w  ww . j a va  2 s .co m

        return cliParser.parse(cliOptions, cliArgs);
    } catch (ParseException pe) {
        System.err.println("CommandLineClient: failed to parse command-line options: " + pe.toString());
        printUsage(cliOptions);
        System.exit(1);
    }
    return null;
}

From source file:io.github.retz.scheduler.Launcher.java

public static int run(String... argv) {

    Configuration conf;//from w w  w.j ava  2 s .co  m
    try {
        conf = parseConfiguration(argv);
        if (conf.fileConfig.isTLS()) {
            LOG.warn("Make sure a valid certificate is being used or RetzExecutor may not work.");
        }
        Database.getInstance().init(conf.getServerConfig());
        if (conf.getServerConfig().getGc()) {
            GarbageJobCollector.start(conf.getServerConfig().getGcLeeway(),
                    conf.getServerConfig().getGcInterval());
        } else {
            LOG.info("Automatic garbage collection is turned off; use retz-admin gc to collect old jobs");
        }
    } catch (ParseException e) {
        LOG.error(e.toString());
        return -1;
    } catch (URISyntaxException e) {
        LOG.error(e.toString());
        return -1;
    } catch (SQLException e) {
        LOG.error(e.toString());
        return -1;
    } catch (IOException e) {
        LOG.error(e.toString());
        return -1;
    }

    Optional<JmxServer> maybeJmxServer = AdminConsole.startJmxServer(conf.getServerConfig());
    if (!maybeJmxServer.isPresent()) {
        LOG.error("Failed to start JMX Server");
        return -1;
    }
    JmxServer jmxServer = maybeJmxServer.get();

    Protos.FrameworkInfo fw = buildFrameworkInfo(conf);

    // Retz must do all recovery process before launching scheduler;
    // This is because running scheduler changes state of any jobs if it
    // has successfully connected to Mesos master.
    // By hitting HTTP endpoints and comparing with database job states,
    // Retz can decide whether to re-run it or just finish it.
    // BTW after connecting to Mesos it looks like re-sending unacked messages.
    maybeRequeueRunningJobs(conf.getMesosMaster(), fw.getId().getValue(), Database.getInstance().getRunning());

    RetzScheduler scheduler;
    try {
        scheduler = new RetzScheduler(conf, fw);
    } catch (Throwable t) {
        LOG.error("Cannot initialize scheduler", t);
        return -1;
    }
    SchedulerDriver driver = SchedulerDriverFactory.create(scheduler, conf, fw);

    Protos.Status status = driver.start();

    if (status != Protos.Status.DRIVER_RUNNING) {
        LOG.error("Cannot start Mesos scheduler: {}", status.name());
        System.exit(-1);
        //} else if (status == Protos.Status.DRIVER_ABORTED) {
        //} else if (status == Protos.Status.DRIVER_NOT_STARTED) {
        //} else if (status == Protos.Status.DRIVER_STOPPED) {
    }

    LOG.info("Mesos scheduler started: {}", status.name());

    // Start web server
    WebConsole.start(conf.fileConfig);
    WebConsole.set(scheduler, driver);
    LOG.info("Web console has started with port {}", conf.getPort());

    java.lang.Runtime.getRuntime().addShutdownHook(new ShutdownThread(driver));

    // Stop them all, usually don't come here
    // Wait for Mesos framework stop
    status = driver.join();
    LOG.info("{} has been stopped: {}", RetzScheduler.FRAMEWORK_NAME, status.name());

    WebConsole.stop(); // Stop web server
    GarbageJobCollector.stop();
    Database.getInstance().stop();
    jmxServer.stop();

    return (status == Protos.Status.DRIVER_STOPPED ? 0 : 255);
}