Example usage for org.apache.commons.cli Option setArgs

List of usage examples for org.apache.commons.cli Option setArgs

Introduction

In this page you can find the example usage for org.apache.commons.cli Option setArgs.

Prototype

public void setArgs(int num) 

Source Link

Document

Sets the number of argument values this Option can take.

Usage

From source file:org.onebusaway.quickstart.bootstrap.WebappBootstrapMain.java

private static Options createOptions() {
    Options options = new Options();
    options.addOption(ARG_PORT, true, "port (default=8080)");
    options.addOption(WebappCommon.ARG_BUILD, false, "");
    options.addOption(WebappCommon.ARG_GTFS_PATH, true, "");
    options.addOption(WebappCommon.ARG_GTFS_REALTIME_TRIP_UPDATES_URL, true, "");
    options.addOption(WebappCommon.ARG_GTFS_REALTIME_VEHICLE_POSITIONS_URL, true, "");
    options.addOption(WebappCommon.ARG_GTFS_REALTIME_ALERTS_URL, true, "");
    options.addOption(WebappCommon.ARG_GTFS_REALTIME_REFRESH_INTERVAL, true, "");

    Option pOption = new Option("P", "use value for given property");
    pOption.setArgName("beanName.beanProperty=value");
    pOption.setArgs(2);
    pOption.setValueSeparator('=');
    options.addOption(pOption);/*www . j a va  2s .c  o  m*/

    return options;
}

From source file:org.onebusaway.transit_data_federation.bundle.FederatedTransitDataBundleCreatorMain.java

protected void buildOptions(Options options) {
    options.addOption(ARG_SKIP_TO, true, "");
    options.addOption(ARG_ONLY, true, "");
    options.addOption(ARG_SKIP, true, "");
    options.addOption(ARG_INCLUDE, true, "");
    options.addOption(ARG_ONLY_IF_DNE, false, "");
    options.addOption(ARG_DATASOURCE_DRIVER_CLASS_NAME, true, "");
    options.addOption(ARG_DATASOURCE_URL, true, "");
    options.addOption(ARG_DATASOURCE_USERNAME, true, "");
    options.addOption(ARG_DATASOURCE_PASSWORD, true, "");
    options.addOption(ARG_BUNDLE_KEY, true, "");
    options.addOption(ARG_RANDOMIZE_CACHE_DIR, false, "");
    options.addOption(ARG_ADDITIONAL_RESOURCES_DIRECTORY, true, "");
    options.addOption(ARG_OSM, true, "");

    Option dOption = new Option("D", "use value for given property");
    dOption.setArgName("property=value");
    dOption.setArgs(2);
    dOption.setValueSeparator('=');
    options.addOption(dOption);/*  ww w.j a va 2s.  c  o  m*/

    Option pOption = new Option("P", "use value for given property");
    pOption.setArgName("beanName.beanProperty=value");
    pOption.setArgs(2);
    pOption.setValueSeparator('=');
    options.addOption(pOption);
}

From source file:org.ow2.proactive.authentication.crypto.CreateCredentials.java

/**
 * Entry point/*from   w  ww .  j  a va  2 s.  c o  m*/
 * 
 * @see org.ow2.proactive.authentication.crypto.Credentials
 * @param args arguments, try '-h' for help
 * @throws IOException
 * @throws ParseException
 *
 */
