Example usage for java.lang System console

List of usage examples for java.lang System console

Introduction

In this page you can find the example usage for java.lang System console.

Prototype

public static Console console() 

Source Link

Document

Returns the unique java.io.Console Console object associated with the current Java virtual machine, if any.

Usage

From source file:org.hawkular.wildfly.agent.installer.AgentInstaller.java

/**
 * Reads password from the console (stdin).
 *
 * @param message to present before reading
 * @return password or null if console is not available
 *///from   www  .  ja v a  2 s  .  c  o m
private static String readPasswordFromStdin(String message) {
    Console console = System.console();
    if (console == null) {
        return null;
    }
    console.writer().write(message);
    console.writer().flush();
    return String.valueOf(console.readPassword());
}

From source file:com.aerospike.benchmarks.Main.java

public Main(String[] commandLineArgs) throws Exception {
    boolean hasTxns = false;

    Options options = new Options();
    options.addOption("h", "hosts", true, "Set the Aerospike host node.");
    options.addOption("p", "port", true, "Set the port on which to connect to Aerospike.");
    options.addOption("U", "user", true, "User name");
    options.addOption("P", "password", true, "Password");
    options.addOption("n", "namespace", true, "Set the Aerospike namespace. Default: test");
    options.addOption("s", "set", true, "Set the Aerospike set name. Default: testset");
    options.addOption("k", "keys", true,
            "Set the number of keys the client is dealing with. "
                    + "If using an 'insert' workload (detailed below), the client will write this "
                    + "number of keys, starting from value = start_value. Otherwise, the client "
                    + "will read and update randomly across the values between start_value and "
                    + "start_value + num_keys.");

    // key type has been changed to integer, so this option is no longer relevant.
    // Leave in (and ignore) so existing benchmark scripts do not break.
    options.addOption("l", "keylength", true, "Not used anymore since key is an integer.");

    options.addOption("b", "bins", true, "Set the number of Aerospike bins. "
            + "Each bin will contain an object defined with -o. The default is single bin (-b 1).");
    options.addOption("o", "objectSpec", true,
            "I | S:<size> | B:<size>\n"
                    + "Set the type of object(s) to use in Aerospike transactions. Type can be 'I' "
                    + "for integer, 'S' for string, or 'B' for Java blob. If type is 'I' (integer), "
                    + "do not set a size (integers are always 8 bytes). If object_type is 'S' "
                    + "(string), this value represents the length of the string.");
    options.addOption("R", "random", false,
            "Use dynamically generated random bin values instead of default static fixed bin values.");
    options.addOption("S", "startkey", true,
            "Set the starting value of the working set of keys. "
                    + "If using an 'insert' workload, the start_value indicates the first value to write. "
                    + "Otherwise, the start_value indicates the smallest value in the working set of keys.");
    options.addOption("w", "workload", true, "I | RU,<percent>[,<percent2>][,<percent3>] | RMU | RMI | RMD\n"
            + "Set the desired workload.\n\n" + "   -w I sets a linear 'insert' workload.\n\n"
            + "   -w RU,80 sets a random read-update workload with 80% reads and 20% writes.\n\n"
            + "      100% of reads will read all bins.\n\n" + "      100% of writes will write all bins.\n\n"
            + "   -w RU,80,60,30 sets a random multi-bin read-update workload with 80% reads and 20% writes.\n\n"
            + "      60% of reads will read all bins. 40% of reads will read a single bin.\n\n"
            + "      30% of writes will write all bins. 70% of writes will write a single bin.\n\n"
            + "    -w RMU sets a random read all bins-update one bin workload with 50% reads.\n\n"
            + "    -w RMI sets a random read all bins-increment one integer bin workload with 50% reads.\n\n"
            + "    -w RMD sets a random read all bins-decrement one integer bin workload with 50% reads.\n\n"
            + "    -w TXN,r:1000,w:200,v:20%\n\n"
            + "       form business transactions with 1000 reads, 200 writes with a variation (+/-) of 20%\n\n");
    options.addOption("e", "expirationTime", true, "Set expiration time of each record in seconds."
            + " -1: Never expire, " + "  0: Default to namespace," + " >0: Actual given expiration time");
    options.addOption("g", "throughput", true,
            "Set a target transactions per second for the client. The client should not exceed this "
                    + "average throughput.");
    options.addOption("t", "transactions", true,
            "Number of transactions to perform in read/write mode before shutting down. "
                    + "The default is to run indefinitely.");

    options.addOption("T", "timeout", true, "Set read and write transaction timeout in milliseconds.");
    options.addOption("readTimeout", true, "Set read transaction timeout in milliseconds.");
    options.addOption("writeTimeout", true, "Set write transaction timeout in milliseconds.");

    options.addOption("maxRetries", true, "Maximum number of retries before aborting the current transaction.");
    options.addOption("sleepBetweenRetries", true,
            "Milliseconds to sleep between retries if a transaction fails and the timeout was not exceeded. "
                    + "Enter zero to skip sleep.");
    options.addOption("consistencyLevel", true,
            "How replicas should be consulted in a read operation to provide the desired consistency guarantee. "
                    + "Values:  one | all.  Default: one");
    options.addOption("commitLevel", true,
            "Desired replica consistency guarantee when committing a transaction on the server. "
                    + "Values:  all | master.  Default: all");

    options.addOption("z", "threads", true, "Set the number of threads the client will use to generate load. "
            + "It is not recommended to use a value greater than 125.");
    options.addOption("latency", true,
            "\"ycsb\"[,warmup count] or <number of latency columns>,<range shift increment>[,(ms|us)]\n"
                    + "ycsb: show the timings in ycsb format\n"
                    + "Show transaction latency percentages using elapsed time ranges.\n"
                    + "<number of latency columns>: Number of elapsed time ranges.\n"
                    + "<range shift increment>: Power of 2 multiple between each range starting at column 3.\n"
                    + "(ms|us): display times in milliseconds (ms, default) or microseconds (us)\n\n"
                    + "A latency definition of '-latency 7,1' results in this layout:\n"
                    + "    <=1ms >1ms >2ms >4ms >8ms >16ms >32ms\n"
                    + "       x%   x%   x%   x%   x%    x%    x%\n"
                    + "A latency definition of '-latency 4,3' results in this layout:\n"
                    + "    <=1ms >1ms >8ms >64ms\n" + "       x%   x%   x%    x%\n\n"
                    + "Latency columns are cumulative. If a transaction takes 9ms, it will be included in both the >1ms and >8ms columns.");

    options.addOption("N", "reportNotFound", false,
            "Report not found errors. Data should be fully initialized before using this option.");
    //options.addOption("v", "validate", false, "Validate data.");
    options.addOption("D", "debug", false, "Run benchmarks in debug mode.");
    options.addOption("u", "usage", false, "Print usage.");

    options.addOption("B", "batchSize", true,
            "Enable batch mode with number of records to process in each batch get call. "
                    + "Batch mode is valid only for RU (read update) workloads. Batch mode is disabled by default.");

    options.addOption("ST", "storeType", true, "Defines data store type to run. Values:  KVS | LLIST | LSTACK");

    options.addOption("BT", "batchThreads", true,
            "Maximum number of concurrent batch sub-threads for each batch command.\n"
                    + "1   : Run each batch node command sequentially.\n"
                    + "0   : Run all batch node commands in parallel.\n"
                    + "> 1 : Run maximum batchThreads in parallel.  When a node command finshes, start a new one until all finished.");

    options.addOption("prole", false, "Distribute reads across proles in round-robin fashion.");

    options.addOption("a", "async", false, "Benchmark asynchronous methods instead of synchronous methods.");
    options.addOption("C", "asyncMaxCommands", true,
            "Maximum number of concurrent asynchronous database commands.");
    options.addOption("E", "asyncSelectorTimeout", true, "Asynchronous select() timeout in milliseconds.");
    options.addOption("W", "asyncSelectorThreads", true,
            "Number of selector threads when running in asynchronous mode.");
    options.addOption("V", "asyncTaskThreads", true,
            "Number of asynchronous tasks. Use zero for unbounded thread pool.");
    options.addOption("F", "keyFile", true, "File path to read the keys for read operation.");
    options.addOption("KT", "keyType", true, "Type of the key(String/Integer) in the file, default is String");

    // parse the command line arguments
    CommandLineParser parser = new PosixParser();
    CommandLine line = parser.parse(options, commandLineArgs);
    String[] extra = line.getArgs();

    if (line.hasOption("u")) {
        logUsage(options);//from  w w w.  j a  v  a 2  s . c o  m
        throw new UsageException();
    }

    if (extra.length > 0) {
        throw new Exception("Unexpected arguments: " + Arrays.toString(extra));
    }

    if (line.hasOption("async")) {
        this.asyncEnabled = true;
        args.readPolicy = clientPolicy.asyncReadPolicyDefault;
        args.writePolicy = clientPolicy.asyncWritePolicyDefault;
        args.batchPolicy = clientPolicy.batchPolicyDefault; // async does not need batch policy.
    } else {
        args.readPolicy = clientPolicy.readPolicyDefault;
        args.writePolicy = clientPolicy.writePolicyDefault;
        args.batchPolicy = clientPolicy.batchPolicyDefault;
    }

    if (line.hasOption("e")) {
        args.writePolicy.expiration = Integer.parseInt(line.getOptionValue("e"));
        if (args.writePolicy.expiration < -1) {
            throw new Exception("Invalid expiration:" + args.writePolicy.expiration + "It should be >= -1");
        }
    }

    if (line.hasOption("hosts")) {
        this.hosts = line.getOptionValue("hosts").split(",");
    } else {
        this.hosts = new String[1];
        this.hosts[0] = "127.0.0.1";
    }

    if (line.hasOption("port")) {
        this.port = Integer.parseInt(line.getOptionValue("port"));
    } else {
        this.port = 3000;
    }

    clientPolicy.user = line.getOptionValue("user");
    clientPolicy.password = line.getOptionValue("password");

    if (clientPolicy.user != null && clientPolicy.password == null) {
        java.io.Console console = System.console();

        if (console != null) {
            char[] pass = console.readPassword("Enter password:");

            if (pass != null) {
                clientPolicy.password = new String(pass);
            }
        }
    }

    if (line.hasOption("namespace")) {
        args.namespace = line.getOptionValue("namespace");
    } else {
        args.namespace = "test";
    }

    if (line.hasOption("set")) {
        args.setName = line.getOptionValue("set");
    } else {
        args.setName = "testset";
    }

    if (line.hasOption("keys")) {
        this.nKeys = Integer.parseInt(line.getOptionValue("keys"));
    } else {
        this.nKeys = 100000;
    }

    if (line.hasOption("startkey")) {
        this.startKey = Integer.parseInt(line.getOptionValue("startkey"));
    }

    //Variables setting in case of command arguments passed with keys in File
    if (line.hasOption("keyFile")) {
        this.filepath = line.getOptionValue("keyFile");
        // Load the file
        keyList = Utils.readKeyFromFile(filepath);
        if (keyList.isEmpty()) {
            throw new Exception("File : '" + filepath + "' is empty,this file can't be processed.");
        }
        this.nKeys = keyList.size();
        this.startKey = 0;
        args.validate = false;

        if (line.hasOption("keyType")) {
            String keyType = line.getOptionValue("keyType");

            if (keyType.equals("S")) {
                args.keyType = KeyType.STRING;
            } else if (keyType.equals("I")) {
                if (Utils.isNumeric(keyList.get(0))) {
                    args.keyType = KeyType.INTEGER;
                } else {
                    throw new Exception(
                            "Invalid keyType '" + keyType + "' Key type doesn't match with file content type.");
                }
            } else {
                throw new Exception("Invalid keyType: " + keyType);
            }
        } else {
            args.keyType = KeyType.STRING;
        }

    }

    if (line.hasOption("bins")) {
        args.nBins = Integer.parseInt(line.getOptionValue("bins"));
    } else {
        args.nBins = 1;
    }

    if (line.hasOption("objectSpec")) {
        String[] objectsArr = line.getOptionValue("objectSpec").split(",");
        args.objectSpec = new DBObjectSpec[objectsArr.length];
        for (int i = 0; i < objectsArr.length; i++) {
            String[] objarr = objectsArr[i].split(":");
            DBObjectSpec dbobj = new DBObjectSpec();
            dbobj.type = objarr[0].charAt(0);
            if (objarr.length > 1) {
                dbobj.size = Integer.parseInt(objarr[1]);
            }
            args.objectSpec[i] = dbobj;
        }
    } else {
        args.objectSpec = new DBObjectSpec[1];
        DBObjectSpec dbobj = new DBObjectSpec();
        dbobj.type = 'I'; // If the object is not specified, it has one bin of integer type
        args.objectSpec[0] = dbobj;
    }

    if (line.hasOption("keyFile")) {
        args.workload = Workload.READ_FROM_FILE;
    } else {
        args.workload = Workload.READ_UPDATE;
    }
    args.readPct = 50;
    args.readMultiBinPct = 100;
    args.writeMultiBinPct = 100;

    if (line.hasOption("workload")) {
        String[] workloadOpts = line.getOptionValue("workload").split(",");
        String workloadType = workloadOpts[0];

        if (workloadType.equals("I")) {
            args.workload = Workload.INITIALIZE;
            this.initialize = true;

            if (workloadOpts.length > 1) {
                throw new Exception(
                        "Invalid workload number of arguments: " + workloadOpts.length + " Expected 1.");
            }
        } else if (workloadType.equals("RU") || workloadType.equals("RR")) {

            args.workload = Workload.READ_UPDATE;
            if (workloadType.equals("RR")) {
                args.writePolicy.recordExistsAction = RecordExistsAction.REPLACE;
            }

            if (workloadOpts.length < 2 || workloadOpts.length > 4) {
                throw new Exception(
                        "Invalid workload number of arguments: " + workloadOpts.length + " Expected 2 to 4.");
            }

            if (workloadOpts.length >= 2) {
                args.readPct = Integer.parseInt(workloadOpts[1]);

                if (args.readPct < 0 || args.readPct > 100) {
                    throw new Exception("Read-update workload read percentage must be between 0 and 100");
                }
            }

            if (workloadOpts.length >= 3) {
                args.readMultiBinPct = Integer.parseInt(workloadOpts[2]);
            }

            if (workloadOpts.length >= 4) {
                args.writeMultiBinPct = Integer.parseInt(workloadOpts[3]);
            }
        } else if (workloadType.equals("RMU")) {
            args.workload = Workload.READ_MODIFY_UPDATE;

            if (workloadOpts.length > 1) {
                throw new Exception(
                        "Invalid workload number of arguments: " + workloadOpts.length + " Expected 1.");
            }
        } else if (workloadType.equals("RMI")) {
            args.workload = Workload.READ_MODIFY_INCREMENT;

            if (workloadOpts.length > 1) {
                throw new Exception(
                        "Invalid workload number of arguments: " + workloadOpts.length + " Expected 1.");
            }
        } else if (workloadType.equals("RMD")) {
            args.workload = Workload.READ_MODIFY_DECREMENT;

            if (workloadOpts.length > 1) {
                throw new Exception(
                        "Invalid workload number of arguments: " + workloadOpts.length + " Expected 1.");
            }
        } else if (workloadType.equals("TXN")) {
            args.workload = Workload.TRANSACTION;
            args.transactionalWorkload = new TransactionalWorkload(workloadOpts);
            hasTxns = true;
        } else {
            throw new Exception("Unknown workload: " + workloadType);
        }
    }

    if (line.hasOption("throughput")) {
        args.throughput = Integer.parseInt(line.getOptionValue("throughput"));
    }

    if (line.hasOption("transactions")) {
        args.transactionLimit = Long.parseLong(line.getOptionValue("transactions"));
    }

    if (line.hasOption("timeout")) {
        int timeout = Integer.parseInt(line.getOptionValue("timeout"));
        args.readPolicy.timeout = timeout;
        args.writePolicy.timeout = timeout;
        args.batchPolicy.timeout = timeout;
    }

    if (line.hasOption("readTimeout")) {
        int timeout = Integer.parseInt(line.getOptionValue("readTimeout"));
        args.readPolicy.timeout = timeout;
        args.batchPolicy.timeout = timeout;
    }

    if (line.hasOption("writeTimeout")) {
        args.writePolicy.timeout = Integer.parseInt(line.getOptionValue("writeTimeout"));
    }

    if (line.hasOption("maxRetries")) {
        int maxRetries = Integer.parseInt(line.getOptionValue("maxRetries"));
        args.readPolicy.maxRetries = maxRetries;
        args.writePolicy.maxRetries = maxRetries;
        args.batchPolicy.maxRetries = maxRetries;
    }

    if (line.hasOption("sleepBetweenRetries")) {
        int sleepBetweenRetries = Integer.parseInt(line.getOptionValue("sleepBetweenRetries"));
        args.readPolicy.sleepBetweenRetries = sleepBetweenRetries;
        args.writePolicy.sleepBetweenRetries = sleepBetweenRetries;
        args.batchPolicy.sleepBetweenRetries = sleepBetweenRetries;
    }

    if (line.hasOption("consistencyLevel")) {
        String level = line.getOptionValue("consistencyLevel");

        if (level.equals("all")) {
            args.readPolicy.consistencyLevel = ConsistencyLevel.CONSISTENCY_ALL;
            args.writePolicy.consistencyLevel = ConsistencyLevel.CONSISTENCY_ALL;
            args.batchPolicy.consistencyLevel = ConsistencyLevel.CONSISTENCY_ALL;
        } else if (!level.equals("one")) {
            throw new Exception("Invalid consistencyLevel: " + level);
        }
    }

    if (line.hasOption("commitLevel")) {
        String level = line.getOptionValue("commitLevel");

        if (level.equals("master")) {
            args.writePolicy.commitLevel = CommitLevel.COMMIT_MASTER;
        } else if (!level.equals("all")) {
            throw new Exception("Invalid commitLevel: " + level);
        }
    }

    if (line.hasOption("prole")) {
        clientPolicy.requestProleReplicas = true;
        args.readPolicy.replica = Replica.MASTER_PROLES;
    }

    if (line.hasOption("threads")) {
        this.nThreads = Integer.parseInt(line.getOptionValue("threads"));

        if (this.nThreads < 1) {
            throw new Exception("Client threads (-z) must be > 0");
        }
    } else {
        this.nThreads = 16;
    }

    if (line.hasOption("reportNotFound")) {
        args.reportNotFound = true;
    }

    if (line.hasOption("validate")) {
        args.validate = true;
    }

    if (line.hasOption("debug")) {
        args.debug = true;
    }

    if (line.hasOption("batchSize")) {
        args.batchSize = Integer.parseInt(line.getOptionValue("batchSize"));
    }

    args.storeType = StorageType.KVS;
    if (line.hasOption("storeType")) {
        String storetype = line.getOptionValue("storeType");
        if (storetype.equals("LLIST")) {
            args.storeType = StorageType.LLIST;
        } else if (storetype.equals("LSTACK")) {
            args.storeType = StorageType.LSTACK;
        }
    }

    if (line.hasOption("batchThreads")) {
        args.batchPolicy.maxConcurrentThreads = Integer.parseInt(line.getOptionValue("batchThreads"));
    }

    if (line.hasOption("asyncMaxCommands")) {
        this.clientPolicy.asyncMaxCommands = Integer.parseInt(line.getOptionValue("asyncMaxCommands"));
    }

    if (line.hasOption("asyncSelectorTimeout")) {
        this.clientPolicy.asyncSelectorTimeout = Integer.parseInt(line.getOptionValue("asyncSelectorTimeout"));
    }

    if (line.hasOption("asyncSelectorThreads")) {
        this.clientPolicy.asyncSelectorThreads = Integer.parseInt(line.getOptionValue("asyncSelectorThreads"));
    }

    if (line.hasOption("asyncTaskThreads")) {
        this.asyncTaskThreads = Integer.parseInt(line.getOptionValue("asyncTaskThreads"));

        if (asyncTaskThreads == 0) {
            this.clientPolicy.asyncTaskThreadPool = Executors.newCachedThreadPool();
        } else {
            this.clientPolicy.asyncTaskThreadPool = Executors.newFixedThreadPool(asyncTaskThreads);
        }
    }

    if (line.hasOption("latency")) {
        String[] latencyOpts = line.getOptionValue("latency").split(",");

        if (latencyOpts.length >= 1 && "ycsb".equalsIgnoreCase(latencyOpts[0])) {
            int warmupCount = 0;
            if (latencyOpts.length == 2) {
                warmupCount = Integer.parseInt(latencyOpts[1]);
            }
            counters.read.latency = new LatencyManagerYcsb(" read", warmupCount);
            counters.write.latency = new LatencyManagerYcsb("write", warmupCount);
            if (hasTxns) {
                counters.transaction.latency = new LatencyManagerYcsb(" txns", warmupCount);
            }
        } else if (latencyOpts.length != 2 && latencyOpts.length != 3) {
            throw new Exception(
                    "Latency expects either \"ycsb\" or 2 or 3 arguments. Received: " + latencyOpts.length);
        } else {
            int columns = Integer.parseInt(latencyOpts[0]);
            int bitShift = Integer.parseInt(latencyOpts[1]);
            boolean showMicroSeconds = false;
            if (latencyOpts.length == 3) {
                if ("us".equalsIgnoreCase(latencyOpts[2])) {
                    showMicroSeconds = true;
                }
            }
            counters.read.latency = new LatencyManagerAerospike(columns, bitShift, showMicroSeconds);
            counters.write.latency = new LatencyManagerAerospike(columns, bitShift, showMicroSeconds);
            if (hasTxns) {
                counters.transaction.latency = new LatencyManagerAerospike(columns, bitShift, showMicroSeconds);
            }
        }
    }

    if (!line.hasOption("random")) {
        args.setFixedBins();
    }

    System.out.println("Benchmark: " + this.hosts[0] + ":" + this.port + ", namespace: " + args.namespace
            + ", set: " + (args.setName.length() > 0 ? args.setName : "<empty>") + ", threads: " + this.nThreads
            + ", workload: " + args.workload);

    if (args.workload == Workload.READ_UPDATE) {
        System.out.print("read: " + args.readPct + '%');
        System.out.print(" (all bins: " + args.readMultiBinPct + '%');
        System.out.print(", single bin: " + (100 - args.readMultiBinPct) + "%)");

        System.out.print(", write: " + (100 - args.readPct) + '%');
        System.out.print(" (all bins: " + args.writeMultiBinPct + '%');
        System.out.println(", single bin: " + (100 - args.writeMultiBinPct) + "%)");
    }

    System.out.println("keys: " + this.nKeys + ", start key: " + this.startKey + ", transactions: "
            + args.transactionLimit + ", bins: " + args.nBins + ", random values: " + (args.fixedBins == null)
            + ", throughput: " + (args.throughput == 0 ? "unlimited" : (args.throughput + " tps")));

    if (args.workload != Workload.INITIALIZE) {
        System.out.println("read policy: timeout: " + args.readPolicy.timeout + ", maxRetries: "
                + args.readPolicy.maxRetries + ", sleepBetweenRetries: " + args.readPolicy.sleepBetweenRetries
                + ", consistencyLevel: " + args.readPolicy.consistencyLevel + ", replica: "
                + args.readPolicy.replica + ", reportNotFound: " + args.reportNotFound);
    }

    System.out.println("write policy: timeout: " + args.writePolicy.timeout + ", maxRetries: "
            + args.writePolicy.maxRetries + ", sleepBetweenRetries: " + args.writePolicy.sleepBetweenRetries
            + ", commitLevel: " + args.writePolicy.commitLevel);

    if (args.batchSize > 1) {
        System.out.println(
                "batch size: " + args.batchSize + ", batch threads: " + args.batchPolicy.maxConcurrentThreads);
    }

    if (this.asyncEnabled) {
        String threadPoolName = (clientPolicy.asyncTaskThreadPool == null) ? "none"
                : clientPolicy.asyncTaskThreadPool.getClass().getName();
        System.out.println("Async: MaxConnTotal " + clientPolicy.asyncMaxCommands + ", MaxConnAction: "
                + clientPolicy.asyncMaxCommandAction + ", SelectorTimeout: " + clientPolicy.asyncSelectorTimeout
                + ", SelectorThreads: " + clientPolicy.asyncSelectorThreads + ", TaskThreadPool: "
                + threadPoolName);
    }

    int binCount = 0;

    for (DBObjectSpec spec : args.objectSpec) {
        System.out.print("bin[" + binCount + "]: ");

        switch (spec.type) {
        case 'I':
            System.out.println("integer");
            break;

        case 'S':
            System.out.println("string[" + spec.size + "]");
            break;

        case 'B':
            System.out.println("byte[" + spec.size + "]");
            break;
        }
        binCount++;
    }

    System.out.println("debug: " + args.debug);

    Log.Level level = (args.debug) ? Log.Level.DEBUG : Log.Level.INFO;
    Log.setLevel(level);
    Log.setCallback(this);
    args.updatePolicy = cloneWritePolicy(args.writePolicy);
    args.updatePolicy.recordExistsAction = RecordExistsAction.UPDATE;
    args.replacePolicy = cloneWritePolicy(args.writePolicy);
    args.replacePolicy.recordExistsAction = RecordExistsAction.REPLACE;

    clientPolicy.failIfNotConnected = true;
}

