Example usage for org.apache.commons.cli CommandLine getArgList

List of usage examples for org.apache.commons.cli CommandLine getArgList

Introduction

In this page you can find the example usage for org.apache.commons.cli CommandLine getArgList.

Prototype

public List getArgList() 

Source Link

Document

Retrieve any left-over non-recognized options and arguments

Usage

From source file:org.glite.security.voms.admin.persistence.tools.AuditLogCtl.java

private AuditLogCtlCommand validateCommandLine(CommandLine line) {

    if (line.hasOption("help")) {
        printHelp();//from w w  w . j a v  a 2  s  .c  o  m
        System.exit(0);
    }

    if (!line.hasOption("vo")) {
        errorAndExit("Please specify a vo with the --vo option");
    }

    @SuppressWarnings("unchecked")
    List<String> args = line.getArgList();

    if (args.isEmpty()) {
        errorAndExit("No command specified");
    }

    if (args.size() > 1) {
        errorAndExit("More than one command argument: " + StringUtils.join(args, ","));
    }

    String command = args.get(0);

    if (!commands.containsKey(command)) {
        errorAndExit("Unrecognized command: " + command);
    }

    return commands.get(command);

}

From source file:org.globus.workspace.cloud.client.AllArgs.java

public void intakeCmdlineOptions(String[] args)

        throws ParameterProblem, ParseException {

    // (debug was fished out already)
    final String sectionTitle = "COMMANDLINE INTAKE";
    CommonPrint.printDebugSection(this.print, sectionTitle);

    final Options options = new Options();
    final Opts opts = new Opts();

    for (int i = 0; i < opts.ALL_ENABLED_OPTIONS.length; i++) {
        options.addOption(opts.ALL_ENABLED_OPTIONS[i]);
    }/*from w w  w .j a va 2s .  c  o  m*/

    final CommandLineParser parser = new PosixParser();
    final CommandLine line = parser.parse(options, args);

    final List leftovers = line.getArgList();
    if (leftovers != null && !leftovers.isEmpty()) {
        // there are situations where this could cause dataloss, see:
        // https://bugzilla.mcs.anl.gov/globus/show_bug.cgi?id=6873
        throw new ParameterProblem("There are unrecognized arguments, check -h to make "
                + "sure you are doing the intended thing: " + leftovers.toString());
    }

    // note debug was already recognized and configured, keeping this
    // block here for completeness (and for gotCmdLine logging)
    if (line.hasOption(Opts.DEBUG_OPT_STRING)) {
        this.print.setDebugStream(System.out);
        this.gotCmdLine(Opts.DEBUG_OPT_STRING_LONG, "enabled");
    }

    if (line.hasOption(Opts.BROKER_ID_OPT_STRING)) {
        this.brokerID = line.getOptionValue(Opts.BROKER_ID_OPT_STRING);
        this.gotCmdLine(Opts.BROKER_ID_OPT_STRING, this.brokerID);
    }

    if (line.hasOption(Opts.BROKER_URL_OPT_STRING)) {
        this.brokerURL = line.getOptionValue(Opts.BROKER_URL_OPT_STRING);
        this.gotCmdLine(Opts.BROKER_URL_OPT_STRING, this.brokerURL);
    }

    if (line.hasOption(Opts.CADIR_OPT_STRING)) {
        this.caAppendDir = line.getOptionValue(Opts.CADIR_OPT_STRING);
        this.gotCmdLine(Opts.CADIR_OPT_STRING, this.caAppendDir);
    }

    if (line.hasOption(Opts.CAHASH_OPT_STRING)) {
        this.caHash = line.getOptionValue(Opts.CAHASH_OPT_STRING);
        this.gotCmdLine(Opts.CAHASH_OPT_STRING, this.caHash);
    }

    if (line.hasOption(Opts.CLUSTER_OPT_STRING)) {
        this.clusterPath = line.getOptionValue(Opts.CLUSTER_OPT_STRING);
        this.gotCmdLine(Opts.CLUSTER_OPT_STRING, this.clusterPath);
    }

    if (line.hasOption(Opts.EC2SCRIPT_OPT_STRING)) {
        this.ec2ScriptPath = line.getOptionValue(Opts.EC2SCRIPT_OPT_STRING);
        this.gotCmdLine(Opts.EC2SCRIPT_OPT_STRING, this.ec2ScriptPath);
    }

    if (line.hasOption(Opts.ASSOC_QUERY_OPT_STRING)) {
        this.actions.add(ACTION_ASSOC_QUERY);
        this.gotCmdLine(Opts.ASSOC_QUERY_OPT_STRING, "enabled");
    }

    if (line.hasOption(Opts.DELETE_OPT_STRING)) {
        this.actions.add(ACTION_DELETE);
        this.gotCmdLine(Opts.DELETE_OPT_STRING, "enabled");
    }

    if (line.hasOption(Opts.DESTROY_OPT_STRING)) {
        this.actions.add(ACTION_DESTROY);
        this.gotCmdLine(Opts.DESTROY_OPT_STRING, "enabled");
    }

    if (line.hasOption(Opts.DOWNLOAD_OPT_STRING)) {
        this.actions.add(ACTION_DOWNLOAD);
        this.gotCmdLine(Opts.DOWNLOAD_OPT_STRING, "enabled");
    }

    if (line.hasOption(Opts.EPR_FILE_OPT_STRING)) {
        this.eprGivenFilePath = line.getOptionValue(Opts.EPR_FILE_OPT_STRING);
        this.gotCmdLine(Opts.EPR_FILE_OPT_STRING, this.eprGivenFilePath);
    }

    if (line.hasOption(Opts.EXTRAHELP_OPT_STRING)) {
        this.actions.add(ACTION_EXTRAHELP);
        this.gotCmdLine(Opts.EXTRAHELP_OPT_STRING, "enabled");
    }

    if (line.hasOption(Opts.FACTORY_OPT_STRING)) {
        this.factoryHostPort = line.getOptionValue(Opts.FACTORY_OPT_STRING);
        this.gotCmdLine(Opts.FACTORY_OPT_STRING, this.factoryHostPort);
    }

    if (line.hasOption(Opts.FACTORY_ID_OPT_STRING)) {
        this.factoryID = line.getOptionValue(Opts.FACTORY_ID_OPT_STRING);
        this.gotCmdLine(Opts.FACTORY_ID_OPT_STRING, this.factoryID);
    }

    if (line.hasOption(Opts.GRIDFTP_OPT_STRING)) {
        this.xferHostPort = line.getOptionValue(Opts.GRIDFTP_OPT_STRING);
        this.gotCmdLine(Opts.GRIDFTP_OPT_STRING, this.xferHostPort);
    }

    if (line.hasOption(Opts.GRIDFTP_ID_OPT_STRING)) {
        this.gridftpID = line.getOptionValue(Opts.GRIDFTP_ID_OPT_STRING);
        this.gotCmdLine(Opts.GRIDFTP_ID_OPT_STRING, this.gridftpID);
    }

    if (line.hasOption(Opts.HANDLE_OPT_STRING)) {
        this.handle = line.getOptionValue(Opts.HANDLE_OPT_STRING);
        this.gotCmdLine(Opts.HANDLE_OPT_STRING, this.handle);
    }

    if (line.hasOption(Opts.HASH_PRINT_OPT_STRING)) {
        this.actions.add(ACTION_HASH_PRINT);
        this.hashPrintDN = line.getOptionValue(Opts.HASH_PRINT_OPT_STRING);
        this.gotCmdLine(Opts.HASH_PRINT_OPT_STRING, this.hashPrintDN);
    }

    if (line.hasOption(Opts.INIT_CTX_OPT_STRING)) {
        this.actions.add(ACTION_INIT_CONTEXT);
        this.initCtxDir = line.getOptionValue(Opts.INIT_CTX_OPT_STRING);
        this.gotCmdLine(Opts.INIT_CTX_OPT_STRING, this.initCtxDir);
    }

    if (line.hasOption(Opts.HELP_OPT_STRING)) {
        this.actions.add(ACTION_HELP);
        this.gotCmdLine(Opts.HELP_OPT_STRING, "enabled");
    }

    if (line.hasOption(Opts.HISTORY_DIR_OPT_STRING)) {
        this.historyDirectory = line.getOptionValue(Opts.HISTORY_DIR_OPT_STRING);
        this.gotCmdLine(Opts.HISTORY_DIR_OPT_STRING, this.historyDirectory);
    }

    if (line.hasOption(Opts.HISTORY_SUBDIR_OPT_STRING)) {
        this.historySubDir = line.getOptionValue(Opts.HISTORY_SUBDIR_OPT_STRING);
        this.gotCmdLine(Opts.HISTORY_SUBDIR_OPT_STRING, this.historySubDir);
    }

    if (line.hasOption(Opts.HOSTKEYDIR_OPT_STRING)) {
        this.hostkeyDir = true;
        this.gotCmdLine(Opts.HOSTKEYDIR_OPT_STRING, "enabled");
    }

    if (line.hasOption(Opts.HOURS_OPT_STRING)) {
        final String hoursString = line.getOptionValue(Opts.HOURS_OPT_STRING);
        final double hours = Double.parseDouble(hoursString);
        final double minutesDouble = hours * 60;
        this.print.dbg("Duration minutes given: " + minutesDouble);

        // intentional loss of precision
        this.durationMinutes = (int) minutesDouble;
        this.print.dbg("Duration minutes used: " + this.durationMinutes);

        this.durationMinutesConfigured = true;
        this.gotCmdLine(Opts.HOURS_OPT_STRING + " (converted to minutes)",
                Integer.toString(this.durationMinutes));
    }

    if (line.hasOption(Opts.KERNEL_OPT_STRING)) {
        this.kernel = line.getOptionValue(Opts.KERNEL_OPT_STRING);
        this.gotCmdLine(Opts.KERNEL_OPT_STRING, this.kernel);
    }

    if (line.hasOption(Opts.LIST_OPT_STRING)) {
        this.actions.add(ACTION_LIST);
        this.gotCmdLine(Opts.LIST_OPT_STRING, "enabled");
    }

    if (line.hasOption(Opts.LOCAL_FILE_OPT_STRING)) {
        this.localfile = line.getOptionValue(Opts.LOCAL_FILE_OPT_STRING);
        this.gotCmdLine(Opts.LOCAL_FILE_OPT_STRING, this.localfile);
    }

    if (line.hasOption(Opts.NAME_OPT_STRING)) {
        this.name = line.getOptionValue(Opts.NAME_OPT_STRING);
        this.gotCmdLine(Opts.NAME_OPT_STRING, this.name);
    }

    if (line.hasOption(Opts.NEWNAME_OPT_STRING)) {
        this.newname = line.getOptionValue(Opts.NEWNAME_OPT_STRING);
        this.gotCmdLine(Opts.NEWNAME_OPT_STRING, this.newname);
    }

    if (line.hasOption(Opts.NOCTXLOCK_OPT_STRING)) {
        this.noContextLock = true;
        this.gotCmdLine(Opts.NOCTXLOCK_OPT_STRING, "enabled");
    }

    if (line.hasOption(Opts.NOTIFICATIONS_OPT_STRING)) {
        this.useNotifications = true;
        this.useNotificationsConfigured = true;
        this.gotCmdLine(Opts.NOTIFICATIONS_OPT_STRING, "enabled");
    }

    if (line.hasOption(Opts.POLL_INTERVAL_OPT_STRING)) {
        final String msString = line.getOptionValue(Opts.POLL_INTERVAL_OPT_STRING);
        this.pollMs = Integer.parseInt(msString);
        this.pollMsConfigured = true;
        this.gotCmdLine(Opts.POLL_INTERVAL_OPT_STRING, msString);
    }

    if (line.hasOption(Opts.PRINT_CTX_STATUS_OPT_STRING)) {
        this.actions.add(ACTION_PRINT_CTX_STATUS);
        this.gotCmdLine(Opts.PRINT_CTX_STATUS_OPT_STRING, "enabled");
    }

    if (line.hasOption(Opts.PRINT_TARGET_OPT_STRING)) {
        this.actions.add(ACTION_TARGET_PRINT);
        this.gotCmdLine(Opts.PRINT_TARGET_OPT_STRING, "enabled");
    }

    if (line.hasOption(Opts.PROPFILE_OPT_STRING)) {
        this.propertiesPath = line.getOptionValue(Opts.PROPFILE_OPT_STRING);
        this.gotCmdLine(Opts.PROPFILE_OPT_STRING, this.propertiesPath);
    }

    if (line.hasOption(Opts.RUN_OPT_STRING)) {
        this.actions.add(ACTION_RUN);
        this.gotCmdLine(Opts.RUN_OPT_STRING, "enabled");
    }

    if (line.hasOption(Opts.SAVE_OPT_STRING)) {
        this.actions.add(ACTION_SAVE);
        this.gotCmdLine(Opts.SAVE_OPT_STRING, "enabled");
    }

    if (line.hasOption(Opts.SECURITY_OPT_STRING)) {
        this.actions.add(ACTION_SECURITY_PRINT);
        this.gotCmdLine(Opts.SECURITY_OPT_STRING, "enabled");
    }

    if (line.hasOption(Opts.SOURCEFILE_OPT_STRING)) {
        this.sourcefile = line.getOptionValue(Opts.SOURCEFILE_OPT_STRING);
        this.gotCmdLine(Opts.SOURCEFILE_OPT_STRING, this.sourcefile);
    }

    if (line.hasOption(Opts.SSH_FILE_OPT_STRING)) {
        this.sshfile = line.getOptionValue(Opts.SSH_FILE_OPT_STRING);
        this.gotCmdLine(Opts.SSH_FILE_OPT_STRING, this.sshfile);
    }

    if (line.hasOption(Opts.STATUS_CHECK_OPT_STRING)) {
        this.actions.add(ACTION_STATUS_CHECK);
        this.gotCmdLine(Opts.STATUS_CHECK_OPT_STRING, "enabled");
    }

    if (line.hasOption(Opts.TARGETDIR_OPT_STRING)) {
        this.targetBaseDirectory = line.getOptionValue(Opts.TARGETDIR_OPT_STRING);
        this.gotCmdLine(Opts.TARGETDIR_OPT_STRING, this.targetBaseDirectory);
    }

    if (line.hasOption(Opts.TIMEOUT_OPT_STRING)) {
        final String timeoutString = line.getOptionValue(Opts.TIMEOUT_OPT_STRING);
        final double hours = Double.parseDouble(timeoutString);
        final double minutesDouble = hours * 60;
        this.print.dbg("Timeout minutes given: " + minutesDouble);

        // intentional loss of precision
        this.timeoutMinutes = (int) minutesDouble;
        this.print.dbg("Timeout minutes used: " + this.timeoutMinutes);

        this.timeoutMinutesConfigured = true;
        this.gotCmdLine(Opts.TIMEOUT_OPT_STRING, Integer.toString(this.timeoutMinutes));
    }

    if (line.hasOption(Opts.COMMON_OPT_STRING)) {
        this.common_image = true;
        this.gotCmdLine(Opts.COMMON_OPT_STRING, "enabled");
    }

    if (line.hasOption(Opts.IMAGE_DESC_OPT_STRING)) {
        final String imageDescString = line.getOptionValue(Opts.IMAGE_DESC_OPT_STRING);
        this.imageDescString = imageDescString;
        this.gotCmdLine(Opts.IMAGE_DESC_OPT_STRING, imageDescString);
    }

    if (line.hasOption(Opts.NOSPINNER_OPT_STRING)) {
        this.nospinner = true;
        this.gotCmdLine(Opts.NOSPINNER_OPT_STRING, "enabled");
    }

    if (line.hasOption(Opts.TRANSFER_OPT_STRING)) {
        this.actions.add(ACTION_TRANSFER);
        this.gotCmdLine(Opts.TRANSFER_OPT_STRING, "enabled");
    }

    if (line.hasOption(Opts.USAGE_OPT_STRING)) {
        this.actions.add(ACTION_USAGE);
        this.gotCmdLine(Opts.USAGE_OPT_STRING, "enabled");
    }

    CommonPrint.printDebugSectionEnd(this.print, sectionTitle);
}