public static void main(String[] args) throws IOException, ParseException {

    SecurityManagerConfigurator.configureSecurityManager(
            CreateCredentials.class.getResource("/all-permissions.security.policy").toString());

    Console console = System.console();
    /**
     * default values
     */
    boolean interactive = true;
    String pubKeyPath = null;
    PublicKey pubKey = null;
    String login = null;
    String pass = null;
    String keyfile = null;
    String cipher = "RSA/ECB/PKCS1Padding";
    String path = Credentials.getCredentialsPath();
    String rm = null;
    String scheduler = null;
    String url = null;

    Options options = new Options();

    Option opt = new Option("h", "help", false, "Display this help");
    opt.setRequired(false);
    options.addOption(opt);

    OptionGroup group = new OptionGroup();
    group.setRequired(false);
    opt = new Option("F", "file", true,
            "Public key path on the local filesystem [default:" + Credentials.getPubKeyPath() + "]");
    opt.setArgName("PATH");
    opt.setArgs(1);
    opt.setRequired(false);
    group.addOption(opt);

    opt = new Option("R", "rm", true, "Request the public key to the Resource Manager at URL");
    opt.setArgName("URL");
    opt.setArgs(1);
    opt.setRequired(false);
    group.addOption(opt);

    opt = new Option("S", "scheduler", true, "Request the public key to the Scheduler at URL");
    opt.setArgName("URL");
    opt.setArgs(1);
    opt.setRequired(false);
    group.addOption(opt);
    options.addOptionGroup(group);

    opt = new Option("l", "login", true,
            "Generate credentials for this specific user, will be asked interactively if not specified");
    opt.setArgName("LOGIN");
    opt.setArgs(1);
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("p", "password", true, "Use this password, will be asked interactively if not specified");
    opt.setArgName("PWD");
    opt.setArgs(1);
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("k", "keyfile", true,
            "Use specified ssh private key, asked interactively if specified without PATH, not specified otherwise.");
    opt.setArgName("PATH");
    opt.setOptionalArg(true);
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("o", "output", true,
            "Output the resulting credentials to the specified file [default:" + path + "]");
    opt.setArgName("PATH");
    opt.setArgs(1);
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("c", "cipher", true,
            "Use specified cipher parameters, need to be compatible with the specified key [default:" + cipher
                    + "]");
    opt.setArgName("PARAMS");
    opt.setArgs(1);
    opt.setRequired(false);
    options.addOption(opt);

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(newline + "ERROR : " + e.getMessage() + newline);
        System.out.println("type -h or --help to display help screen");
        System.exit(1);
    }

    if (cmd.hasOption("help")) {
        displayHelp(options);
    }

    if (cmd.hasOption("file")) {
        pubKeyPath = cmd.getOptionValue("file");
    }
    if (cmd.hasOption("rm")) {
        rm = cmd.getOptionValue("rm");
    }
    if (cmd.hasOption("scheduler")) {
        scheduler = cmd.getOptionValue("scheduler");
    }

    if (cmd.hasOption("login")) {
        login = cmd.getOptionValue("login");
    }
    if (cmd.hasOption("password")) {
        pass = cmd.getOptionValue("password");
    }
    if (cmd.hasOption("keyfile") && cmd.getOptionValues("keyfile") != null) {
        keyfile = cmd.getOptionValue("keyfile");
    }

    if (cmd.hasOption("output")) {
        path = cmd.getOptionValue("output");
    }
    if (cmd.hasOption("cipher")) {
        cipher = cmd.getOptionValue("cipher");
    }

    int acc = 0;
    if (pubKeyPath != null) {
        acc++;
    }
    if (scheduler != null) {
        url = Connection.normalize(scheduler) + "SCHEDULER";
        acc++;

    }
    if (rm != null) {
        url = Connection.normalize(rm) + "RMAUTHENTICATION";
        acc++;
    }
    if (acc > 1) {
        System.out.println("--rm, --scheduler and --file arguments cannot be combined.");
        System.out.println("try -h for help.");
        System.exit(1);
    }

    if (url != null) {
        try {
            Connection<AuthenticationImpl> conn = new Connection<AuthenticationImpl>(AuthenticationImpl.class) {
                public Logger getLogger() {
                    return Logger.getLogger("pa.scheduler.credentials");
                }
            };
            AuthenticationImpl auth = conn.connect(url);
            pubKey = auth.getPublicKey();
        } catch (Exception e) {
            System.err.println("ERROR : Could not retrieve public key from '" + url + "'");
            e.printStackTrace();
            System.exit(3);
        }
        System.out.println("Successfully obtained public key from " + url + newline);
    } else if (pubKeyPath != null) {
        try {
            pubKey = Credentials.getPublicKey(pubKeyPath);
        } catch (KeyException e) {
            System.err
                    .println("ERROR : Could not retrieve public key from '" + pubKeyPath + "' (no such file)");
            System.exit(4);
        }
    } else {
        System.out.println("No public key specified, attempting to retrieve it from default location.");
        pubKeyPath = Credentials.getPubKeyPath();
        try {
            pubKey = Credentials.getPublicKey(pubKeyPath);
        } catch (KeyException e) {
            System.err
                    .println("ERROR : Could not retrieve public key from '" + pubKeyPath + "' (no such file)");
            System.exit(5);
        }
    }

    if (login != null && pass != null
            && (!cmd.hasOption("keyfile") || cmd.getOptionValues("keyfile") != null)) {
        System.out.println("Running in non-interactive mode." + newline);
        interactive = false;
    } else {
        System.out.println("Running in interactive mode.");
    }

    if (interactive) {
        System.out.println("Please enter Scheduler credentials,");
        System.out.println("they will be stored encrypted on disk for future logins." + newline);
        System.out.print("login: ");
        if (login == null) {
            login = console.readLine();
        } else {
            System.out.println(login);
        }
        System.out.print("password: ");
        if (pass == null) {
            pass = new String(console.readPassword());
        } else {
            System.out.println("*******");
        }
        System.out.print("keyfile: ");
        if (!cmd.hasOption("keyfile")) {
            System.out.println("no key file specified");
        } else if (cmd.hasOption("keyfile") && cmd.getOptionValues("keyfile") != null) {
            System.out.println(keyfile);
        } else {
            keyfile = console.readLine();
        }
    }

    try {
        CredData credData;
        if (keyfile != null && keyfile.length() > 0) {
            byte[] keyfileContent = FileToBytesConverter.convertFileToByteArray(new File(keyfile));
            credData = new CredData(CredData.parseLogin(login), CredData.parseDomain(login), pass,
                    keyfileContent);
        } else {
            System.out.println("--> Ignoring keyfile, credential does not contain SSH key");
            credData = new CredData(CredData.parseLogin(login), CredData.parseDomain(login), pass);
        }
        Credentials cred = Credentials.createCredentials(credData, pubKey, cipher);
        cred.writeToDisk(path);
    } catch (FileNotFoundException e) {
        System.err.println("ERROR : Could not retrieve ssh private key from '" + keyfile + "' (no such file)");
        System.exit(6);
    } catch (Throwable t) {
        t.printStackTrace();
        System.exit(7);
    }

    System.out.println("Successfully stored encrypted credentials on disk at :");
    System.out.println("\t" + path);

    System.exit(0);
}

From source file:org.ow2.proactive.resourcemanager.utils.console.ResourceManagerController.java