From source file:org.ejbca.ui.cli.ca.CaType.java

@Override
public CommandResult execute(ParameterContainer parameters) {
    // Install BC provider
    CryptoProviderTools.installBCProviderIfNotAvailable();

    String profileName = parameters.get(CERTIFICATE_PROFILE_KEY);
    final String superAdminCN = parameters.get(SUPERADMIN_CN_KEY);
    //Default is X509
    final CaType type;
    if (parameters.get(TYPE_KEY) != null) {
        type = CaType.lookupCaType(parameters.get(TYPE_KEY));
        if (type == null) {
            log.error("CA type of name " + parameters.get(TYPE_KEY) + " unknown. Available types: "
                    + CaType.getTypeNames());
            return CommandResult.FUNCTIONAL_FAILURE;
        }//  w  w w  .ja v a  2 s  .c  om
    } else {
        type = CaType.X509;
    }
    final String explicitEcc = (parameters.get(EXPLICIT_ECC_KEY) != null ? Boolean.TRUE.toString()
            : Boolean.FALSE.toString());
    final String extcachainName = parameters.get(EXTERNAL_CHAIN_KEY);

    final String caname = parameters.get(CA_NAME_KEY);
    final String dn = CertTools.stringToBCDNString(StringTools.strip(parameters.get(DN_KEY)));
    final String catokentype = parameters.get(TOKEN_TYPE_KEY);
    String catokenpassword = StringTools.passwordDecryption(parameters.get(TOKEN_PASSWORD_KEY),
            "ca.tokenpassword");
    if (StringUtils.equals(catokenpassword, "prompt")) {
        getLogger().info("Enter CA token password: ");
        getLogger().info("");
        catokenpassword = String.valueOf(System.console().readPassword());
    }
    final String keyspec = parameters.get(KEY_SPEC_KEY);
    final String keytype = parameters.get(KEY_TYPE_KEY);
    final long validity = Long.parseLong(parameters.get(VALIDITY_KEY));
    String policyId = parameters.get(POLICY_ID_KEY);
    final ArrayList<CertificatePolicy> policies = new ArrayList<CertificatePolicy>(1);
    if ((policyId != null) && (policyId.toLowerCase().trim().equals("null"))) {
        policyId = null;
    } else {
        String[] array = policyId.split(" ");
        for (int i = 0; i < array.length; i += 2) {
            String id = array[i + 0];
            String cpsurl = "";
            if (array.length > i + 1) {
                cpsurl = array[i + 1];
            }
            policies.add(new CertificatePolicy(id, CertificatePolicy.id_qt_cps, cpsurl));
        }
    }
    String signAlg = parameters.get(SIGNING_ALGORITHM_KEY);
    Properties cryptoTokenProperties = new Properties();
    String caTokenPropertiesFile = parameters.get(CA_TOKEN_PROPERTIES_KEY);
    if (caTokenPropertiesFile != null && "soft".equals(catokentype)) {
        log.error("Can't define a CAToken properties file for a soft token.");
        return CommandResult.FUNCTIONAL_FAILURE;
    } else if (caTokenPropertiesFile != null) {
        if ((caTokenPropertiesFile != null) && (!caTokenPropertiesFile.equalsIgnoreCase("null"))) {
            File file = new File(caTokenPropertiesFile);
            if (!file.exists()) {
                log.error("CA Token propoerties file " + caTokenPropertiesFile + " does not exist.");
                return CommandResult.FUNCTIONAL_FAILURE;
            } else if (file.isDirectory()) {
                log.error("CA Token propoerties file " + caTokenPropertiesFile + " is a directory.");
                return CommandResult.FUNCTIONAL_FAILURE;
            } else {
                try {
                    cryptoTokenProperties.load(new FileInputStream(caTokenPropertiesFile));
                } catch (FileNotFoundException e) {
                    //Can't happen
                    throw new IllegalStateException(
                            "Newly referenced file " + caTokenPropertiesFile + " was not found.", e);
                } catch (IOException e) {
                    throw new IllegalStateException("Unknown exception was caught when reading input stream",
                            e);
                }
            }
        }
    }
    int signedByCAId = CAInfo.SELFSIGNED;
    if (parameters.get(SIGNED_BY) != null) {
        if (StringUtils.equalsIgnoreCase("External", parameters.get(SIGNED_BY))) {
            signedByCAId = CAInfo.SIGNEDBYEXTERNALCA;
            if (extcachainName == null) {
                log.error("Signing by external CA requires parameter " + EXTERNAL_CHAIN_KEY);
                return CommandResult.FUNCTIONAL_FAILURE;
            }
        } else {
            signedByCAId = Integer.valueOf(parameters.get(SIGNED_BY));
        }
    }

    // Check that the CA doesn't exist already
    getLogger().debug("Checking that CA doesn't exist: " + caname);
    if (getCAInfo(getAuthenticationToken(), caname) != null) {
        getLogger().error("Error: CA '" + caname + "' exists already");
        return CommandResult.FUNCTIONAL_FAILURE;
    }

    // Get the profile ID from the name if we specified a certain profile name
    int certificateProfileId = CertificateProfileConstants.CERTPROFILE_FIXED_ROOTCA;
    if (profileName == null) {
        if (signedByCAId == CAInfo.SELFSIGNED) {
            profileName = "ROOTCA";
        } else {
            profileName = "SUBCA";
            certificateProfileId = CertificateProfileConstants.CERTPROFILE_FIXED_SUBCA;
        }
    } else {
        certificateProfileId = EjbRemoteHelper.INSTANCE.getRemoteSession(CertificateProfileSessionRemote.class)
                .getCertificateProfileId(profileName);
        if (certificateProfileId == 0) {
            getLogger().info("Error: Certificate profile with name '" + profileName + "' does not exist.");
            return CommandResult.FUNCTIONAL_FAILURE;
        }

        CertificateProfile certificateProfile = EjbRemoteHelper.INSTANCE
                .getRemoteSession(CertificateProfileSessionRemote.class).getCertificateProfile(profileName);
        if (certificateProfile.getType() != CertificateConstants.CERTTYPE_ROOTCA
                && certificateProfile.getType() != CertificateConstants.CERTTYPE_SUBCA) {
            getLogger().info("Error: Certificate profile " + profileName + " is not of type ROOTCA or SUBCA.");
            return CommandResult.FUNCTIONAL_FAILURE;
        }
    }

    if (KeyTools.isUsingExportableCryptography()) {
        getLogger().warn("WARNING!");
        getLogger().warn("WARNING: Using exportable strength crypto!");
        getLogger().warn("WARNING!");
        getLogger().warn(
                "The Unlimited Strength Crypto policy files have not been installed. EJBCA may not function correctly using exportable crypto.");
        getLogger().warn(
                "Please install the Unlimited Strength Crypto policy files as documented in the Installation guide.");
        getLogger().warn("Sleeping 10 seconds...");
        getLogger().warn("");
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            throw new IllegalStateException("Thread.sleep was interrupted for unknown reason.", e);
        }
    }
    getLogger().info("Initializing CA");

    getLogger().info("Generating rootCA keystore:");
    getLogger().info("CA Type:" + type.getTypeName());
    getLogger().info("CA name: " + caname);
    getLogger().info("SuperAdmin CN: " + superAdminCN);
    getLogger().info("DN: " + dn);
    getLogger().info("CA token type: " + catokentype);
    getLogger().info("CA token password: " + (catokenpassword == null ? "null" : "hidden"));
    getLogger().info("Keytype: " + keytype);
    getLogger().info("Keyspec: " + keyspec);
    getLogger().info("Validity (days): " + validity);
    getLogger().info("Policy ID: " + policyId);
    getLogger().info("Signature alg: " + signAlg);
    getLogger().info("Certificate profile: " + profileName);
    getLogger().info("CA token properties: " + cryptoTokenProperties.toString());
    if (StringUtils.equalsIgnoreCase(explicitEcc, "true")) {
        // Set if we should use explicit ECC parameters of not. On Java 6 this renders the created CA certificate not serializable
        getLogger().info("Explicit ECC public key parameters: " + explicitEcc);
        cryptoTokenProperties.setProperty(CryptoToken.EXPLICIT_ECC_PUBLICKEY_PARAMETERS, explicitEcc);
    }
    try {
        String signedByStr = "Signed by: ";
        if ((signedByCAId != CAInfo.SELFSIGNED) && (signedByCAId != CAInfo.SIGNEDBYEXTERNALCA)) {
            try {
                CAInfo cainfo = EjbRemoteHelper.INSTANCE.getRemoteSession(CaSessionRemote.class)
                        .getCAInfo(getAuthenticationToken(), signedByCAId);
                signedByStr += cainfo.getName();
            } catch (CADoesntExistsException e) {
                throw new IllegalArgumentException("CA with id " + signedByCAId + " does not exist.");
            }
        } else if (signedByCAId == CAInfo.SELFSIGNED) {
            signedByStr += "Self signed";
        } else if (signedByCAId == CAInfo.SIGNEDBYEXTERNALCA) {
            signedByStr += "External CA";
        }
        getLogger().info(signedByStr);

        if (superAdminCN != null) {
            try {
                initAuthorizationModule(getAuthenticationToken(), dn.hashCode(), superAdminCN);
            } catch (RoleExistsException e) {
                log.error("Tryin to initialize Authorization module (since " + SUPERADMIN_CN_KEY
                        + " was set), but module is already initialized.");
                return CommandResult.FUNCTIONAL_FAILURE;
            }
        }
        // Transform our mixed properties into CA Token properties and cryptoTokenProperties
        final Properties caTokenProperties = new Properties();
        final String defaultAlias = cryptoTokenProperties
                .getProperty(CATokenConstants.CAKEYPURPOSE_DEFAULT_STRING);
        if (defaultAlias != null) {
            caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_DEFAULT_STRING, defaultAlias);
            cryptoTokenProperties.remove(CATokenConstants.CAKEYPURPOSE_DEFAULT_STRING);
        } else {
            caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_DEFAULT_STRING,
                    CAToken.SOFTPRIVATEDECKEYALIAS);
        }
        final String certSignAlias = cryptoTokenProperties
                .getProperty(CATokenConstants.CAKEYPURPOSE_CERTSIGN_STRING);
        if (certSignAlias != null) {
            caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_CERTSIGN_STRING, certSignAlias);
            cryptoTokenProperties.remove(CATokenConstants.CAKEYPURPOSE_CERTSIGN_STRING);
        } else {
            caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_CERTSIGN_STRING,
                    CAToken.SOFTPRIVATESIGNKEYALIAS);
        }
        final String crlSignAlias = cryptoTokenProperties
                .getProperty(CATokenConstants.CAKEYPURPOSE_CRLSIGN_STRING);
        if (crlSignAlias != null) {
            caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_CRLSIGN_STRING, crlSignAlias);
            cryptoTokenProperties.remove(CATokenConstants.CAKEYPURPOSE_CRLSIGN_STRING);
        } else {
            final String certSignValue = caTokenProperties
                    .getProperty(CATokenConstants.CAKEYPURPOSE_CERTSIGN_STRING);
            caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_CRLSIGN_STRING, certSignValue);
        }
        final String hardTokenEncAlias = cryptoTokenProperties
                .getProperty(CATokenConstants.CAKEYPURPOSE_HARDTOKENENCRYPT_STRING);
        if (hardTokenEncAlias != null) {
            caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_HARDTOKENENCRYPT_STRING,
                    hardTokenEncAlias);
            cryptoTokenProperties.remove(CATokenConstants.CAKEYPURPOSE_HARDTOKENENCRYPT_STRING);
        }
        final String keyEncAlias = cryptoTokenProperties
                .getProperty(CATokenConstants.CAKEYPURPOSE_KEYENCRYPT_STRING);
        if (keyEncAlias != null) {
            caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_KEYENCRYPT_STRING, keyEncAlias);
            cryptoTokenProperties.remove(CATokenConstants.CAKEYPURPOSE_KEYENCRYPT_STRING);
        }
        final String testKeyAlias = cryptoTokenProperties
                .getProperty(CATokenConstants.CAKEYPURPOSE_TESTKEY_STRING);
        if (testKeyAlias != null) {
            caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_TESTKEY_STRING, testKeyAlias);
            cryptoTokenProperties.remove(CATokenConstants.CAKEYPURPOSE_TESTKEY_STRING);
        }
        // If authentication code is provided as "null", use the default token password for soft tokens (from cesecore.properties), and auto activation
        // If a user defined authentication code is provided, use this and do not enable auto activation for soft tokens
        final char[] authenticationCode;
        if (StringUtils.equalsIgnoreCase(catokenpassword, "null")) {
            authenticationCode = null;
            // auto activation is enabled by default when using the default soft token pwd, which is used by default
        } else {
            authenticationCode = catokenpassword.toCharArray();
        }
        // We must do this in order to not set the default password when creating a new soft CA token
        // A bit tricky, but thats how it is as of EJBCA 5.0.x, 2012-05.
        final String className;
        if (StringUtils.equalsIgnoreCase(catokentype, "soft")) {
            className = SoftCryptoToken.class.getName();
            if (authenticationCode != null) {
                getLogger().info("Non default password used for soft CA token, auto activation disabled.");
                cryptoTokenProperties.setProperty(SoftCryptoToken.NODEFAULTPWD, "true");
            }
        } else {
            className = PKCS11CryptoToken.class.getName();
        }
        // Create the CryptoToken
        final CryptoTokenManagementSessionRemote cryptoTokenManagementSession = EjbRemoteHelper.INSTANCE
                .getRemoteSession(CryptoTokenManagementSessionRemote.class);
        int cryptoTokenId;
        try {
            try {
                cryptoTokenId = cryptoTokenManagementSession.createCryptoToken(getAuthenticationToken(), caname,
                        className, cryptoTokenProperties, null, authenticationCode);
            } catch (CryptoTokenNameInUseException e) {
                // If the name was already in use we simply add a timestamp to the name to make it unique
                final String postfix = "_" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
                try {
                    cryptoTokenId = cryptoTokenManagementSession.createCryptoToken(getAuthenticationToken(),
                            caname + postfix, className, cryptoTokenProperties, null, authenticationCode);
                } catch (CryptoTokenNameInUseException e1) {
                    //Shouldn't be able to happen.
                    throw new IllegalStateException(
                            "Crypto token name was in use, even though a unique name was just generated.", e);
                }
            }
        } catch (NoSuchSlotException e) {
            log.error("Slot as defined in the file " + caTokenPropertiesFile + " was not found: "
                    + e.getMessage());
            return CommandResult.FUNCTIONAL_FAILURE;
        } catch (CryptoTokenAuthenticationFailedException e) {
            log.error("Authentication to crypto token failed: " + e.getMessage());
            return CommandResult.FUNCTIONAL_FAILURE;
        }
        // Create the CA Token
        final CAToken caToken = new CAToken(cryptoTokenId, caTokenProperties);
        caToken.setSignatureAlgorithm(signAlg);
        caToken.setEncryptionAlgorithm(AlgorithmConstants.SIGALG_SHA1_WITH_RSA);
        // Generate CA keys if it is a soft CryptoToken
        if ("soft".equals(catokentype)) {
            final String signKeyAlias = caToken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN);
            final String signKeySpecification = "DSA".equals(keytype) ? "DSA" + keyspec : keyspec;

            try {
                cryptoTokenManagementSession.createKeyPair(getAuthenticationToken(), cryptoTokenId,
                        signKeyAlias, signKeySpecification);
            } catch (InvalidAlgorithmParameterException e) {
                log.error(signKeySpecification + " was not a valid alias: " + e.getMessage());
                return CommandResult.FUNCTIONAL_FAILURE;
            } catch (InvalidKeyException e) {
                log.error("Key generation for alias " + signKeyAlias + " failed." + e.getMessage());
                return CommandResult.FUNCTIONAL_FAILURE;
            }
            final String defaultKeyAlias = caToken
                    .getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_KEYENCRYPT);
            // Decryption key must be RSA
            final String defaultKeySpecification = "RSA".equals(keytype) ? keyspec : "2048";
            try {
                cryptoTokenManagementSession.createKeyPair(getAuthenticationToken(), cryptoTokenId,
                        defaultKeyAlias, defaultKeySpecification);
            } catch (InvalidAlgorithmParameterException e) {
                log.error(defaultKeySpecification + " was not a valid alias: " + e.getMessage());
                return CommandResult.FUNCTIONAL_FAILURE;
            } catch (InvalidKeyException e) {
                log.error("Key generation for alias " + defaultKeyAlias + " failed: " + e.getMessage());
                return CommandResult.FUNCTIONAL_FAILURE;
            }

        }
        // Create the CA Info
        CAInfo cainfo = null;
        switch (type) {
        case CVC:
            // Get keysequence from SERIALNUMBER in DN is it exists
            final String keysequence = CertTools.getPartFromDN(dn, "SN");
            if (keysequence != null) {
                getLogger().info("CVC key sequence: " + keysequence);
                caToken.setKeySequence(keysequence);
                if (StringUtils.isNumeric(keysequence)) {
                    getLogger().info("CVC key sequence format is numeric.");
                    caToken.setKeySequenceFormat(StringTools.KEY_SEQUENCE_FORMAT_NUMERIC);
                } else {
                    getLogger().info("CVC key sequence format is alphanumeric.");
                    caToken.setKeySequenceFormat(StringTools.KEY_SEQUENCE_FORMAT_ALPHANUMERIC);
                }
            }
            cainfo = createCVCCAInfo(dn, caname, certificateProfileId, validity, signedByCAId, caToken);
            break;
        case X509:
            //Default, slip below.
        default:
            // Create and active OSCP CA Service.
            ArrayList<ExtendedCAServiceInfo> extendedcaservices = new ArrayList<ExtendedCAServiceInfo>();
            String extendedServiceKeySpec = keyspec;
            if (keytype.equals(AlgorithmConstants.KEYALGORITHM_RSA)) {
                // Never use larger keys than 2048 bit RSA for OCSP signing
                int len = Integer.parseInt(extendedServiceKeySpec);
                if (len > 2048) {
                    extendedServiceKeySpec = "2048";
                }
            }
            extendedcaservices.add(new XKMSCAServiceInfo(ExtendedCAServiceInfo.STATUS_INACTIVE,
                    "CN=XKMSCertificate, " + dn, "", extendedServiceKeySpec, keytype));
            extendedcaservices.add(new CmsCAServiceInfo(ExtendedCAServiceInfo.STATUS_INACTIVE,
                    "CN=CmsCertificate, " + dn, "", extendedServiceKeySpec, keytype));
            extendedcaservices.add(new HardTokenEncryptCAServiceInfo(ExtendedCAServiceInfo.STATUS_ACTIVE));
            extendedcaservices.add(new KeyRecoveryCAServiceInfo(ExtendedCAServiceInfo.STATUS_ACTIVE));
            cainfo = createX509CaInfo(dn, caname, certificateProfileId, validity, signedByCAId, caToken,
                    policies, extendedcaservices);
            break;
        }
        getLogger().info("Creating CA...");
        // Make an error control before starting do do something else.
        List<Certificate> cachain = null;
        if (cainfo.getSignedBy() == CAInfo.SIGNEDBYEXTERNALCA) {
            try {
                cachain = CertTools.getCertsFromPEM(extcachainName);
            } catch (CertificateException e) {
                log.error("Certificate file " + extcachainName + " did not contain a correct certificate.");
                return CommandResult.FUNCTIONAL_FAILURE;
            }
            if (cachain == null || cachain.isEmpty()) {
                log.error(
                        extcachainName + " does not seem to exist or contain any certificates in PEM format.");
                return CommandResult.FUNCTIONAL_FAILURE;
            }
        }
        try {
            EjbRemoteHelper.INSTANCE.getRemoteSession(CAAdminSessionRemote.class)
                    .createCA(getAuthenticationToken(), cainfo);
        } catch (CAExistsException e) {
            log.error("CA " + caname + " already exists.");
            return CommandResult.FUNCTIONAL_FAILURE;
        } catch (InvalidAlgorithmException e) {
            log.error("Algirithm was not valid: " + e.getMessage());
            return CommandResult.FUNCTIONAL_FAILURE;
        }
        try {
            if (StringUtils.equalsIgnoreCase(explicitEcc, "true")) {
                getLogger().info(
                        "Not re-reading CAInfo, since explicit ECC parameters were used, which is not serializable on Java 6. Use Web GUI for further interactions.");
            } else {
                CAInfo newInfo;

                newInfo = EjbRemoteHelper.INSTANCE.getRemoteSession(CaSessionRemote.class)
                        .getCAInfo(getAuthenticationToken(), caname);

                int caid = newInfo.getCAId();
                getLogger().info("CAId for created CA: " + caid);
            }
            if (cainfo.getSignedBy() == CAInfo.SIGNEDBYEXTERNALCA) {
                getLogger().info("Creating a CA signed by an external CA, creating certificate request.");
                CAInfo info = EjbRemoteHelper.INSTANCE.getRemoteSession(CaSessionRemote.class)
                        .getCAInfo(getAuthenticationToken(), caname);
                if (info.getStatus() != CAConstants.CA_WAITING_CERTIFICATE_RESPONSE) {
                    log.error(
                            "Creating a CA signed by an external CA should result in CA having status, CA_WAITING_CERTIFICATE_RESPONSE. Terminating process, please troubleshoot.");
                    return CommandResult.FUNCTIONAL_FAILURE;
                }
                byte[] request;
                try {
                    request = EjbRemoteHelper.INSTANCE.getRemoteSession(CAAdminSessionRemote.class).makeRequest(
                            getAuthenticationToken(), info.getCAId(), cachain,
                            info.getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN));
                } catch (CertPathValidatorException e) {
                    log.error("Error creating certificate request for CA:" + e.getMessage());
                    return CommandResult.FUNCTIONAL_FAILURE;
                }
                final String filename = info.getName() + "_csr.der";
                FileOutputStream fos = new FileOutputStream(filename);
                fos.write(request);
                fos.close();
                getLogger().info(
                        "Created CSR for CA, to be sent to external CA. Wrote CSR to file '" + filename + "'.");
            } else {
                getLogger().info("Created and published initial CRL.");
            }
        } catch (CADoesntExistsException e) {
            throw new IllegalStateException("Newly created CA does not exist.", e);
        }
        getLogger().info("CA initialized");
        getLogger().info("Note that any open browser sessions must be restarted to interact with this CA.");
    } catch (AuthorizationDeniedException e) {
        log.error("Current CLI user not authorized to create CA: " + e.getMessage());
        return CommandResult.AUTHORIZATION_FAILURE;
    } catch (CryptoTokenOfflineException e) {
        log.error("Crypto token was unavailable: " + e.getMessage());
        return CommandResult.FUNCTIONAL_FAILURE;
    } catch (IOException e) {
        throw new IllegalStateException("Unknown IOException was caught.", e);
    }
    return CommandResult.SUCCESS;
}