From source file:org.globus.workspace.remoting.admin.client.AdminClient.java

private void loadArgs(String[] args) throws ParameterProblem {

    logger.debug("Parsing command line arguments");
    final CommandLineParser parser = new PosixParser();

    final Opts opts = new Opts();
    final CommandLine line;
    try {/*from   w ww  .j  a v a 2  s.  c o  m*/
        line = parser.parse(opts.getOptions(), args);
    } catch (ParseException e) {
        throw new ParameterProblem(e.getMessage(), e);
    }

    // figure action first
    AdminAction theAction = null;
    for (AdminAction a : AdminAction.values()) {
        if (line.hasOption(a.option())) {
            if (theAction == null) {
                theAction = a;
            } else {
                throw new ParameterProblem("You may only specify a single action");
            }
        }
    }

    if (theAction == null) {
        throw new ParameterProblem("You must specify an action");
    }

    this.action = theAction;
    logger.debug("Action: " + theAction);

    // short circuit for --help arg
    if (theAction == AdminAction.Help) {
        return;
    }

    // then action-specific arguments
    if (theAction == AdminAction.AddNodes || theAction == AdminAction.UpdateNodes) {
        this.hosts = parseHosts(line.getOptionValue(theAction.option()));

        if (line.hasOption(Opts.MEMORY)) {
            final String memString = line.getOptionValue(Opts.MEMORY);
            if (memString == null || memString.trim().length() == 0) {
                throw new ParameterProblem("Node memory value is empty");
            }
            this.nodeMemory = parseMemory(memString);
            this.nodeMemoryConfigured = true;
        }

        if (line.hasOption(Opts.NETWORKS)) {
            this.nodeNetworks = line.getOptionValue(Opts.NETWORKS);
        }

        if (line.hasOption(Opts.POOL)) {
            String pool = line.getOptionValue(Opts.POOL);
            if (pool == null || pool.trim().length() == 0) {
                throw new ParameterProblem("Node pool value is empty");
            }
            this.nodePool = pool.trim();
        }

        final boolean active = line.hasOption(Opts.ACTIVE);
        final boolean inactive = line.hasOption(Opts.INACTIVE);

        if (active && inactive) {
            throw new ParameterProblem(
                    "You cannot specify both " + Opts.ACTIVE_LONG + " and " + Opts.INACTIVE_LONG);
        }

        if (active) {
            this.nodeActiveConfigured = true;
        }
        if (inactive) {
            this.nodeActive = false;
            this.nodeActiveConfigured = true;
        }

    } else if (theAction == AdminAction.RemoveNodes) {
        this.hosts = parseHosts(line.getOptionValue(theAction.option()));
    } else if (theAction == AdminAction.ListNodes) {
        final String hostArg = line.getOptionValue(AdminAction.ListNodes.option());
        if (hostArg != null) {
            this.hosts = parseHosts(hostArg);
        }
    } else if (theAction == AdminAction.PoolAvailability) {
        if (line.hasOption(Opts.POOL)) {
            final String pool = line.getOptionValue(Opts.POOL);
            if (pool == null || pool.trim().length() == 0) {
                throw new ParameterProblem("Pool name value is empty");
            }
            this.nodePool = pool;
        }
        if (line.hasOption(Opts.FREE)) {
            this.inUse = RemoteNodeManagement.FREE_ENTRIES;
        }
        if (line.hasOption(Opts.USED)) {
            this.inUse = RemoteNodeManagement.USED_ENTRIES;
        }
    }

    //finally everything else
    if (!line.hasOption(Opts.CONFIG)) {
        throw new ParameterProblem(Opts.CONFIG_LONG + " option is required");
    }
    String config = line.getOptionValue(Opts.CONFIG);
    if (config == null || config.trim().length() == 0) {
        throw new ParameterProblem("Config file path is invalid");
    }
    super.configPath = config.trim();

    final boolean batchMode = line.hasOption(Opts.BATCH);
    final boolean json = line.hasOption(Opts.JSON);

    final Reporter.OutputMode mode;
    if (batchMode && json) {
        throw new ParameterProblem("You cannot specify both " + Opts.BATCH_LONG + " and " + Opts.JSON_LONG);
    } else if (batchMode) {
        mode = Reporter.OutputMode.Batch;
    } else if (json) {
        mode = Reporter.OutputMode.Json;
    } else {
        mode = Reporter.OutputMode.Friendly;
    }

    final String[] fields;
    if (line.hasOption(Opts.REPORT)) {
        fields = parseFields(line.getOptionValue(Opts.REPORT), theAction);
    } else {
        fields = theAction.fields();
    }

    String delimiter = null;
    if (line.hasOption(Opts.DELIMITER)) {
        delimiter = line.getOptionValue(Opts.DELIMITER);
    }

    this.reporter = new Reporter(mode, fields, delimiter);

    if (line.hasOption(Opts.OUTPUT)) {
        final String filename = line.getOptionValue(Opts.OUTPUT);
        final File f = new File(filename);
        try {
            this.outStream = new FileOutputStream(f);
        } catch (FileNotFoundException e) {
            throw new ParameterProblem(
                    "Specified output file could not be opened for writing: " + f.getAbsolutePath(), e);
        }
    } else {
        this.outStream = System.out;
    }

    final List leftovers = line.getArgList();
    if (leftovers != null && !leftovers.isEmpty()) {
        throw new ParameterProblem("There are unrecognized arguments, check -h to make "
                + "sure you are doing the intended thing: " + leftovers.toString());
    }

}