public void load(String[] args) {

    Options options = new Options();

    Option help = new Option("h", "help", false, "Display this help");
    help.setRequired(false);//from w w  w  .ja va 2  s  . co m
    options.addOption(help);

    Option username = new Option("l", "login", true, "The username to join the Resource Manager");
    username.setArgName("login");
    username.setArgs(1);
    username.setRequired(false);
    options.addOption(username);

    Option rmURL = new Option("u", "rmURL", true, "The Resource manager URL (default " + RM_DEFAULT_URL + ")");
    rmURL.setArgName("rmURL");
    rmURL.setArgs(1);
    rmURL.setRequired(false);
    options.addOption(rmURL);

    Option visual = new Option("g", "gui", false, "Start the console in a graphical view");
    rmURL.setRequired(false);
    options.addOption(visual);

    addCommandLineOptions(options);

    boolean displayHelp = false;

    try {
        String pwdMsg = null;

        Parser parser = new GnuParser();
        cmd = parser.parse(options, args);

        if (cmd.hasOption("h")) {
            displayHelp = true;
        } else {
            if (cmd.hasOption("environment")) {
                model.setInitEnv(cmd.getOptionValue("environment"));
            }
            String url;
            if (cmd.hasOption("u")) {
                url = cmd.getOptionValue("u");
            } else {
                url = RM_DEFAULT_URL;
            }

            logger.info("Connecting to the RM on " + url);
            auth = RMConnection.join(url);
            logger.info("\t-> Connection established on " + url);

            if (cmd.hasOption("l")) {
                user = cmd.getOptionValue("l");
            }
            if (cmd.hasOption("credentials")) {
                if (cmd.getOptionValues("credentials").length == 1) {
                    System.setProperty(Credentials.credentialsPathProperty, cmd.getOptionValue("credentials"));
                }
                try {
                    this.credentials = Credentials.getCredentials();
                } catch (KeyException e) {
                    logger.error("Could not retreive credentials... Try to adjust the System property: "
                            + Credentials.credentialsPathProperty);
                    throw e;
                }
            } else {
                ConsoleReader console = new ConsoleReader(System.in, new PrintWriter(System.out));
                if (cmd.hasOption("l")) {
                    pwdMsg = user + "'s password: ";
                } else {
                    user = console.readLine("login: ");
                    pwdMsg = "password: ";
                }

                //ask password to User
                try {
                    console.setDefaultPrompt(pwdMsg);
                    pwd = console.readLine('*');
                } catch (IOException ioe) {
                    logger.error("" + ioe);
                    logger.debug("", ioe);
                }

                PublicKey pubKey = null;
                try {
                    // first attempt at getting the pubkey : ask the RM
                    RMAuthentication auth = RMConnection.join(url);
                    pubKey = auth.getPublicKey();
                    logger.info("Retrieved public key from Resource Manager at " + url);
                } catch (Exception e) {
                    try {
                        // second attempt : try default location
                        pubKey = Credentials.getPublicKey(Credentials.getPubKeyPath());
                        logger.info("Using public key at " + Credentials.getPubKeyPath());
                    } catch (Exception exc) {
                        logger.error(
                                "Could not find a public key. Contact the administrator of the Resource Manager.");
                        logger.debug("", exc);
                        System.exit(1);
                    }
                }
                try {
                    this.credentials = Credentials.createCredentials(
                            new CredData(CredData.parseLogin(user), CredData.parseDomain(user), pwd), pubKey);
                } catch (KeyException e) {
                    logger.error("Could not create credentials... " + e);
                    throw e;
                }
            }

            //connect to the scheduler
            connect();
            //connect JMX service
            connectJMXClient();
            //start the command line or the interactive mode
            start();

        }
    } catch (MissingArgumentException e) {
        logger.error(e.getLocalizedMessage());
        logger.debug("", e);
        displayHelp = true;
    } catch (MissingOptionException e) {
        logger.error("Missing option: " + e.getLocalizedMessage());
        logger.debug("", e);
        displayHelp = true;
    } catch (UnrecognizedOptionException e) {
        logger.error(e.getLocalizedMessage());
        logger.debug("", e);
        displayHelp = true;
    } catch (AlreadySelectedException e) {
        logger.error(e.getClass().getSimpleName() + " : " + e.getLocalizedMessage());
        logger.debug("", e);
        displayHelp = true;
    } catch (ParseException e) {
        logger.debug("", e);
        displayHelp = true;
    } catch (RMException e) {
        logger.error(
                "Error at connection : " + e.getMessage() + newline + "Shutdown the controller." + newline);
        logger.debug("", e);
        System.exit(2);
    } catch (LoginException e) {
        logger.error(e.getMessage() + newline + "Shutdown the controller." + newline);
        logger.debug("", e);
        System.exit(3);
    } catch (Exception e) {
        logger.error(
                "An error has occurred : " + e.getMessage() + newline + "Shutdown the controller." + newline,
                e);
        logger.debug("", e);
        System.exit(4);
    }

    if (displayHelp) {
        logger.info("");
        HelpFormatter hf = new HelpFormatter();
        hf.setWidth(160);
        String note = newline + "NOTE : if no " + control
                + " command is specified, the controller will start in interactive mode.";
        hf.printHelp(commandName + shellExtension(), "", options, note, true);
        System.exit(5);
    }

    // if execution reaches this point this means it must exit
    System.exit(0);
}

From source file:org.ow2.proactive.resourcemanager.utils.console.ResourceManagerController.java