From source file:com.mijecu25.sqlplus.SQLPlus.java

/**
 * Create an SQLPlusConnection by taking the credentials from the user.
 *
 * @throws IOException if there is an I/O error while reading input from the user.
 * @throws SQLException if there is an error while establishing a connection.
 *///from   ww w  . j a  v a2 s.  c  o  m
private static void createSQLPlusConnection() throws IOException, SQLException {
    if (false) {
        System.out.println("You will now enter the credentials to connect to your database");

        // Add credentials
        System.out.print(SQLPlus.PROMPT + "Host(default " + SQLPlusConnection.getDefaultHost() + "): ");
        String host = SQLPlus.console.readLine().trim();
        SQLPlus.logger.info("User entered host:" + host);
        // TODO validate host        

        //        if(!host.isEmpty()) {
        //            // The Console object for the JVM could not be found. Alert the user and throw a
        //            // NullPointerException that the caller will handle
        //            SQLPlus.logger.fatal(Messages.FATAL + "The user wants to use a host that is not supported");
        //            System.out.println(Messages.ERROR + SQLPlus.PROGRAM_NAME + " does not support the host that you entered");
        //            
        //            SQLPlus.logger.info("Throwing a " + IllegalArgumentException.class.getSimpleName() + " to the "
        //                    + "calling class");
        //            throw new IllegalArgumentException();  
        //        }

        System.out.print(SQLPlus.PROMPT + "Database(default " + SQLPlusConnection.getDefaultDatabase() + "): ");
        String database = SQLPlus.console.readLine().trim();
        SQLPlus.logger.info("User entered database:" + database);

        if (database.isEmpty()) {
            database = SQLPlusConnection.getDefaultDatabase();
            SQLPlus.logger.info("Using default database:" + database);
        }

        String port = "";

        // While the port is not numeric
        while (!StringUtils.isNumeric(port)) {
            System.out.print(SQLPlus.PROMPT + "Port (default " + SQLPlusConnection.getDefaultPort() + "): ");
            port = SQLPlus.console.readLine().trim();
            SQLPlus.logger.info("Port entered: " + port);
            SQLPlus.logger.info("Port string length: " + port.length());

            // If the port is empty
            if (port.isEmpty()) {
                // Assume that the user wants to use the default port. Continue to the next step
                break;
            }

            // If the port has more than 5 numbers or is not numberic 
            if (port.length() > 5 || !StringUtils.isNumeric(port)) {
                SQLPlus.logger.warn("The user provided an invalid port number: " + port);
                System.out.println(
                        Messages.WARNING + "You need to provided a valid port number " + "from 0 to 65535");

                // Set the port to the empty string to ask the user again
                port = "";
            }
        }
        SQLPlus.logger.info("User entered port:" + port);

        String username = "";

        // While the username is empty
        while (username.isEmpty()) {
            System.out.print(SQLPlus.PROMPT + "Username: ");
            username = SQLPlus.console.readLine().trim();

            // If the username is empty
            if (username.isEmpty()) {
                SQLPlus.logger.warn("The user did not provide a username");
                System.out.println(Messages.WARNING + "You cannot have an empty username");
            }
        }
        SQLPlus.logger.info("User entered username:" + username);

        // Reset the jline console since we are going to use the regular console to securely get the password
        SQLPlus.resetConsole();

        // Get the console for safe password entry
        Console javaConsole = System.console();

        // If the console is null
        if (javaConsole == null) {
            // The Console object for the JVM could not be found. Alert the user and throw a
            // NullPointerException that the caller will handle
            SQLPlus.logger.fatal("A JVM Console object to enter a password was not found");
            System.out.println(
                    Messages.ERROR + SQLPlus.PROGRAM_NAME + " was not able to find your JVM's Console object. "
                            + "Try running " + SQLPlus.PROGRAM_NAME + " from the command line.");

            SQLPlus.logger.info(
                    "Throwing a " + NullPointerException.class.getSimpleName() + " to the " + "calling class");
            throw new NullPointerException();
        }

        // Read the password without echoing the result
        char[] password = javaConsole.readPassword("%s", SQLPlus.PROMPT + "Password:");

        // If the password is null
        if (password == null) {
            // The Console object for the JVM could not be found. Alert the user and throw a
            // NullPointerException that the caller will handle
            SQLPlus.logger.fatal("The password captured by the JVM Console object returned null");
            System.out.println(
                    Messages.ERROR + SQLPlus.PROGRAM_NAME + " was not able to get the password you entered from"
                            + "your JVM's Console object. Try running " + SQLPlus.PROGRAM_NAME
                            + " from the command line or a different" + "terminal program");

            SQLPlus.logger.info(
                    "Throwing a " + NullPointerException.class.getSimpleName() + " to the " + "calling class");
            throw new NullPointerException();
        }
        SQLPlus.logger.info("User entered some password");
        System.out.println();

        // Create a connection based on the database system
        switch (database) {
        case SQLPlusMySQLConnection.MYSQL:
            // If the default port and host are used
            if (port.isEmpty() && host.isEmpty()) {
                SQLPlus.logger.info("Connection with username, password");
                sqlPlusConnection = SQLPlusMySQLConnection.getConnection(username, password);
            }
            // If the default port is used
            else if (port.isEmpty()) {
                SQLPlus.logger.info("Connection with username, password, and host");
                sqlPlusConnection = SQLPlusMySQLConnection.getConnection(username, password, host);
            }
            // All the values were provided by the user
            else {
                SQLPlus.logger.info("Connection with all credentials");
                sqlPlusConnection = SQLPlusMySQLConnection.getConnection(username, password, host, port);
            }
            break;
        default:
            // Database entered is not supported
            SQLPlus.logger.fatal(Messages.FATAL + "The database system " + database + " is not supported");
            System.out.println(
                    Messages.ERROR + SQLPlus.PROGRAM_NAME + " does not support the database that you entered");

            SQLPlus.logger.info("Throwing a " + IllegalArgumentException.class.getSimpleName() + " to the "
                    + "calling class");
            throw new IllegalArgumentException();
        }

        // Delete any traces of password in memory by filling the password array with with random characters
        // to minimize the lifetime of sensitive data in memory. Then call the garbage collections
        java.util.Arrays.fill(password, Character.MIN_VALUE);
        System.gc();

        // Recreate the jline console
        SQLPlus.console = new ConsoleReader();
        SQLPlus.console.setHandleUserInterrupt(true);
    }

    // TODO remove this which is for testing
    SQLPlus.logger.info("Connection with username, password, and host");
    SQLPlusConnection sqlPlusConnection = SQLPlusMySQLConnection.getConnection("sqlplus", new char[0],
            SQLPlusConnection.getDefaultHost());

    // TODO this does have to be in the final code
    SQLPlus.logger.info("Created and returning a SQLPlusConnection " + sqlPlusConnection);
    SQLPlus.sqlPlusConnection = sqlPlusConnection;
}