From source file:org.globus.workspace.remoting.admin.client.RemoteAdminToolsMain.java

private void loadArgs(String[] args) throws ParameterProblem {

    logger.debug("Parsing command line arguments");
    final CommandLineParser parser = new PosixParser();

    final Opts opts = new Opts();
    final CommandLine line;
    try {// ww  w .  j a v  a2  s .  co  m
        line = parser.parse(opts.getOptions(), args);
    } catch (ParseException e) {
        throw new ParameterProblem(e.getMessage(), e);
    }

    // figure action first
    ToolAction tAction = null;
    for (ToolAction t : ToolAction.values()) {
        if (line.hasOption(t.option())) {
            if (tAction == null) {
                tAction = t;
            } else {
                throw new ParameterProblem("You may only specify a single action");
            }
        }
    }

    if (tAction == null) {
        throw new ParameterProblem("You must specify an action");
    }

    this.action = tAction;
    logger.debug("Action: " + tAction);

    // short circuit for --help arg
    if (tAction == ToolAction.Help) {
        return;
    }

    //numOpts just makes sure you don't have non-compatible options running at the same time
    if (this.action == ToolAction.ListVMs) {
        if (line.hasOption(Opts.USER)) {
            final String user = line.getOptionValue(Opts.USER);
            if (user == null || user.trim().length() == 0) {
                throw new ParameterProblem("User value is empty");
            }
            this.user = user;
            numOpts++;
        }
        if (line.hasOption(Opts.DN)) {
            final String dn = line.getOptionValue(Opts.DN);
            if (dn == null || dn.trim().length() == 0) {
                throw new ParameterProblem("User DN value is empty");
            }
            this.userDN = dn;
            numOpts++;
        }
        if (line.hasOption(Opts.GROUP_ID)) {
            final String gid = line.getOptionValue(Opts.GROUP_ID);
            if (gid == null || gid.trim().length() == 0) {
                throw new ParameterProblem("Group id value is empty");
            }
            this.groupId = gid;
            numOpts++;
        }
        if (line.hasOption(Opts.GROUP_NAME)) {
            final String gname = line.getOptionValue(Opts.GROUP_NAME);
            if (gname == null || gname.trim().length() == 0) {
                throw new ParameterProblem("Group name value is empty");
            }
            this.groupName = gname;
            numOpts++;
        }
        if (line.hasOption(Opts.HOST)) {
            final String hostname = line.getOptionValue(Opts.HOST);
            if (hostname == null || hostname.trim().length() == 0) {
                throw new ParameterProblem("Host value is empty");
            }
            this.hostname = hostname;
            numOpts++;
        }
        if (line.hasOption(Opts.STATE)) {
            final String state = line.getOptionValue(Opts.STATE);
            if (state == null || state.trim().length() == 0) {
                throw new ParameterProblem("State value is empty");
            }
            this.state = state;
            numOpts++;
        }
    } else if (this.action == ToolAction.ShutdownVMs || this.action == ToolAction.CleanupVMs) {
        if (line.hasOption(Opts.ALL_VMS)) {
            allVMs = true;
            numOpts++;
        }
        if (line.hasOption(Opts.ID)) {
            final String id = line.getOptionValue(Opts.ID);
            if (id == null || id.trim().length() == 0) {
                throw new ParameterProblem("VM ID value is empty");
            }
            this.vmIDs = parseValues(id);
            numOpts++;
        }
        if (line.hasOption(Opts.USER)) {
            final String user = line.getOptionValue(Opts.USER);
            if (user == null || user.trim().length() == 0) {
                throw new ParameterProblem("User value is empty");
            }
            this.userList = parseValues(user);
            numOpts++;
        }
        if (line.hasOption(Opts.DN)) {
            final String dn = line.getOptionValue(Opts.DN);
            if (dn == null || dn.trim().length() == 0) {
                throw new ParameterProblem("DN value is empty");
            }
            this.DNList = parseValues(dn);
            numOpts++;
        }
        if (line.hasOption(Opts.GROUP_ID)) {
            final String gid = line.getOptionValue(Opts.GROUP_ID);
            if (gid == null || gid.trim().length() == 0) {
                throw new ParameterProblem("Group id value is empty");
            }
            this.gidList = parseValues(gid);
            numOpts++;
        }
        if (line.hasOption(Opts.GROUP_NAME)) {
            final String gname = line.getOptionValue(Opts.GROUP_NAME);
            if (gname == null || gname.trim().length() == 0) {
                throw new ParameterProblem("Group name value is empty");
            }
            this.gnameList = parseValues(gname);
            numOpts++;
        }
        if (line.hasOption(Opts.HOST)) {
            final String hostname = line.getOptionValue(Opts.HOST);
            if (hostname == null || hostname.trim().length() == 0) {
                throw new ParameterProblem("Hostname value is empty");
            }
            this.hostList = parseValues(hostname);
            numOpts++;
        }
        if (line.hasOption(Opts.SECONDS)) {
            final String seconds = line.getOptionValue(Opts.SECONDS);
            if (seconds == null || seconds.trim().length() == 0) {
                throw new ParameterProblem("Seconds value is empty");
            }
            this.seconds = seconds;
        }
    }

    //finally everything else
    if (!line.hasOption(Opts.CONFIG)) {
        throw new ParameterProblem(Opts.CONFIG_LONG + " option is required");
    }
    String config = line.getOptionValue(Opts.CONFIG);
    if (config == null || config.trim().length() == 0) {
        throw new ParameterProblem("Config file path is invalid");
    }
    super.configPath = config.trim();

    final boolean batchMode = line.hasOption(Opts.BATCH);
    final boolean json = line.hasOption(Opts.JSON);
    force = line.hasOption(Opts.FORCE);

    final Reporter.OutputMode mode;
    if (batchMode && json) {
        throw new ParameterProblem("You cannot specify both " + Opts.BATCH_LONG + " and " + Opts.JSON_LONG);
    } else if (batchMode) {
        mode = Reporter.OutputMode.Batch;
    } else if (json) {
        mode = Reporter.OutputMode.Json;
    } else {
        mode = Reporter.OutputMode.Friendly;
    }

    final String[] fields;
    if (line.hasOption(Opts.REPORT)) {
        fields = parseFields(line.getOptionValue(Opts.REPORT), tAction);
    } else {
        fields = tAction.fields();
    }

    String delimiter = null;
    if (line.hasOption(Opts.DELIMITER)) {
        delimiter = line.getOptionValue(Opts.DELIMITER);
    }

    if (fields != null)
        this.reporter = new Reporter(mode, fields, delimiter);

    if (line.hasOption(Opts.OUTPUT)) {
        final String filename = line.getOptionValue(Opts.OUTPUT);
        final File f = new File(filename);
        try {
            this.outStream = new FileOutputStream(f);
        } catch (FileNotFoundException e) {
            throw new ParameterProblem(
                    "Specified output file could not be opened for writing: " + f.getAbsolutePath(), e);
        }
    } else {
        this.outStream = System.out;
    }

    final List leftovers = line.getArgList();
    if (leftovers != null && !leftovers.isEmpty()) {
        throw new ParameterProblem("There are unrecognized arguments, check -h to make "
                + "sure you are doing the intended thing: " + leftovers.toString());
    }

}