protected OptionGroup addCommandLineOptions(Options options) {
    OptionGroup actionGroup = new OptionGroup();

    Option addNodesOpt = new Option("a", "addnodes", true, control + "Add nodes by their URLs");
    addNodesOpt.setArgName("node URLs");
    addNodesOpt.setRequired(false);/*from w  w w.j  a va2  s.  c o m*/
    addNodesOpt.setArgs(Option.UNLIMITED_VALUES);
    actionGroup.addOption(addNodesOpt);

    Option removeNodesOpt = new Option("d", "removenodes", true, control + "Remove nodes by their URLs");
    removeNodesOpt.setArgName("node URLs");
    removeNodesOpt.setRequired(false);
    removeNodesOpt.setArgs(Option.UNLIMITED_VALUES);
    actionGroup.addOption(removeNodesOpt);

    Option lockNodesOpt = new Option("locknodes", true, control + "Lock nodes by their URLs");
    lockNodesOpt.setArgName("node URLs");
    lockNodesOpt.setRequired(false);
    lockNodesOpt.setArgs(Option.UNLIMITED_VALUES);
    actionGroup.addOption(lockNodesOpt);

    Option unlockNodesOpt = new Option("unlocknodes", true, control + "Unlock nodes by their URLs");
    unlockNodesOpt.setArgName("node URLs");
    unlockNodesOpt.setRequired(false);
    unlockNodesOpt.setArgs(Option.UNLIMITED_VALUES);
    actionGroup.addOption(unlockNodesOpt);

    Option createNSOpt = new Option("cn", "createns", true, control + "Create new node sources");
    createNSOpt.setArgName("names");
    createNSOpt.setRequired(false);
    createNSOpt.setArgs(Option.UNLIMITED_VALUES);
    actionGroup.addOption(createNSOpt);

    Option infrastuctureOpt = new Option("i", "infrastructure", true,
            "Specify an infrastructure when node source is created");
    infrastuctureOpt.setArgName("params");
    infrastuctureOpt.setRequired(false);
    infrastuctureOpt.setOptionalArg(true);
    infrastuctureOpt.setArgs(Option.UNLIMITED_VALUES);
    options.addOption(infrastuctureOpt);

    Option policyOpt = new Option("p", "policy", true, "Specify a policy when node source is created");
    policyOpt.setArgName("params");
    policyOpt.setOptionalArg(true);
    policyOpt.setRequired(false);
    policyOpt.setArgs(Option.UNLIMITED_VALUES);
    options.addOption(policyOpt);

    Option listNodesOpt = new Option("ln", "listnodes", true, control
            + "List nodes handled by Resource Manager. Display is : NODESOURCE HOSTNAME STATE NODE_URL");
    listNodesOpt.setRequired(false);
    listNodesOpt.setOptionalArg(true);
    listNodesOpt.setArgName("nodeSourceName");
    actionGroup.addOption(listNodesOpt);

    Option listNSOpt = new Option("lns", "listns", false,
            control + "List node sources on Resource Manager. Display is : NODESOURCE TYPE");
    listNSOpt.setRequired(false);
    actionGroup.addOption(listNSOpt);

    Option topologyOpt = new Option("t", "topology", false, control + "Displays nodes topology.");
    topologyOpt.setRequired(false);
    actionGroup.addOption(topologyOpt);

    Option removeNSOpt = new Option("r", "removens", true, control + "Remove given node sources");
    removeNSOpt.setArgName("names");
    removeNSOpt.setRequired(false);
    removeNSOpt.setArgs(Option.UNLIMITED_VALUES);
    actionGroup.addOption(removeNSOpt);

    Option shutdownOpt = new Option("s", "shutdown", false, control + "Shutdown Resource Manager");
    shutdownOpt.setRequired(false);
    actionGroup.addOption(shutdownOpt);

    Option acopt = new Option("stats", "statistics", false,
            control + "Display some statistics about the Resource Manager");
    acopt.setRequired(false);
    acopt.setArgs(0);
    actionGroup.addOption(acopt);

    acopt = new Option("ma", "myaccount", false, control + "Display current user account informations");
    acopt.setRequired(false);
    acopt.setArgs(0);
    actionGroup.addOption(acopt);

    acopt = new Option("ua", "useraccount", false, control + "Display account information by username");
    acopt.setRequired(false);
    acopt.setArgs(1);
    acopt.setArgName("username");
    actionGroup.addOption(acopt);

    acopt = new Option("ni", "nodeinfo", true, control + "Display node information");
    acopt.setRequired(false);
    acopt.setArgs(1);
    acopt.setArgName("nodeURL");
    actionGroup.addOption(acopt);

    acopt = new Option("rc", "reloadconfig", false,
            control + "Reloads the resource manager permission policy and log4j config");
    acopt.setRequired(false);
    acopt.setArgs(0);
    actionGroup.addOption(acopt);

    options.addOptionGroup(actionGroup);

    Option nodeSourceNameOpt = new Option("ns", "nodesource", true,
            control + "Specify an existing node source name for adding nodes");
    nodeSourceNameOpt.setArgName("nodes URLs");
    nodeSourceNameOpt.setRequired(false);
    nodeSourceNameOpt.setArgs(1);
    options.addOption(nodeSourceNameOpt);

    Option preeemptiveRemovalOpt = new Option("f", "force", false,
            control + "Do not wait for busy nodes to be freed before "
                    + "nodes removal, node source removal and shutdown actions (-d, -r and -s)");
    preeemptiveRemovalOpt.setRequired(false);
    options.addOption(preeemptiveRemovalOpt);

    Option script = new Option("sf", "script", true,
            control + "Execute the given javascript file with optional arguments.");
    script.setArgName("filePath arg1=val1 arg2=val2 ...");
    script.setArgs(Option.UNLIMITED_VALUES);
    script.setOptionalArg(true);
    script.setRequired(false);
    options.addOption(script);

    script = new Option("env", "environment", true, "Execute the given script and go into interactive mode");
    script.setArgName("filePath");
    script.setRequired(false);
    script.setOptionalArg(true);
    options.addOption(script);

    Option opt = new Option("c", "credentials", true,
            "Path to the credentials (" + Credentials.getCredentialsPath() + ").");
    opt.setRequired(false);
    opt.setArgs(1);
    options.addOption(opt);

    return actionGroup;
}