From source file:org.apache.juddi.samples.JuddiAdminService.java

void viewRemoveRemoteNode(String authtoken) throws Exception {
    List<Node> uddiNodeList = clerkManager.getClientConfig().getUDDINodeList();
    System.out.println();/* w ww . j a v  a  2  s. c  o  m*/
    System.out.println("Select a node (from *this config)");
    for (int i = 0; i < uddiNodeList.size(); i++) {
        System.out.print(i + 1);
        System.out.println(") " + uddiNodeList.get(i).getName() + uddiNodeList.get(i).getDescription());
    }
    System.out.println("Node #: ");
    int index = Integer.parseInt(System.console().readLine()) - 1;
    String node = uddiNodeList.get(index).getName();
    Transport transport = clerkManager.getTransport(node);

    JUDDIApiPortType juddiApiService = transport.getJUDDIApiService();

    NodeList allNodes = juddiApiService.getAllNodes(authtoken);
    if (allNodes == null || allNodes.getNode().isEmpty()) {
        System.out.println("No nodes registered!");
    } else {
        for (int i = 0; i < allNodes.getNode().size(); i++) {
            System.out
                    .println("_______________________________________________________________________________");
            System.out.println("(" + i + ") Name :" + allNodes.getNode().get(i).getName());
            System.out.println("(" + i + ") Inquiry :" + allNodes.getNode().get(i).getInquiryUrl());

        }

        System.out.println("Node to remove from : ");
        int nodenum = Integer.parseInt(System.console().readLine());
        juddiApiService.deleteNode(new DeleteNode(authtoken, allNodes.getNode().get(nodenum).getName()));

    }
}