From source file:org.gridchem.client.GridChem.java

/**
 * Utility class to parse the command line.  Options are final static constants
 * defined in this class.  We use the apache command line tools to parse the 
 * command line used to run this app against the set of known options.  Appropriate
 * action is taken accordingly.// www  .ja va  2 s  .  c  o  m
 * 
 * @param args
 * @throws Exception
 */
private static void parseCommandLine(String[] args) throws Exception {
    Trace.entry();

    CommandLineParser parser = new PosixParser();
    CommandLine line = parser.parse(options, args);

    Settings.WEBSERVICE = true;

    // all command line flags are exclusive. only one will be
    // accepted at a time.
    if (line.getArgList().size() < 0) {
        Settings.DEVEL = false;
        Settings.FAILOVER = false;
        Settings.DEBUG = false;
        Settings.LOCAL = false;
        Trace.note("Using vanilla version of client");
        return;
    } else if (line.hasOption("f")) {
        Settings.FAILOVER = true;
        // change to the derrick or uky server
        Invariants.httpsGateway = "https://derrick.tacc.utexas.edu/cgi-bin/";
        Invariants.kerbGateway = "https://derrick.tacc.utexas.edu/cgi-bin/";
        Invariants.wsGateway = "http://129.114.4.7:8443/wsrf/services/GMSService";
        Trace.note("Using development version of client");
    } else if (line.hasOption("d")) {
        /*            Settings.DEVEL = true;
                    Invariants.httpsGateway = Invariants.httpsGateway + "devel/";
                    Invariants.kerbGateway = Invariants.kerbGateway + "devel/";
                    Invariants.wsGateway = "http://129.114.4.7:8080/wsrf/services/GMSService";
                    Trace.note("Using development version of client");*/
        Settings.DEVEL = true;
        Invariants.httpsGateway = "https://ccg-mw2.ncsa.uiuc.edu/cgi-bin/devel/";
        Invariants.kerbGateway = Invariants.kerbGateway + "devel/";
        Invariants.wsGateway = "http://ccg-mw2.ncsa.uiuc.edu:8080/wsrf/services/GMSService";
        Trace.note("Using development version of client");
    } else if (line.hasOption("l")) {
        Settings.LOCAL = true;
        Invariants.wsGateway = "http://127.0.0.1:8080/wsrf/services/GMSService";
        Trace.note("Using development version of client with local services");
    } else if (line.hasOption("h")) {
        displayUsage();
        System.exit(0);
    } else {
        // ccg-mw1.ncsa.uiuc.edu as production server
        Invariants.wsGateway = "http://141.142.56.171:8080/wsrf/services/GMSService";
        Trace.note("Using web service production version of client");
    }

    if (line.hasOption("v")) {
        Env.setVersion(line.getOptionValue("v"));
    }

    Trace.exit();
}