From source file:org.ow2.proactive.scheduler.authentication.ManageUsers.java

/**
 * Build the command line options and parse
 *///from   w  w  w .  j a  va  2  s.  c o m
private static CommandLine getCommandLine(String[] args, String loginFilePath, String groupFilePath,
        Options options) throws ManageUsersException {
    Option opt = new Option(HELP_OPTION, HELP_OPTION_NAME, false, "Display this help");
    opt.setRequired(false);
    options.addOption(opt);
    OptionGroup optionGroup = new OptionGroup();
    optionGroup.setRequired(false);

    opt = new Option(CREATE_OPTION, CREATE_OPTION_NAME, true, "Action to create a user");
    opt.setArgName(CREATE_OPTION_NAME.toUpperCase());
    opt.setArgs(0);
    opt.setRequired(false);
    optionGroup.addOption(opt);

    opt = new Option(UPDATE_OPTION, UPDATE_OPTION_NAME, true,
            "Action to update an existing user. Updating a user means to change the user's password or group membership.");
    opt.setArgName(UPDATE_OPTION_NAME.toUpperCase());
    opt.setArgs(0);
    opt.setRequired(false);
    optionGroup.addOption(opt);

    opt = new Option(DELETE_OPTION, DELETE_OPTION_NAME, true, "Action to delete an existing user");
    opt.setArgName(DELETE_OPTION_NAME.toUpperCase());
    opt.setArgs(0);
    opt.setRequired(false);
    optionGroup.addOption(opt);
    options.addOptionGroup(optionGroup);

    opt = new Option(LOGIN_OPTION, LOGIN_OPTION_NAME, true,
            "Generate credentials for this specific user, will be asked interactively if not specified");
    opt.setArgName(LOGIN_OPTION_NAME.toUpperCase());
    opt.setArgs(1);
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(PWD_OPTION, PWD_OPTION_NAME, true,
            "Password of the user, if the user is created or updated, will be asked interactively if not specified");
    opt.setArgName(PWD_OPTION_NAME.toUpperCase());
    opt.setArgs(1);
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(GROUPS_OPTION, GROUPS_OPTION_NAME, true,
            "A comma-separated list of groups the user must be member of. Can be used when the user is created or updated");
    opt.setArgName(GROUPS_OPTION_NAME.toUpperCase());
    opt.setArgs(1);
    opt.setRequired(false);
    options.addOption(opt);

    optionGroup.setRequired(false);
    opt = new Option(KEYFILE_OPTION, KEYFILE_OPTION_NAME, true,
            "Public key path on the local filesystem [default:" + getPublicKeyFilePath() + "]");
    opt.setArgName(KEYFILE_OPTION_NAME.toUpperCase());
    opt.setArgs(1);
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(LOGINFILE_OPTION, LOGINFILE_OPTION_NAME, true,
            "Path to the login file in use [default:" + loginFilePath + "]");
    opt.setArgName(LOGINFILE_OPTION_NAME.toUpperCase());
    opt.setArgs(1);
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(GROUPFILE_OPTION, GROUPFILE_OPTION_NAME, true,
            "Path to the group file in use [default:" + groupFilePath + "]");
    opt.setArgName(GROUPFILE_OPTION_NAME.toUpperCase());
    opt.setArgs(1);
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(SOURCE_LOGINFILE_OPTION, SOURCE_LOGINFILE_OPTION_NAME, true,
            "Path to a source login file, used for bulk creation or bulk update. The source login file must contain clear text passwords in the format username:password");
    opt.setArgName(SOURCE_LOGINFILE_OPTION_NAME.toUpperCase());
    opt.setArgs(1);
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(SOURCE_GROUPFILE_OPTION, SOURCE_GROUPFILE_OPTION_NAME, true,
            "Path to a source group file, used for bulk creation or bulk update. The source group file must contain group assignements in the format username:group");
    opt.setArgName(SOURCE_GROUPFILE_OPTION_NAME.toUpperCase());
    opt.setArgs(1);
    opt.setRequired(false);
    options.addOption(opt);

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        exitWithErrorMessage(newline + e.getMessage() + newline, "type -h or --help to display help screen",
                null);
    }
    return cmd;
}

From source file:org.ow2.proactive.scheduler.util.console.SchedulerController.java