From source file:ee.ria.xroad.signer.console.SignerCLI.java

/**
 * Log in token./*w  w w. j  a  v  a 2s.com*/
 * @param tokenId token id
 * @throws Exception if an error occurs
 */
@Command(description = "Log in token", abbrev = "li")
public void loginToken(@Param(name = "tokenId", description = "Token ID") String tokenId) throws Exception {
    char[] pin = System.console().readPassword("PIN: ");

    Map<String, Object> logData = new LinkedHashMap<>();
    logData.put(TOKEN_ID_PARAM, tokenId);

    try {
        PasswordStore.storePassword(tokenId, pin);
        SignerClient.execute(new ActivateToken(tokenId, true));

        AuditLogger.log(LOG_INTO_THE_TOKEN, XROAD_USER, logData);
    } catch (Exception e) {
        AuditLogger.log(LOG_INTO_THE_TOKEN, XROAD_USER, e.getMessage(), logData);

        throw e;
    }
}

From source file:org.opoo.press.maven.wagon.github.GitHub.java

private GitHubClient createClient(String host, String userName, String password, String oauth2Token)
        throws GitHubException {
    GitHubClient client;//from ww w.java  2  s  .  c o  m
    if (!StringUtils.isEmpty(host)) {
        if (log.isDebugEnabled()) {
            log.debug("Using custom host: " + host);
        }
        client = createClient(host);
    } else {
        client = new GitHubClient();
    }

    if (!StringUtils.isEmpty(userName) && !StringUtils.isEmpty(password)) {
        if (log.isDebugEnabled()) {
            log.debug("Using basic authentication with username: " + userName);
        }
        client.setCredentials(userName, password);
        return client;
    } else if (!StringUtils.isEmpty(oauth2Token)) {
        if (log.isDebugEnabled()) {
            log.debug("Using OAuth2 access token authentication");
        }
        client.setOAuth2Token(oauth2Token);
        return client;
    } else if (StringUtils.isEmpty(userName) && !StringUtils.isEmpty(password)) {
        if (log.isDebugEnabled()) {
            log.debug("Using OAuth2 access token authentication");
        }
        client.setOAuth2Token(password);
        return client;
    } else if (!StringUtils.isEmpty(userName) && System.console() != null) {
        Console console = System.console();
        while (StringUtils.isEmpty(password)) {
            password = new String(console.readPassword("Input the password for '" + userName + "': "));
        }
        client.setCredentials(userName, password);
        return client;
    }

    throw new GitHubException("No authentication credentials configured");
}