From source file:org.gudy.azureus2.ui.console.commands.Alias.java

public void execute(String commandName, ConsoleInput console, CommandLine commandLine) {

    List args = commandLine.getArgList();
    if (args.isEmpty()) {
        if (commandLine.hasOption('d'))
            console.out.println(commandName + " --delete requires the name of an alias to remove");
        else//from  w w w  . jav  a  2s  .c om
            printAliases(console);
        return;
    }
    if (commandLine.hasOption('d'))
        deleteAlias(console, (String) args.get(0));
    else {
        String aliasName = (String) args.remove(0);
        if (args.isEmpty()) {
            printAlias(console, aliasName);
        } else
            addAlias(console, aliasName, args);
    }
}

From source file:org.gudy.azureus2.ui.console.commands.Log.java

public void execute(String commandName, final ConsoleInput ci, CommandLine commandLine) {
    Appender con = Logger.getRootLogger().getAppender("ConsoleAppender");
    List args = commandLine.getArgList();
    if ((con != null) && (!args.isEmpty())) {
        String subcommand = (String) args.get(0);
        if ("off".equalsIgnoreCase(subcommand)) {
            if (args.size() == 1) {
                con.addFilter(new DenyAllFilter());
                ci.out.println("> Console logging off");
            } else {

                String name = (String) args.get(1);

                Object[] entry = (Object[]) channel_listener_map.remove(name);

                if (entry == null) {

                    ci.out.println("> Channel '" + name + "' not being logged");

                } else {

                    ((LoggerChannel) entry[0]).removeListener((LoggerChannelListener) entry[1]);

                    ci.out.println("> Channel '" + name + "' logging off");
                }//from  w ww  .j  a v  a 2s. co  m
            }
        } else if ("on".equalsIgnoreCase(subcommand)) {

            if (args.size() == 1) {

                if (commandLine.hasOption('f')) {
                    // send log output to a file
                    String filename = commandLine.getOptionValue('f');

                    try {
                        Appender newAppender = new FileAppender(new PatternLayout("%d{ISO8601} %c{1}-%p: %m%n"),
                                filename, true);
                        newAppender.setName("ConsoleAppender");
                        Logger.getRootLogger().removeAppender(con);
                        Logger.getRootLogger().addAppender(newAppender);
                        ci.out.println("> Logging to filename: " + filename);
                    } catch (IOException e) {
                        ci.out.println("> Unable to log to file: " + filename + ": " + e);
                    }
                } else {
                    if (!(con instanceof ConsoleAppender)) {
                        Logger.getRootLogger().removeAppender(con);
                        con = new ConsoleAppender(new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN));
                        con.setName("ConsoleAppender");
                        Logger.getRootLogger().addAppender(con);
                    }
                    // switch back to console appender
                    ci.out.println("> Console logging on");
                }

                con.clearFilters();
            } else {
                // hack - dunno how to do plugin-specific logging using these damn appenders..

                Map channel_map = getChannelMap(ci);

                final String name = (String) args.get(1);

                LoggerChannel channel = (LoggerChannel) channel_map.get(name);

                if (channel == null) {

                    ci.out.println("> Channel '" + name + "' not found");

                } else if (channel_listener_map.get(name) != null) {

                    ci.out.println("> Channel '" + name + "' already being logged");

                } else {

                    LoggerChannelListener l = new LoggerChannelListener() {
                        public void messageLogged(int type, String content) {
                            ci.out.println("[" + name + "] " + content);
                        }

                        public void messageLogged(String str, Throwable error) {
                            ci.out.println("[" + name + "] " + str);

                            error.printStackTrace(ci.out);
                        }
                    };

                    channel.addListener(l);

                    channel_listener_map.put(name, new Object[] { channel, l });

                    ci.out.println("> Channel '" + name + "' on");
                }

            }
        } else if (subcommand.equalsIgnoreCase("list")) {

            Map channel_map = getChannelMap(ci);

            Iterator it = channel_map.keySet().iterator();

            while (it.hasNext()) {

                String name = (String) it.next();

                ci.out.println(
                        "  " + name + " [" + (channel_listener_map.get(name) == null ? "off" : "on") + "]");
            }
        } else {

            ci.out.println("> Command 'log': Subcommand '" + subcommand + "' unknown.");
        }
    } else {
        ci.out.println(
                "> Console logger not found or missing subcommand for 'log'\r\n> log syntax: log [-f filename] (on [name]|off [name]|list)");
    }
}