public void load(String[] args) {
    Options options = new Options();

    Option help = new Option("h", "help", false, "Display this help");
    help.setRequired(false);//from   www.  j  a  v  a2  s . com
    options.addOption(help);

    Option username = new Option("l", "login", true, "The username to join the Scheduler");
    username.setArgName("login");
    username.setArgs(1);
    username.setRequired(false);
    options.addOption(username);

    Option schedulerURL = new Option("u", "url", true,
            "The scheduler URL (default " + SCHEDULER_DEFAULT_URL + ")");
    schedulerURL.setArgName("schedulerURL");
    schedulerURL.setRequired(false);
    options.addOption(schedulerURL);

    Option keyfile = new Option("k", "key", true, "(Optional) The path to a private SSH key");
    keyfile.setArgName("sshkeyFilePath");
    keyfile.setArgs(1);
    keyfile.setRequired(false);
    options.addOption(keyfile);

    addCommandLineOptions(options);

    boolean displayHelp = false;

    try {
        String pwdMsg = null;

        Parser parser = new GnuParser();
        cmd = parser.parse(options, args);

        if (cmd.hasOption("help")) {
            displayHelp = true;
        } else {

            if (cmd.hasOption("env")) {
                model.setInitEnv(cmd.getOptionValue("env"));
            }
            String url;
            if (cmd.hasOption("url")) {
                url = cmd.getOptionValue("url");
            } else {
                url = SCHEDULER_DEFAULT_URL;
            }
            logger.info("Trying to connect Scheduler on " + url);
            auth = SchedulerConnection.join(url);
            logger.info("\t-> Connection established on " + url);

            logger.info(newline + "Connecting client to the Scheduler");

            if (cmd.hasOption("login")) {
                user = cmd.getOptionValue("login");
            }

            if (cmd.hasOption("credentials")) {
                if (cmd.getOptionValue("credentials") != null) {
                    System.setProperty(Credentials.credentialsPathProperty, cmd.getOptionValue("credentials"));
                }
                try {
                    this.credentials = Credentials.getCredentials();
                } catch (KeyException e) {
                    logger.error("Could not retreive credentials... Try to adjust the System property: "
                            + Credentials.credentialsPathProperty + " or use the -c option.");
                    throw e;
                }
            } else {
                ConsoleReader console = new ConsoleReader(System.in, new PrintWriter(System.out));
                if (cmd.hasOption("login")) {
                    pwdMsg = user + "'s password: ";
                } else {
                    user = console.readLine("login: ");
                    pwdMsg = "password: ";
                }

                //ask password to User
                try {
                    console.setDefaultPrompt(pwdMsg);
                    pwd = console.readLine('*');
                } catch (IOException ioe) {
                    logger.error("" + ioe);
                    logger.debug("", ioe);
                }

                PublicKey pubKey = null;
                try {
                    // first attempt at getting the pubkey : ask the scheduler
                    SchedulerAuthenticationInterface auth = SchedulerConnection.join(url);
                    pubKey = auth.getPublicKey();
                    logger.info("Retrieved public key from Scheduler at " + url);
                } catch (Exception e) {
                    try {
                        // second attempt : try default location
                        pubKey = Credentials.getPublicKey(Credentials.getPubKeyPath());
                        logger.info("Using public key at " + Credentials.getPubKeyPath());
                    } catch (Exception exc) {
                        logger.error(
                                "Could not find a public key. Contact the administrator of the Scheduler.");
                        logger.debug("", exc);
                        System.exit(7);
                    }
                }
                try {
                    if (cmd.hasOption("key")) {
                        byte[] keyfileContent = FileToBytesConverter
                                .convertFileToByteArray(new File(cmd.getOptionValue("key")));
                        this.credentials = Credentials.createCredentials(new CredData(CredData.parseLogin(user),
                                CredData.parseDomain(user), pwd, keyfileContent), pubKey);
                    } else {
                        this.credentials = Credentials.createCredentials(
                                new CredData(CredData.parseLogin(user), CredData.parseDomain(user), pwd),
                                pubKey);
                    }
                } catch (FileNotFoundException fnfe) {
                    logger.error("SSH keyfile not found : '" + cmd.getOptionValue("key") + "'");
                    logger.debug("", fnfe);
                    System.exit(8);
                } catch (Exception e) {
                    logger.error("Could not create credentials... " + e);
                    throw e;
                }
            }

            //connect to the scheduler
            connect();
            //connect JMX service
            connectJMXClient();
            //start the command line or the interactive mode
            start();
        }
    } catch (MissingArgumentException e) {
        logger.error(e.getLocalizedMessage());
        logger.debug("", e);
        displayHelp = true;
    } catch (MissingOptionException e) {
        logger.error("Missing option: " + e.getLocalizedMessage());
        logger.debug("", e);
        displayHelp = true;
    } catch (UnrecognizedOptionException e) {
        logger.error(e.getLocalizedMessage());
        logger.debug("", e);
        displayHelp = true;
    } catch (AlreadySelectedException e) {
        logger.error(e.getClass().getSimpleName() + " : " + e.getLocalizedMessage());
        logger.debug("", e);
        displayHelp = true;
    } catch (ParseException e) {
        displayHelp = true;
    } catch (LoginException e) {
        logger.error(getMessages(e) + "Shutdown the controller." + newline);
        logger.debug("", e);
        System.exit(3);
    } catch (SchedulerException e) {
        logger.error(getMessages(e) + "Shutdown the controller." + newline);
        logger.debug("", e);
        System.exit(4);
    } catch (Exception e) {
        logger.error(getMessages(e) + "Shutdown the controller." + newline, e);
        logger.debug("", e);
        System.exit(5);
    }

    if (displayHelp) {
        logger.info("");
        HelpFormatter hf = new HelpFormatter();
        hf.setWidth(135);
        String note = newline + "NOTE : if no " + control
                + "command is specified, the controller will start in interactive mode.";
        hf.printHelp(getCommandName() + Tools.shellExtension(), "", options, note, true);
        System.exit(6);
    }

    // if execution reaches this point this means it must exit
    System.exit(0);
}