From source file:com.github.rvesse.github.pr.stats.PullRequestStats.java

private void prepareCredentials(GitHubClient client) {
    if (this.oauthToken != null) {
        // OAuth 2 Authentication
        client.setOAuth2Token(this.oauthToken);
        System.out.println("Authenticating to GitHub using OAuth2 Token");
    } else if (this.oauthTokenFile != null) {
        // OAuth 2 Authentication with token stored in file
        try (BufferedReader reader = new BufferedReader(new FileReader(this.oauthTokenFile))) {
            this.oauthToken = reader.readLine();
            client.setOAuth2Token(this.oauthToken);
            System.out.println("Authenticating to GitHub using OAuth2 Token");
        } catch (IOException e) {
            throw new RuntimeException(
                    String.format("Unable to read specified OAuth Token file %s", this.oauthTokenFile));
        }/*from w  ww . j  av  a2 s  .c o m*/
    } else {
        // Username and Password authentication
        if (this.user == null) {
            System.out.print("Please enter your GitHub username [" + System.getProperty("user.name") + "]: ");
            this.user = System.console().readLine();
        }
        if (this.user == null || this.user.length() == 0) {
            this.user = System.getProperty("user.name");
        }
        if (this.pwd == null) {
            System.out.print("Please enter your GitHub password: ");
            this.pwd = new String(System.console().readPassword());
        }
        if (this.pwd == null || this.pwd.length() == 0) {
            System.err.println("Failed to specify a GitHub password");
            System.exit(1);
        }
        System.out.println("Authenticating to GitHub using Username and Password as user " + this.user);
        client.setCredentials(this.user, this.pwd);
    }
}