From source file:org.gudy.azureus2.ui.console.commands.Priority.java

public void execute(String commandName, ConsoleInput console, CommandLine commandLine) {

    String tnumstr, fnumstr, newpriostr;
    int tnumber;// w  w  w  .  j av a 2 s.co m
    DiskManagerFileInfo[] files;
    String[] sections;
    List args = commandLine.getArgList();
    LinkedList fs, fe;
    DownloadManager dm;

    if (args.isEmpty()) {
        console.out.println("Torrent # required!");
        return;
    } else {
        tnumstr = (String) args.remove(0);
    }
    if (args.isEmpty()) {
        console.out.println("File # required!");
        return;
    } else {
        fnumstr = (String) args.remove(0);
    }

    if ((console.torrents == null) || console.torrents.isEmpty()) {
        console.out.println("> Command 'prio': No torrents in list (try 'show torrents' first).");
        return;
    }

    try {
        tnumber = Integer.parseInt(tnumstr);
        if ((tnumber == 0) || (tnumber > console.torrents.size())) {
            console.out.println("> Command 'prio': Torrent #" + tnumber + " unknown.");
            return;
        }

        dm = (DownloadManager) console.torrents.get(tnumber - 1);
        files = dm.getDiskManagerFileInfo();
    } catch (Exception e) {
        e.printStackTrace();
        console.out.println("> Command 'prio': Torrent # '" + tnumstr + "' unknown.");
        return;
    }

    if (args.isEmpty()) {
        console.out.println("> Command 'prio': missing parameter for new priority");
        return;
    } else {
        newpriostr = (String) args.remove(0);
    }

    if (newpriostr.equalsIgnoreCase("normal")) {
        newprio = NORMAL;
    } else if (newpriostr.equalsIgnoreCase("high")) {
        newprio = HIGH;
    } else if (newpriostr.equalsIgnoreCase("dnd")) {
        newprio = DONOTDOWNLOAD;
    } else if (newpriostr.equalsIgnoreCase("del")) {
        newprio = DELETE;
    } else {
        console.out.println("> Command 'prio': unknown priority " + newpriostr);
        return;
    }

    if (fnumstr.equalsIgnoreCase("all")) {
        sections = new String[1];
        sections[0] = "1-" + files.length;
    } else
        sections = fnumstr.split(",");

    fs = new LinkedList();
    fe = new LinkedList();

    int dash, start, end;
    for (int i = 0; i < sections.length; i++) {
        try {
            if ((dash = sections[i].indexOf('-')) != -1) {
                start = Integer.parseInt(sections[i].substring(0, dash));
                end = Integer.parseInt(sections[i].substring(dash + 1));
            } else
                start = end = Integer.parseInt(sections[i]);
            if ((start == 0) || (end > files.length)) {
                console.out.println("> Command 'prio': Invalid file range " + sections[i]);
                return;
            }
            if (start > end) {
                console.out.println("> Command 'prio': Invalid file range '" + sections[i] + "'");
            }

            // -1 compensates for 0-based offsets
            fs.add(new Integer(start - 1));
            fe.add(new Integer(end - 1));
        } catch (Exception e) {
            console.out.println("> Command 'prio': File # '" + sections[i] + "' unknown.");
            return;
        }
    }

    //      console.out.println("DM was " + dm.getState());
    if ((newprio == DELETE) && (dm.getState() != DownloadManager.STATE_STOPPED)) {
        try {
            dm.stopIt(DownloadManager.STATE_STOPPED, false, false);
        } catch (Exception e) {
            console.out.println("Failed to stop torrent " + tnumber);
            return;
        }
    }

    //      console.out.println("DM is " + dm.getState());
    int nummod = 0;
    while (fs.size() > 0) {
        start = ((Integer) fs.removeFirst()).intValue();
        end = ((Integer) fe.removeFirst()).intValue();
        for (int i = start; i <= end; i++) {
            nummod++;
            // DEBUG
            //            console.out.println("Setting priority for file " + i + " to " + newprio);
            if (newprio == NORMAL) {
                files[i].setPriority(0);
                files[i].setSkipped(false);
            } else if (newprio == HIGH) {
                files[i].setPriority(1);
                files[i].setSkipped(false);
            } else if (newprio == DONOTDOWNLOAD) {
                files[i].setPriority(0);
                files[i].setSkipped(true);
            } else if (newprio == DELETE) {
                int st = files[i].getStorageType();
                int target_st = -1;
                if (st == DiskManagerFileInfo.ST_LINEAR) {
                    target_st = DiskManagerFileInfo.ST_COMPACT;
                } else if (st == DiskManagerFileInfo.ST_REORDER) {
                    target_st = DiskManagerFileInfo.ST_REORDER_COMPACT;
                }
                if (target_st != -1 && files[i].setStorageType(target_st)) {
                    files[i].setPriority(0);
                    files[i].setSkipped(true);
                } else {
                    console.out.println("> Command 'prio': Failed to delete file " + (i + 1));
                    nummod--;
                }
            }
        }
    }
    if ((newprio == DELETE) && (dm.getState() == DownloadManager.STATE_STOPPED)) {
        try {
            dm.stopIt(DownloadManager.STATE_QUEUED, false, false);
        } catch (Exception e) {
            console.out.println("Failed to restart torrent " + tnumber);
            return;
        }
    }

    //      console.out.println("DM is again " + dm.getState());

    console.out.println(nummod + " file(s) priority set to " + priostr[newprio - 1]);
}