From source file:org.ow2.proactive.scheduler.util.console.SchedulerController.java

protected OptionGroup addCommandLineOptions(Options options) {
    OptionGroup actionGroup = new OptionGroup();

    Option opt = new Option("s", "submit", true, control + "Submit the given job XML file");
    opt.setArgName("XMLDescriptor");
    opt.setRequired(false);/*from   ww  w  .  j a v a2s .  c  o m*/
    opt.setArgs(Option.UNLIMITED_VALUES);
    actionGroup.addOption(opt);

    opt = new Option("sa", "submitarchive", true, control + "Submit the given job archive");
    opt.setArgName("jobarchive");
    opt.setRequired(false);
    opt.setArgs(1);
    actionGroup.addOption(opt);

    opt = new Option("cmd", "command", false,
            control + "If mentionned, -submit argument becomes a command line, ie: -submit command args...");
    opt.setRequired(false);
    options.addOption(opt);
    opt = new Option("cmdf", "commandf", false, control
            + "If mentionned, -submit argument becomes a text file path containing command lines to schedule");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("ss", "selectscript", true,
            control + "Used with -cmd or -cmdf, specify a selection script");
    opt.setArgName("selectScript");
    opt.setRequired(false);
    opt.setArgs(1);
    options.addOption(opt);

    opt = new Option("jn", "jobname", true, control + "Used with -cmd or -cmdf, specify the job name");
    opt.setArgName("jobName");
    opt.setRequired(false);
    opt.setArgs(1);
    options.addOption(opt);

    opt = new Option("pj", "pausejob", true, control + "Pause the given job (pause every non-running tasks)");
    opt.setArgName("jobId");
    opt.setRequired(false);
    opt.setArgs(1);
    actionGroup.addOption(opt);

    opt = new Option("rj", "resumejob", true, control + "Resume the given job (restart every paused tasks)");
    opt.setArgName("jobId");
    opt.setRequired(false);
    opt.setArgs(1);
    actionGroup.addOption(opt);

    opt = new Option("kj", "killjob", true, control + "Kill the given job (cause the job to finish)");
    opt.setArgName("jobId");
    opt.setRequired(false);
    opt.setArgs(1);
    actionGroup.addOption(opt);

    opt = new Option("rmj", "removejob", true, control + "Remove the given job");
    opt.setArgName("jobId");
    opt.setRequired(false);
    opt.setArgs(1);
    actionGroup.addOption(opt);

    opt = new Option("pt", "preempttask", true,
            control + "Stop the given task and re-schedules it after specified delay.");
    opt.setArgName("jobId taskName delay");
    opt.setRequired(false);
    opt.setArgs(3);
    actionGroup.addOption(opt);

    opt = new Option("rt", "restarttask", true,
            control + "Terminate the given task and re-schedules it after specified delay.");
    opt.setArgName("jobId taskName delay");
    opt.setRequired(false);
    opt.setArgs(3);
    actionGroup.addOption(opt);

    opt = new Option("kt", "killtask", true, control + "Kill the given task.");
    opt.setArgName("jobId taskName");
    opt.setRequired(false);
    opt.setArgs(2);
    actionGroup.addOption(opt);

    opt = new Option("jr", "jobresult", true, control + "Get the result of the given job");
    opt.setArgName("jobId");
    opt.setRequired(false);
    opt.setArgs(1);
    actionGroup.addOption(opt);

    opt = new Option("tr", "taskresult", true, control + "Get the result of the given task");
    opt.setArgName("jobId taskName [inc]");
    opt.setRequired(false);
    opt.setArgs(3);
    opt.setOptionalArg(true);
    actionGroup.addOption(opt);

    opt = new Option("jo", "joboutput", true, control + "Get the output of the given job");
    opt.setArgName("jobId");
    opt.setRequired(false);
    opt.setArgs(2);
    actionGroup.addOption(opt);

    opt = new Option("to", "taskoutput", true, control + "Get the output of the given task");
    opt.setArgName("jobId taskName");
    opt.setRequired(false);
    opt.setArgs(2);
    actionGroup.addOption(opt);

    opt = new Option("jp", "jobpriority", true,
            control + "Change the priority of the given job (Idle, Lowest, Low, Normal, High, Highest)");
    opt.setArgName("jobId newPriority");
    opt.setRequired(false);
    opt.setArgs(2);
    actionGroup.addOption(opt);

    opt = new Option("js", "jobstate", true,
            control + "Get the current state of the given job (Also tasks description)");
    opt.setArgName("jobId");
    opt.setRequired(false);
    opt.setArgs(2);
    actionGroup.addOption(opt);

    opt = new Option("lj", "listjobs", false, control + "Display the list of jobs managed by the scheduler");
    opt.setRequired(false);
    opt.setArgs(0);
    actionGroup.addOption(opt);

    opt = new Option("stats", "statistics", false, control + "Display some statistics about the Scheduler");
    opt.setRequired(false);
    opt.setArgs(0);
    actionGroup.addOption(opt);

    opt = new Option("ma", "myaccount", false, control + "Display current user account information");
    opt.setRequired(false);
    opt.setArgs(0);
    actionGroup.addOption(opt);

    opt = new Option("ua", "useraccount", false, control + "Display account information by username");
    opt.setRequired(false);
    opt.setArgs(1);
    opt.setArgName("username");
    actionGroup.addOption(opt);

    opt = new Option("rc", "reloadconfig", false,
            control + "Reloads the scheduler permission policy and log4j config");
    opt.setRequired(false);
    opt.setArgs(0);
    actionGroup.addOption(opt);

    opt = new Option("sf", "script", true,
            control + "Execute the given javascript file with optional arguments.");
    opt.setArgName("filePath arg1=val1 arg2=val2 ...");
    opt.setRequired(false);
    opt.setArgs(Option.UNLIMITED_VALUES);
    opt.setOptionalArg(true);
    actionGroup.addOption(opt);

    opt = new Option("env", "environment", true,
            "Execute the given script as an environment for the interactive mode");
    opt.setArgName("filePath");
    opt.setRequired(false);
    opt.setArgs(1);
    actionGroup.addOption(opt);

    opt = new Option("test", false,
            control + "Test if the Scheduler is successfully started by committing some examples");
    opt.setRequired(false);
    opt.setArgs(0);
    actionGroup.addOption(opt);

    opt = new Option("c", "credentials", true,
            "Path to the credentials (" + Credentials.getCredentialsPath() + ").");
    opt.setRequired(false);
    opt.setOptionalArg(true);
    options.addOption(opt);

    options.addOptionGroup(actionGroup);

    opt = new Option("start", "schedulerstart", false, control + "Start the Scheduler");
    opt.setRequired(false);
    actionGroup.addOption(opt);

    opt = new Option("stop", "schedulerstop", false, control + "Stop the Scheduler");
    opt.setRequired(false);
    actionGroup.addOption(opt);

    opt = new Option("pause", "schedulerpause", false,
            control + "Pause the Scheduler (cause all non-running jobs to be paused)");
    opt.setRequired(false);
    actionGroup.addOption(opt);

    opt = new Option("freeze", "schedulerfreeze", false,
            control + "Freeze the Scheduler (cause all non-running tasks to be paused)");
    opt.setRequired(false);
    actionGroup.addOption(opt);

    opt = new Option("resume", "schedulerresume", false, control + "Resume the Scheduler");
    opt.setRequired(false);
    actionGroup.addOption(opt);

    opt = new Option("shutdown", "schedulershutdown", false, control + "Shutdown the Scheduler");
    opt.setRequired(false);
    actionGroup.addOption(opt);

    opt = new Option("kill", "schedulerkill", false, control + "Kill the Scheduler");
    opt.setRequired(false);
    actionGroup.addOption(opt);

    opt = new Option("lrm", "linkrm", true, control + "Reconnect a RM to the scheduler");
    opt.setArgName("rmURL");
    opt.setRequired(false);
    opt.setArgs(1);
    actionGroup.addOption(opt);

    opt = new Option("pr", "policyreload", false, control + "Reload the policy configuration");
    opt.setRequired(false);
    actionGroup.addOption(opt);

    opt = new Option("p", "policy", true, control + "Change the current scheduling policy");
    opt.setArgName("fullName");
    opt.setRequired(false);
    opt.setArgs(1);
    actionGroup.addOption(opt);

    opt = new Option("ll", "logs", true, control + "Get server logs of given job or task");
    opt.setArgName("jobId [taskName]");
    opt.setRequired(false);
    opt.setArgs(2);
    actionGroup.addOption(opt);

    options.addOptionGroup(actionGroup);

    return actionGroup;
}