From source file:org.apache.juddi.samples.JuddiAdminService.java

private void menu_RemoveReplicationNode(ReplicationConfiguration replicationNodes) {
    if (replicationNodes.getCommunicationGraph() == null) {
        replicationNodes.setCommunicationGraph(new CommunicationGraph());
    }/*from  w w w  .  java2  s . c  om*/
    for (int i = 0; i < replicationNodes.getCommunicationGraph().getNode().size(); i++) {
        System.out.println((i + 1) + ") " + replicationNodes.getCommunicationGraph().getNode().get(i));
    }
    System.out.println("Node #: ");
    int index = Integer.parseInt(System.console().readLine()) - 1;
    replicationNodes.getCommunicationGraph().getNode().remove(index);

}

From source file:ee.ria.xroad.signer.console.SignerCLI.java

/**
 * Initialize software token/*  w w  w  .j a  va2 s .c  om*/
 * @throws Exception if an error occurs
 */
@Command(description = "Initialize software token")
public void initSoftwareToken() throws Exception {
    char[] pin = System.console().readPassword("PIN: ");
    char[] pin2 = System.console().readPassword("retype PIN: ");

    if (!Arrays.equals(pin, pin2)) {
        System.out.println("ERROR: PINs do not match");

        return;
    }

    try {
        SignerClient.execute(new InitSoftwareToken(pin));

        AuditLogger.log(INITIALIZE_THE_SOFTWARE_TOKEN_EVENT, XROAD_USER, null);
    } catch (Exception e) {
        AuditLogger.log(INITIALIZE_THE_SOFTWARE_TOKEN_EVENT, XROAD_USER, e.getMessage(), null);

        throw e;
    }
}