From source file:org.guvnor.jcr2vfsmigration.config.MigrationConfig.java

public void parseArgs(String[] args) {
    Options options = new Options();
    options.addOption("i", "inputJcrRepository", true, "The Guvnor 5 JCR repository");
    options.addOption("o", "outputVfsRepository", true, "The Guvnor 6 VFS repository");
    CommandLine commandLine;
    try {//w  ww.j  a v  a 2  s . c  o m
        commandLine = new BasicParser().parse(options, args);
    } catch (ParseException e) {
        throw new IllegalArgumentException("The arguments (" + Arrays.toString(args) + ") could not be parsed.",
                e);
    }
    if (!commandLine.getArgList().isEmpty()) {
        throw new IllegalArgumentException("The arguments (" + Arrays.toString(args)
                + ") have unsupported arguments (" + commandLine.getArgList() + ").");
    }
    parseArgInputJcrRepository(commandLine);
    parseArgOutputVfsRepository(commandLine);
}

From source file:org.hashes.ui.HashesCli.java

private static Configuration buidConfiguration(final CommandLine cmd)
        throws MalformedURLException, ParseException {

    @SuppressWarnings("unchecked")
    final List<String> arguments = cmd.getArgList();

    if ((arguments == null) || arguments.isEmpty()) {
        throw new ParseException("Missing required option: url");
    } else if (arguments.size() > 1) {
        LOG.warn("Multiple urls are not allowed. Using: " + arguments.get(0));
    }/* w w  w. ja v a  2s. co m*/

    final URL url = new URL(arguments.get(0));

    // required fields
    final ConfigurationBuilder builder = new ConfigurationBuilder(url.getHost());

    // optional fields
    // URL
    builder.withSchemeName(url.getProtocol());
    final int port = url.getPort();
    if (port != -1) {
        builder.withPort(port);
    }
    final String path = url.getPath();
    if (!path.isEmpty()) {
        builder.withPath(path);
    }

    // algorithm
    final AbstractCollisionGenerator algorithm = getCollisionGenerator(cmd);
    if (algorithm != null) {
        builder.withCollisionGenerator(algorithm);
    }

    if (cmd.hasOption(CliOption.PROGRESS_BAR.getOption().getOpt())) {
        builder.withProgressMonitorFactory(new SysOutProgressMonitorFactory());
    }

    final String saveKeys = (String) cmd.getParsedOptionValue(CliOption.SAVE_KEYS.getOption().getOpt());
    if (saveKeys != null) {
        builder.saveCollisionsToFile(new File(saveKeys));
    }

    if (cmd.hasOption(CliOption.WAIT.getOption().getOpt())) {
        builder.waitForResponse();
    }

    if (cmd.hasOption(CliOption.NEW.getOption().getOpt())) {
        builder.generateNewKeys();
    }

    if (cmd.hasOption(CliOption.KEYS.getOption().getOpt())) {
        final Object keys = cmd.getParsedOptionValue(CliOption.KEYS.getOption().getOpt());
        final int numberOfkeys = ((Number) keys).intValue();
        if (numberOfkeys <= 0) {
            throw new ParseException("The number of keys should be greater than 0");
        }
        builder.withNumberOfKeys(numberOfkeys);
    }

    if (cmd.hasOption(CliOption.REQUESTS.getOption().getOpt())) {
        final Object requests = cmd.getParsedOptionValue(CliOption.REQUESTS.getOption().getOpt());
        final int numberOfRequests = ((Number) requests).intValue();
        if (numberOfRequests <= 0) {
            throw new ParseException("The number of requests should be greater than 0");
        }
        builder.withRequestsPerClient(numberOfRequests);
    }

    if (cmd.hasOption(CliOption.CLIENTS.getOption().getOpt())) {
        final Object clients = cmd.getParsedOptionValue(CliOption.CLIENTS.getOption().getOpt());
        final int numberOfClients = ((Number) clients).intValue();
        if (numberOfClients <= 0) {
            throw new ParseException("The number of clients should be greater than 0");
        }
        builder.withNumberOfClients(numberOfClients);
    }

    if (cmd.hasOption(CliOption.CONNECTION_TIMEOUT.getOption().getOpt())) {
        final Object timeout = cmd.getParsedOptionValue(CliOption.CONNECTION_TIMEOUT.getOption().getOpt());
        final int connectionTimeout = ((Number) timeout).intValue();
        if (connectionTimeout < 0) {
            throw new ParseException("The connection timeout should be greater than or equal to 0");
        }
        builder.withConnectTimeout(connectionTimeout * MILLIS_IN_SECOND);
    }

    if (cmd.hasOption(CliOption.READ_TIMEOUT.getOption().getOpt())) {
        final Object timeout = cmd.getParsedOptionValue(CliOption.READ_TIMEOUT.getOption().getOpt());
        final int readTimeout = ((Number) timeout).intValue();
        if (readTimeout < 0) {
            throw new ParseException("The read timeout should be greater than or equal to 0");
        }
        builder.withReadTimeout(readTimeout * MILLIS_IN_SECOND);
    }

    if (cmd.hasOption(CliOption.HEADER.getOption().getOpt())) {
        for (final String value : cmd.getOptionValues(CliOption.HEADER.getOption().getOpt())) {
            final String[] header = value.split(HEADER_SEPARATOR);
            // trim headers
            for (int i = 0; i < header.length; i++) {
                header[i] = header[i].trim();
            }

            if (header.length != 2 || header[0].isEmpty() || header[1].isEmpty()) {
                throw new ParseException("Malformed HTTP header: " + value);
            }

            builder.withHTTPHeader(header[0], header[1]);
        }
    }

    return builder.build();
}