From source file:org.ow2.proactive_grid_cloud_portal.cli.CommandFactory.java

protected Options createOptions(Collection<CommandSet.Entry> entries) {
    Options options = new Options();

    for (CommandSet.Entry entry : entries) {
        Option option = new Option(entry.opt(), entry.longOpt(), entry.hasArgs(), entry.description());

        option.setArgName(entry.argNames());
        option.setArgs(entry.numOfArgs());
        option.setOptionalArg(entry.hasOptionalArg());

        options.addOption(option);/*  w  w  w  .jav a2 s. c  o m*/
    }
    return options;
}

From source file:org.seedstack.seed.core.internal.cli.CliModel.java

CliModel(Set<Field> fields) {
    for (Field field : fields) {
        CliOption optionAnnotation = field.getAnnotation(CliOption.class);
        CliArgs argsAnnotation = field.getAnnotation(CliArgs.class);

        if (optionAnnotation != null) {
            Option option = new Option(optionAnnotation.name(), optionAnnotation.longName(),
                    optionAnnotation.valueCount() > 0 || optionAnnotation.valueCount() == -1,
                    optionAnnotation.description());

            if (optionAnnotation.valueCount() == -1) {
                option.setArgs(Option.UNLIMITED_VALUES);
            } else if (optionAnnotation.valueCount() > 0) {
                option.setArgs(optionAnnotation.valueCount());
            }//w  ww  .  j  ava 2  s.  com

            option.setValueSeparator(optionAnnotation.valueSeparator());
            option.setRequired(optionAnnotation.mandatory());
            option.setOptionalArg(!optionAnnotation.mandatoryValue());
            optionAnnotations.add(optionAnnotation);
            optionFields.add(field);
            options.addOption(option);
        } else if (argsAnnotation != null) {
            mandatoryArgsCount = argsAnnotation.mandatoryCount();
            argsField = field;
        }
    }
}