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:com.archivas.clienttools.arcmover.cli.ArcMetadata.java

protected void parseArgs() throws ParseException {

    // create the command cmdLine parser
    CommandLineParser parser = new PosixParser();
    CommandLine cmdLine;

    // parse the command cmdLine arguments
    cmdLine = parser.parse(getOptions(), getArgs());

    // Help/* w  ww.  j a  v  a  2 s .c  o m*/
    printHelp = cmdLine.hasOption("h");
    if (printHelp) {
        return;
    }

    initializeProfiles(cmdLine.hasOption("insecure"));

    // See how we are getting the input list: file or from stdin
    @SuppressWarnings({ "unchecked" })
    List<String> argList = cmdLine.getArgList();

    // Handle the load schedule and export lists
    LoadSchedule schedule = LoadSchedule.getDefaultLoadSchedule();
    getLoadSchedule(cmdLine, schedule);
    setUpExportListThread(cmdLine);

    // See if we are rerunning, set up the job if we are
    boolean rerunning = handleRerunAndResume(cmdLine, schedule);

    if (rerunning) {
        List<String> extraOptions = new ArrayList<String>();
        if (cmdLine.hasOption(PROFILE_OPTION)) {
            extraOptions.add(PROFILE_OPTION);
        }
        if (cmdLine.hasOption(PATH_OPTION)) {
            extraOptions.add(PATH_OPTION);
        }
        if (cmdLine.hasOption(JOB_NAME)) {
            extraOptions.add(JOB_NAME);
        }
        if (cmdLine.hasOption(HOLD_OPTION)) {
            extraOptions.add(HOLD_OPTION);
        }
        if (cmdLine.hasOption(INDEX_OPTION)) {
            extraOptions.add(INDEX_OPTION);
        }
        if (cmdLine.hasOption(SHRED_OPTION)) {
            extraOptions.add(SHRED_OPTION);
        }
        if (cmdLine.hasOption(RETENTION_OPTION)) {
            extraOptions.add(RETENTION_OPTION);
        }
        if (cmdLine.hasOption(CUSTOM_METADATA_OPTION)) {
            extraOptions.add(CUSTOM_METADATA_OPTION);
        }
        if (cmdLine.hasOption(ACL_OPTION)) {
            extraOptions.add(ACL_OPTION);
        }
        if (cmdLine.hasOption(OWNER_OPTION)) {
            extraOptions.add(OWNER_OPTION);
        }
        if (cmdLine.hasOption(DOMAIN_OPTION)) {
            extraOptions.add(DOMAIN_OPTION);
        }
        if (!extraOptions.isEmpty()) {
            throw new ParseException("The following supplied options are not allowed with --" + RESUME
                    + " or --" + RERUN + ": " + extraOptions);
        }
        // The list_file is not allowed for rerun/resume
        if (argList.size() > numCmdLineArgs - 1) {
            throw new ParseException(
                    "The list_file argument is not allowed with --" + RESUME + " or --" + RERUN);
        }

    } else {
        if (argList.size() != numCmdLineArgs) {
            throw new ParseException("Missing argument list_file.");
        }

        String listFileName = argList.get(numCmdLineArgs - 1);

        // Required fields

        // Parse require options
        String profileName = getProfileNameFromCmdLineAndValidateExistance(cmdLine, PROFILE_OPTION);
        AbstractProfileBase profile = ProfileManager.getProfileByName(profileName);

        if (!profile.isAuthNamespace()) {
            throw new ParseException("Metadata may only be set on HCP namespaces.");
        }

        String path = validatePath(cmdLine);

        // Optional fields
        String jobName = null;
        if (cmdLine.hasOption(JOB_NAME)) {
            jobName = cmdLine.getOptionValue(JOB_NAME);
        }

        FileMetadata metadata = new FileMetadata();

        if (cmdLine.hasOption(INDEX_OPTION)) {
            metadata.setSearchIndex(new Boolean(cmdLine.getOptionValue(INDEX_OPTION)));
        }
        if (cmdLine.hasOption(HOLD_OPTION)) {
            metadata.setRetentionHold(new Boolean(cmdLine.getOptionValue(HOLD_OPTION)));
        }
        if (cmdLine.hasOption(SHRED_OPTION)) {
            metadata.setShred(new Boolean(cmdLine.getOptionValue(SHRED_OPTION)));
        }

        if (cmdLine.hasOption(RETENTION_OPTION)) {
            String cmdLineRetentionValue = cmdLine.getOptionValue(RETENTION_OPTION);
            Retention retention = Retention.fromHcapValue(cmdLineRetentionValue);
            metadata.setRetention(retention);
        }

        if (cmdLine.hasOption(CUSTOM_METADATA_OPTION)) {
            CustomMetadata customMetadata = new CustomMetadata(CustomMetadata.Form.FILE,
                    cmdLine.getOptionValue(CUSTOM_METADATA_OPTION));
            metadata.setCustomMetadata(customMetadata);
        }

        if (cmdLine.hasOption(ACL_OPTION)) {
            if (profile.supportsACLs()) {
                ACLMetadata acl = new ACLMetadata(CustomMetadata.Form.FILE, cmdLine.getOptionValue(ACL_OPTION));
                metadata.setACL(acl);
            } else {
                throw new ParseException("The " + ACL_OPTION
                        + " may only be specified when updating a HCP 5.0 or later namespace.");
            }
        }

        // throw an exception if anonymous user tries to set owner for objects
        if (profile.isAnonymousAccess()) {
            if (cmdLine.hasOption(OWNER_OPTION)) {
                throw new ParseException("Cannot use owner option with an anonymous namespace profile.");
            }
        }

        if (profile.supportsOwner()) {
            if (cmdLine.hasOption(OWNER_OPTION)) {
                Owner owner;
                if (cmdLine.hasOption(DOMAIN_OPTION)) {
                    owner = new Owner(cmdLine.getOptionValue(OWNER_OPTION),
                            cmdLine.getOptionValue(DOMAIN_OPTION));
                } else {
                    String ownerName = cmdLine.getOptionValue(OWNER_OPTION);
                    if (ownerName.length() == 0) {
                        owner = new Owner(Owner.OwnerType.PUBLIC);
                    } else {
                        owner = new Owner(ownerName);
                    }
                }
                metadata.setOwner(owner);
            }
        } else {
            List<String> extraOptions = new ArrayList<String>();
            if (cmdLine.hasOption(OWNER_OPTION)) {
                extraOptions.add(OWNER_OPTION);
            }
            if (cmdLine.hasOption(DOMAIN_OPTION)) {
                extraOptions.add(DOMAIN_OPTION);
            }
            if (!extraOptions.isEmpty()) {
                throw new ParseException(
                        "The following supplied options are only allowed when copying from the local file system to an HCP 5.0 or later namespace: "
                                + extraOptions);
            }
        }

        // Validate the input file if one was provided
        try {
            FileListParser.validateFile(new File(listFileName), profile, path, "");
        } catch (IOException e) {
            throw new ParseException("Error parsing input file.  Msg: " + e.getMessage());
        } catch (FileListParserException e) {
            throw new ParseException("Error parsing input file.  Msg: " + e.getMessage());
        }

        // Setup the job with the arguments
        try {
            setupMetadataJob(listFileName, profile, path, jobName, metadata, schedule);
            managedJobImpl = arcMover.createManagedJob(managedJob);
        } catch (Exception e) {
            LOG.log(Level.SEVERE, "An error occurred preparing a metadata job", e);
            throw new ParseException(
                    "Error writing to database during file list parsing.  Msg: " + e.getMessage());
        }
    }
}

From source file:jsastrawi.cli.LemmatizeCmd.java

/**
 * Handle lemmatize command/*from ww  w.  j av  a 2s.com*/
 *
 * @param args arguments
 * @throws IOException IOException
 */
public void handle(String[] args) throws IOException {
    Options options = buildOptions();
    CommandLineParser parser = new DefaultParser();

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

        if (args.length == 0 || cmd.hasOption("h")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("lemmatize [args...] WORD...", options);
        } else {
            Set<String> dictionary;

            if (cmd.hasOption('d')) {
                dictionary = getDictionaryFromFile(cmd.getOptionValue('d'));
            } else {
                dictionary = getDefaultDictionary();
            }

            Lemmatizer l = new DefaultLemmatizer(dictionary);

            if (cmd.hasOption("tb")) {
                Map<String, String> map = scanTestBedMapFromFile(cmd.getOptionValue("tb"));
                runTestBed(map, l);
            } else if (!cmd.getArgList().isEmpty()) {
                for (String word : cmd.getArgs()) {
                    output.println(l.lemmatize(word));
                }
            }
        }
    } catch (ParseException ex) {
        Logger.getLogger(LemmatizeCmd.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:fr.ortolang.diffusion.client.cmd.CopyCommand.java

@Override
public void execute(String[] args) {
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd;
    String localPath = null;//from w  w  w  .  j a v  a2  s.  c om
    String workspace = null;
    String remotePath = null;

    try {
        cmd = parser.parse(options, args);
        if (cmd.hasOption("h")) {
            help();
        }
        String[] credentials = getCredentials(cmd);
        String username = credentials[0];
        String password = credentials[1];

        if (cmd.hasOption("w")) {
            workspace = cmd.getOptionValue("w");
        } else {
            System.out.println("Workspace key is needed (-w)");
            help();
        }

        if (cmd.hasOption("m")) {
            //TODO validate (with an enum ?)
            mode = cmd.getOptionValue("m");
        }

        List<String> argList = cmd.getArgList();
        if (argList.size() < 2) {
            System.out.println("Two arguments is needed (localpath and remotepath)");
            help();
        } else {
            localPath = argList.get(0);
            remotePath = argList.get(1);
        }

        client = OrtolangClient.getInstance();
        if (username.length() > 0) {
            client.getAccountManager().setCredentials(username, password);
            client.login(username);
        }
        System.out.println("Connected as user: " + client.connectedProfile());
        if (!Files.exists(Paths.get(localPath))) {
            errors.append("-> Le chemin local (").append(localPath).append(") n'existe pas\r\n");
        } else {
            //TODO Checks if remote Path exist
            if (Files.exists(Paths.get(localPath))) {
                copy(Paths.get(localPath), workspace, remotePath);
            }
        }
        if (errors.length() > 0) {
            System.out.println("## Some errors has been found : ");
            System.out.print(errors.toString());
        }

        client.logout();
        client.close();
    } catch (ParseException e) {
        System.out.println("Failed to parse command line properties " + e.getMessage());
        help();
    } catch (OrtolangClientException | OrtolangClientAccountException e) {
        System.out.println("Unexpected error !!");
        e.printStackTrace();
    }
}

From source file:jos.parser.Parser.java

public void parse(String[] args) {
    final Options options = new Options();
    options.addOption("h", "help", false, "Show usage info");
    options.addOption("d", "debug", false, "Show debug info");
    options.addOption("l", "limit", true, "Limit methods to methods for the specific API level (ex: 5_0)");
    options.addOption("a", "annotation", true, "Comment annotation to add, for example: 'since 6.0'");

    final CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    List<String> sources = null;
    try {/*from  w  ww  .j a  va2 s  .  c o  m*/
        cmd = parser.parse(options, args);
        @SuppressWarnings("unchecked")
        final List<String> arglist = cmd.getArgList();
        sources = arglist;
    } catch (ParseException e) {
        System.err.println("Error parsing command line: " + e.getMessage());
        return;
    }

    if (sources == null || sources.isEmpty() || cmd.hasOption('h')) {
        final HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("parse", options);
        return;
    }

    debug = cmd.hasOption('d');
    limit = cmd.getOptionValue('l', null);
    extraAnnotation = cmd.getOptionValue('a', null);

    for (final String f : sources) {
        final File fs = new File(f);
        try {
            boolean multiLineComment = false;
            r = new BufferedReader(new FileReader(fs));
            String line;
            while ((line = r.readLine()) != null) {
                line = line.trim();
                line = line.replace("UIKIT_EXTERN_CLASS ", "");

                if (line.startsWith("/*")) {
                    multiLineComment = true;
                }
                if (multiLineComment) {
                    if (line.endsWith("*/")) {
                        multiLineComment = false;
                        continue;
                    }
                }
                if (multiLineComment) {
                    continue;
                }

                if (line.startsWith("//")) {
                    continue;
                }
                if (line.startsWith("#")) {
                    continue;
                }
                if (line.length() == 0) {
                    continue;
                }
                if (line.startsWith("@class")) {
                    continue;
                }

                if (line.indexOf("_CLASS_AVAILABLE") != -1) {
                    int p = line.indexOf('@');
                    if (p == -1) {
                        continue;
                    }
                    line = line.substring(p);
                }

                if (line.indexOf("@interface") != -1) {
                    processInterface(clean("@interface", line));
                }
                if (line.indexOf("@protocol") != -1 && !line.endsWith(";") /*&& line.indexOf("<") != -1)*/) {
                    processProtocol(clean("@protocol", line));
                }
                if (line.indexOf("typedef NS_ENUM") != -1) {
                    processEnum(clean("typedef NS_ENUM", line));
                }
            }
        } catch (final IOException e) {
            System.err.println("Error parsing '" + f + "': " + e.getMessage());
            break;
        } finally {
            try {
                r.close();
            } catch (final IOException e) {

            }
        }
    }
    gencs.close();
}

From source file:com.msd.gin.halyard.tools.HalyardParallelExport.java

@Override
public int run(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(newOption("h", null, "Prints this help"));
    options.addOption(newOption("v", null, "Prints version"));
    options.addOption(newOption("s", "source_htable", "Source HBase table with Halyard RDF store"));
    options.addOption(newOption("q", "sparql_query",
            "SPARQL tuple or graph query with use of '" + PARALLEL_SPLIT_FUNCTION_URI + "' function"));
    options.addOption(newOption("t", "target_url",
            "file://<path>/<file_name>{0}.<ext> or hdfs://<path>/<file_name>{0}.<ext> or jdbc:<jdbc_connection>/<table_name>"));
    options.addOption(newOption("p", "property=value", "JDBC connection properties"));
    options.addOption(newOption("l", "driver_classpath", "JDBC driver classpath delimited by ':'"));
    options.addOption(newOption("c", "driver_class", "JDBC driver class name"));
    try {/*from   www.ja  v  a 2s .  c o  m*/
        CommandLine cmd = new PosixParser().parse(options, args);
        if (args.length == 0 || cmd.hasOption('h')) {
            printHelp(options);
            return -1;
        }
        if (cmd.hasOption('v')) {
            Properties p = new Properties();
            try (InputStream in = HalyardExport.class
                    .getResourceAsStream("/META-INF/maven/com.msd.gin.halyard/hbasesail/pom.properties")) {
                if (in != null)
                    p.load(in);
            }
            System.out.println("Halyard Parallel Export version " + p.getProperty("version", "unknown"));
            return 0;
        }
        if (!cmd.getArgList().isEmpty())
            throw new ExportException("Unknown arguments: " + cmd.getArgList().toString());
        for (char c : "sqt".toCharArray()) {
            if (!cmd.hasOption(c))
                throw new ExportException("Missing mandatory option: " + c);
        }
        for (char c : "sqtlc".toCharArray()) {
            String s[] = cmd.getOptionValues(c);
            if (s != null && s.length > 1)
                throw new ExportException("Multiple values for option: " + c);
        }
        String source = cmd.getOptionValue('s');
        String query = cmd.getOptionValue('q');
        if (!query.contains(PARALLEL_SPLIT_FUNCTION_NAME)) {
            throw new ExportException("Parallel export SPARQL query must contain '"
                    + PARALLEL_SPLIT_FUNCTION_URI + "' function.");
        }
        String target = cmd.getOptionValue('t');
        if ((target.startsWith("file:") || target.startsWith("hdfs:")) && !target.contains("{0}")) {
            throw new ExportException(
                    "Parallel export file target must contain '{0}' counter in the file path or name.");
        }
        getConf().set(SOURCE, source);
        getConf().set(QUERY, query);
        getConf().set(TARGET, target);
        String driver = cmd.getOptionValue('c');
        if (driver != null) {
            getConf().set(JDBC_DRIVER, driver);
        }
        String props[] = cmd.getOptionValues('p');
        if (props != null) {
            for (int i = 0; i < props.length; i++) {
                props[i] = Base64.encodeBase64String(props[i].getBytes(UTF8));
            }
            getConf().setStrings(JDBC_PROPERTIES, props);
        }
        TableMapReduceUtil.addDependencyJars(getConf(), HalyardExport.class, NTriplesUtil.class, Rio.class,
                AbstractRDFHandler.class, RDFFormat.class, RDFParser.class, HTable.class,
                HBaseConfiguration.class, AuthenticationProtos.class, Trace.class);
        HBaseConfiguration.addHbaseResources(getConf());
        Job job = Job.getInstance(getConf(), "HalyardParallelExport " + source + " -> " + target);
        String cp = cmd.getOptionValue('l');
        if (cp != null) {
            String jars[] = cp.split(":");
            for (int i = 0; i < jars.length; i++) {
                File f = new File(jars[i]);
                if (!f.isFile())
                    throw new ExportException("Invalid JDBC driver classpath element: " + jars[i]);
                job.addFileToClassPath(new Path(f.toURI()));
                jars[i] = f.getName();
            }
            job.getConfiguration().setStrings(JDBC_CLASSPATH, jars);
        }
        job.setJarByClass(HalyardParallelExport.class);
        job.setMaxMapAttempts(1);
        job.setMapperClass(ParallelExportMapper.class);
        job.setMapOutputKeyClass(NullWritable.class);
        job.setMapOutputValueClass(Void.class);
        job.setNumReduceTasks(0);
        job.setInputFormatClass(IndexedInputFormat.class);
        job.setOutputFormatClass(NullOutputFormat.class);
        TableMapReduceUtil.initCredentials(job);
        if (job.waitForCompletion(true)) {
            LOG.info("Parallel Export Completed..");
            return 0;
        }
        return -1;
    } catch (RuntimeException exp) {
        System.out.println(exp.getMessage());
        printHelp(options);
        throw exp;
    }

}

From source file:com.acmutv.ontoqa.ui.CliService.java

/**
 * Handles the command line arguments passed to the main method, according to {@link BaseOptions}.
 * Loads the configuration and returns the list of arguments.
 * @param argv the command line arguments passed to the main method.
 * @return the arguments list./*from w w w. ja va2s .c  o  m*/
 * @see CommandLine
 * @see AppConfiguration
 */
public static List<String> handleArguments(String[] argv) {
    LOGGER.trace("Processing arguments: {}", Arrays.asList(argv));
    CommandLine cmd = getCommandLine(argv);

    /* OPTION: silent */
    if (cmd.hasOption("silent")) {
        LOGGER.trace("Detected option SILENT");
        activateSilent();
    }

    /* OPTION: trace */
    if (cmd.hasOption("trace")) {
        LOGGER.trace("Detected option TRACE");
        activateTrace();
    }

    /* OPTION: version */
    if (cmd.hasOption("version")) {
        LOGGER.trace("Detected option VERSION");
        printVersion();
        System.exit(0);
    }

    /* OPTION: help */
    if (cmd.hasOption("help")) {
        LOGGER.trace("Detected option HELP");
        printHelp();
        System.exit(0);
    }

    boolean configured = false;
    /* OPTION: config */
    if (cmd.hasOption("config")) {
        final String configPath = cmd.getOptionValue("config");
        LOGGER.trace("Detected option CONFIG with configPath={}", configPath);
        LOGGER.trace("Loading custom configuration {}", configPath);
        try {
            loadConfiguration(configPath);
            configured = true;
        } catch (IOException exc) {
            LOGGER.warn("Cannot load custom configuration");
        }
    }

    if (!configured) {
        final String configPath = AppConfigurationService.DEFAULT_CONFIG_FILENAME;
        LOGGER.trace("Loading local configuration {}", configPath);
        try {
            loadConfiguration(configPath);
            configured = true;
        } catch (IOException exc) {
            LOGGER.warn("Cannot load local configuration");
        }
    }

    if (!configured) {
        LOGGER.trace("Loading default configuration");
        AppConfigurationService.loadDefault();
    }

    LOGGER.trace("Configuration loaded: {}", AppConfigurationService.getConfigurations());

    return cmd.getArgList();
}

From source file:com.logicmonitor.ft.jxmtop.JMXTopMain.java

/**
 * @param args : arguments array/*from  w ww . j a v a  2s  .co  m*/
 * @return Run Parameter
 */
private static RunParameter ARGSAnalyser(String[] args) {

    Options options = new Options();
    options.addOption(new Option("h", "help", false, "show this help message"))
            .addOption(new Option("u", true, "User name for remote process"))
            .addOption(new Option("p", true, "Password for remote process"))
            .addOption(new Option("f", true, "Path to the configure file"))
            .addOption(new Option("i", true, "Interval between two scan tasks, unit is second"))
            .addOption(new Option("a", false, "Show alias names instead of jmx paths"));

    CommandLineParser parser = new BasicParser();
    RunParameter runParameter = new RunParameter();
    ArrayList<JMXInPath> inputtedPaths = new ArrayList<JMXInPath>();
    try {
        CommandLine cli = parser.parse(options, args);
        if (args.length == 0 || cli.hasOption('h')) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("jmxtop jmxURL [jmx path lists]", "To view statuses of jmx paths:", options,
                    "[Use 'Esc' or 'q' or 'Ctrl-c' to exit top console]\n[Use Key UP and Key DOWN to change pages]\n@Support by LogicMonitor",
                    true);
            exit(0);
        }

        runParameter.setValid(true);
        if (cli.hasOption('a')) {
            runParameter.setShowAliasTitle(true);
        }
        if (cli.hasOption('f')) {
            List<JMXInPath> paths_from_file = getPathsFromFile(cli.getOptionValue('f'));
            inputtedPaths.addAll(paths_from_file);
        }

        if (cli.hasOption('u')) {
            runParameter.setUsername(cli.getOptionValue('u'));
        }
        if (cli.hasOption('p')) {
            runParameter.setPassword(cli.getOptionValue('p'));
        }
        if (cli.hasOption('i')) {
            try {
                int interval = Integer.valueOf(cli.getOptionValue('i'));
                if (interval < 0)
                    System.err.println("The interval value is negative! Using default set!");
                else {
                    runParameter.setInterval(interval);
                }
            } catch (Exception e) {
                runParameter.setValid(false);
                runParameter.setValidInfo(
                        runParameter.getValidInfo() + "Argument after <-i> should be an integer\n");
            }
        }
        List<String> others = cli.getArgList();
        boolean jmxurl_found = false;
        for (String other : others) {
            if (other.toLowerCase().startsWith("service:jmx:")) {
                if (jmxurl_found) {
                    runParameter.setValid(false);
                    runParameter.setValidInfo(runParameter.getValidInfo() + "multiple jmxurl found\n");
                    return runParameter;
                } else {
                    jmxurl_found = true;
                    runParameter.setSurl(other.toLowerCase());
                }
            } else {
                inputtedPaths.add(new JMXInPath(other));
            }
        }
        if (!jmxurl_found) {
            runParameter.setValid(false);
            runParameter.setValidInfo(runParameter.getValidInfo()
                    + "No jmxurl found. The jmxurl should start with \"service:jmx:\" \n");
        }
    } catch (ParseException e) {
        e.printStackTrace();
        runParameter.setValid(false);
        runParameter.setValidInfo(runParameter.getValidInfo() + "Exception caught while parse arguments!\n");
    }

    if (inputtedPaths.isEmpty()) {
        runParameter.setValid(false);
        runParameter.setValidInfo(runParameter.getValidInfo() + "No jmx paths inputted");
    } else {
        runParameter.setPaths(inputtedPaths);
    }
    return runParameter;
}

From source file:DcmQR.java

private static CommandLine parse(String[] args) {
    Options opts = new Options();
    OptionBuilder.withArgName("aet[@host][:port]");
    OptionBuilder.hasArg();//from w ww.  j av a  2 s. c om
    OptionBuilder.withDescription("set AET, local address and listening port of local Application Entity");
    opts.addOption(OptionBuilder.create("L"));

    OptionBuilder.withArgName("username");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription(
            "enable User Identity Negotiation with specified username and " + " optional passcode");
    opts.addOption(OptionBuilder.create("username"));

    OptionBuilder.withArgName("passcode");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription(
            "optional passcode for User Identity Negotiation, " + "only effective with option -username");
    opts.addOption(OptionBuilder.create("passcode"));

    opts.addOption("uidnegrsp", false,
            "request positive User Identity Negotation response, " + "only effective with option -username");

    OptionBuilder.withArgName("NULL|3DES|AES");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("enable TLS connection without, 3DES or AES encryption");
    opts.addOption(OptionBuilder.create("tls"));

    opts.addOption("nossl2", false, "disable SSLv2Hello TLS handshake");
    opts.addOption("noclientauth", false, "disable client authentification for TLS");

    OptionBuilder.withArgName("file|url");
    OptionBuilder.hasArg();
    OptionBuilder
            .withDescription("file path or URL of P12 or JKS keystore, resource:tls/test_sys_1.p12 by default");
    opts.addOption(OptionBuilder.create("keystore"));

    OptionBuilder.withArgName("password");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("password for keystore file, 'secret' by default");
    opts.addOption(OptionBuilder.create("keystorepw"));

    OptionBuilder.withArgName("password");
    OptionBuilder.hasArg();
    OptionBuilder
            .withDescription("password for accessing the key in the keystore, keystore password by default");
    opts.addOption(OptionBuilder.create("keypw"));

    OptionBuilder.withArgName("file|url");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("file path or URL of JKS truststore, resource:tls/mesa_certs.jks by default");
    opts.addOption(OptionBuilder.create("truststore"));

    OptionBuilder.withArgName("password");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("password for truststore file, 'secret' by default");
    opts.addOption(OptionBuilder.create("truststorepw"));

    OptionBuilder.withArgName("aet");
    OptionBuilder.hasArg();
    OptionBuilder
            .withDescription("retrieve instances of matching entities by C-MOVE to specified destination.");
    opts.addOption(OptionBuilder.create("cmove"));

    opts.addOption("cget", false, "retrieve instances of matching entities by C-GET.");

    OptionBuilder.withArgName("cuid[:ts]");
    OptionBuilder.hasArgs();
    OptionBuilder.withDescription("negotiate support of specified Storage SOP Class and Transfer "
            + "Syntaxes. The Storage SOP\nClass may be specified by its UID "
            + "or by one\nof following key words:\n" + "CR  - Computed Radiography Image Storage\n"
            + "CT  - CT Image Storage\n" + "MR  - MRImageStorage\n" + "US  - Ultrasound Image Storage\n"
            + "NM  - Nuclear Medicine Image Storage\n" + "PET - PET Image Storage\n"
            + "SC  - Secondary Capture Image Storage\n" + "XA  - XRay Angiographic Image Storage\n"
            + "XRF - XRay Radiofluoroscopic Image Storage\n"
            + "DX  - Digital X-Ray Image Storage for Presentation\n"
            + "                            MG  - Digital Mammography X-Ray Image Storage\n"
            + "for Presentation\n" + "PR  - Grayscale Softcopy Presentation State Storage\n"
            + "                            KO  - Key Object Selection Document Storage\n"
            + "SR  - Basic Text Structured Report Document Storage\n"
            + "                            The Transfer Syntaxes may be specified by a comma\n"
            + "                            separated list of UIDs or by one of following key\n"
            + "                            words:\n"
            + "                            IVRLE - offer only Implicit VR Little Endian\n"
            + "                            Transfer Syntax\n"
            + "                            LE - offer Explicit and Implicit VR Little Endian\n"
            + "                            Transfer Syntax\n"
            + "                            BE - offer Explicit VR Big Endian Transfer Syntax\n"
            + "                            DEFL - offer Deflated Explicit VR Little\n"
            + "                            Endian Transfer Syntax\n"
            + "                            JPLL - offer JEPG Loss Less Transfer Syntaxes\n"
            + "                            JPLY - offer JEPG Lossy Transfer Syntaxes\n"
            + "                            MPEG2 - offer MPEG2 Transfer Syntax\n"
            + "                            NOPX - offer No Pixel Data Transfer Syntax\n"
            + "                            NOPXD - offer No Pixel Data Deflate Transfer Syntax\n"
            + "                            If only the Storage SOP Class is specified, all\n"
            + "                            Transfer Syntaxes listed above except No Pixel Data\n"
            + "                            and No Pixel Data Delflate Transfer Syntax are\n"
            + "                            offered.");
    opts.addOption(OptionBuilder.create("cstore"));

    OptionBuilder.withArgName("dir");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("store received objects into files in specified directory <dir>."
            + " Do not store received objects\nby default.");
    opts.addOption(OptionBuilder.create("cstoredest"));

    opts.addOption("ivrle", false, "offer only Implicit VR Little Endian Transfer Syntax.");

    OptionBuilder.withArgName("maxops");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription(
            "maximum number of outstanding C-MOVE-RQ " + "it may invoke asynchronously, 1 by default.");
    opts.addOption(OptionBuilder.create("async"));

    OptionBuilder.withArgName("maxops");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("maximum number of outstanding storage operations performed "
            + "asynchronously, unlimited by\n                            default.");
    opts.addOption(OptionBuilder.create("storeasync"));

    opts.addOption("noextneg", false, "disable extended negotiation.");
    opts.addOption("rel", false, "negotiate support of relational queries and retrieval.");
    opts.addOption("datetime", false, "negotiate support of combined date and time attribute range matching.");
    opts.addOption("fuzzy", false, "negotiate support of fuzzy semantic person name attribute matching.");

    opts.addOption("retall", false,
            "negotiate private FIND SOP Classes " + "to fetch all available attributes of matching entities.");
    opts.addOption("blocked", false,
            "negotiate private FIND SOP Classes "
                    + "to return attributes of several matching entities per FIND\n"
                    + "                            response.");
    opts.addOption("vmf", false,
            "negotiate private FIND SOP Classes to "
                    + "return attributes of legacy CT/MR images of one series as\n"
                    + "                           virtual multiframe object.");
    opts.addOption("pdv1", false, "send only one PDV in one P-Data-TF PDU, pack command and data "
            + "PDV in one P-DATA-TF PDU\n" + "                           by default.");
    opts.addOption("tcpdelay", false, "set TCP_NODELAY socket option to false, true by default");

    OptionBuilder.withArgName("ms");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("timeout in ms for TCP connect, no timeout by default");
    opts.addOption(OptionBuilder.create("connectTO"));

    OptionBuilder.withArgName("ms");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("delay in ms for Socket close after sending A-ABORT, 50ms by default");
    opts.addOption(OptionBuilder.create("soclosedelay"));

    OptionBuilder.withArgName("ms");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("period in ms to check for outstanding DIMSE-RSP, 10s by default");
    opts.addOption(OptionBuilder.create("reaper"));

    OptionBuilder.withArgName("ms");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("timeout in ms for receiving C-FIND-RSP, 60s by default");
    opts.addOption(OptionBuilder.create("cfindrspTO"));

    OptionBuilder.withArgName("ms");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("timeout in ms for receiving C-MOVE-RSP and C-GET RSP, 600s by default");
    opts.addOption(OptionBuilder.create("cmoverspTO"));

    OptionBuilder.withArgName("ms");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("timeout in ms for receiving C-GET-RSP and C-MOVE RSP, 600s by default");
    opts.addOption(OptionBuilder.create("cgetrspTO"));

    OptionBuilder.withArgName("ms");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("timeout in ms for receiving A-ASSOCIATE-AC, 5s by default");
    opts.addOption(OptionBuilder.create("acceptTO"));

    OptionBuilder.withArgName("ms");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("timeout in ms for receiving A-RELEASE-RP, 5s by default");
    opts.addOption(OptionBuilder.create("releaseTO"));

    OptionBuilder.withArgName("KB");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("maximal length in KB of received P-DATA-TF PDUs, 16KB by default");
    opts.addOption(OptionBuilder.create("rcvpdulen"));

    OptionBuilder.withArgName("KB");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("maximal length in KB of sent P-DATA-TF PDUs, 16KB by default");
    opts.addOption(OptionBuilder.create("sndpdulen"));

    OptionBuilder.withArgName("KB");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("set SO_RCVBUF socket option to specified value in KB");
    opts.addOption(OptionBuilder.create("sorcvbuf"));

    OptionBuilder.withArgName("KB");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("set SO_SNDBUF socket option to specified value in KB");
    opts.addOption(OptionBuilder.create("sosndbuf"));

    OptionBuilder.withArgName("KB");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("minimal buffer size to write received object to file, 1KB by default");
    opts.addOption(OptionBuilder.create("filebuf"));

    OptionGroup qrlevel = new OptionGroup();

    OptionBuilder.withDescription(
            "perform patient level query, multiple " + "exclusive with -S and -I, perform study level query\n"
                    + "                            by default.");
    OptionBuilder.withLongOpt("patient");
    opts.addOption(OptionBuilder.create("P"));

    OptionBuilder.withDescription(
            "perform series level query, multiple " + "exclusive with -P and -I, perform study level query\n"
                    + "                            by default.");
    OptionBuilder.withLongOpt("series");
    opts.addOption(OptionBuilder.create("S"));

    OptionBuilder.withDescription(
            "perform instance level query, multiple " + "exclusive with -P and -S, perform study level query\n"
                    + "                            by default.");
    OptionBuilder.withLongOpt("image");
    opts.addOption(OptionBuilder.create("I"));

    opts.addOptionGroup(qrlevel);

    OptionBuilder.withArgName("[seq/]attr=value");
    OptionBuilder.hasArgs();
    OptionBuilder.withValueSeparator('=');
    OptionBuilder.withDescription(
            "specify matching key. attr can be " + "specified by name or tag value (in hex), e.g. PatientName\n"
                    + "or 00100010. Attributes in nested Datasets can\n"
                    + "be specified by including the name/tag value of\n"
                    + "                            the sequence attribute, e.g. 00400275/00400009\n"
                    + "for Scheduled Procedure Step ID in the Request\n" + "Attributes Sequence");
    opts.addOption(OptionBuilder.create("q"));

    OptionBuilder.withArgName("attr");
    OptionBuilder.hasArgs();
    OptionBuilder.withDescription(
            "specify additional return key. attr can " + "be specified by name or tag value (in hex).");
    opts.addOption(OptionBuilder.create("r"));

    OptionBuilder.withArgName("num");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription(
            "cancel query after receive of specified " + "number of responses, no cancel by default");
    opts.addOption(OptionBuilder.create("C"));

    OptionBuilder.withArgName("aet");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("retrieve matching objects to specified " + "move destination.");
    opts.addOption(OptionBuilder.create("cmove"));

    opts.addOption("evalRetrieveAET", false, "Only Move studies not allready stored on destination AET");
    opts.addOption("lowprior", false, "LOW priority of the C-FIND/C-MOVE operation, MEDIUM by default");
    opts.addOption("highprior", false, "HIGH priority of the C-FIND/C-MOVE operation, MEDIUM by default");

    OptionBuilder.withArgName("num");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("repeat query (and retrieve) several times");
    opts.addOption(OptionBuilder.create("repeat"));

    OptionBuilder.withArgName("ms");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("delay in ms between repeated query (and retrieve), no delay by default");
    opts.addOption(OptionBuilder.create("repeatdelay"));

    opts.addOption("reuseassoc", false, "Reuse association for repeated query (and retrieve)");
    opts.addOption("closeassoc", false, "Close association between repeated query (and retrieve)");

    opts.addOption("h", "help", false, "print this message");
    opts.addOption("V", "version", false, "print the version information and exit");
    CommandLine cl = null;
    try {
        cl = new GnuParser().parse(opts, args);
    } catch (ParseException e) {
        exit("dcmqr: " + e.getMessage());
        throw new RuntimeException("unreachable");
    }
    if (cl.hasOption('V')) {
        Package p = DcmQR.class.getPackage();
        System.out.println("dcmqr v" + p.getImplementationVersion());
        System.exit(0);
    }
    if (cl.hasOption('h') || cl.getArgList().size() != 1) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(USAGE, DESCRIPTION, opts, EXAMPLE);
        System.exit(0);
    }

    return cl;
}

From source file:mod.org.dcm4che2.tool.DcmQR.java

private static CommandLine parse(String[] args) {
    Options opts = new Options();

    OptionBuilder.withArgName("name");
    OptionBuilder.hasArg();//w ww.j av a  2 s  .  c om
    OptionBuilder.withDescription("set device name, use DCMQR by default");
    opts.addOption(OptionBuilder.create("device"));

    OptionBuilder.withArgName("aet[@host][:port]");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("set AET, local address and listening port of local"
            + "Application Entity, use device name and pick up any valid "
            + "local address to bind the socket by default");
    opts.addOption(OptionBuilder.create("L"));

    OptionBuilder.withArgName("username");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription(
            "enable User Identity Negotiation with specified username and " + " optional passcode");
    opts.addOption(OptionBuilder.create("username"));

    OptionBuilder.withArgName("passcode");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription(
            "optional passcode for User Identity Negotiation, " + "only effective with option -username");
    opts.addOption(OptionBuilder.create("passcode"));

    opts.addOption("uidnegrsp", false,
            "request positive User Identity Negotation response, " + "only effective with option -username");

    OptionBuilder.withArgName("NULL|3DES|AES");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("enable TLS connection without, 3DES or AES encryption");
    opts.addOption(OptionBuilder.create("tls"));

    OptionGroup tlsProtocol = new OptionGroup();
    tlsProtocol.addOption(new Option("tls1", "disable the use of SSLv3 and SSLv2 for TLS connections"));
    tlsProtocol.addOption(new Option("ssl3", "disable the use of TLSv1 and SSLv2 for TLS connections"));
    tlsProtocol.addOption(new Option("no_tls1", "disable the use of TLSv1 for TLS connections"));
    tlsProtocol.addOption(new Option("no_ssl3", "disable the use of SSLv3 for TLS connections"));
    tlsProtocol.addOption(new Option("no_ssl2", "disable the use of SSLv2 for TLS connections"));
    opts.addOptionGroup(tlsProtocol);

    opts.addOption("noclientauth", false, "disable client authentification for TLS");

    OptionBuilder.withArgName("file|url");
    OptionBuilder.hasArg();
    OptionBuilder
            .withDescription("file path or URL of P12 or JKS keystore, resource:tls/test_sys_1.p12 by default");
    opts.addOption(OptionBuilder.create("keystore"));

    OptionBuilder.withArgName("password");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("password for keystore file, 'secret' by default");
    opts.addOption(OptionBuilder.create("keystorepw"));

    OptionBuilder.withArgName("password");
    OptionBuilder.hasArg();
    OptionBuilder
            .withDescription("password for accessing the key in the keystore, keystore password by default");
    opts.addOption(OptionBuilder.create("keypw"));

    OptionBuilder.withArgName("file|url");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("file path or URL of JKS truststore, resource:tls/mesa_certs.jks by default");
    opts.addOption(OptionBuilder.create("truststore"));

    OptionBuilder.withArgName("password");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("password for truststore file, 'secret' by default");
    opts.addOption(OptionBuilder.create("truststorepw"));

    OptionBuilder.withArgName("aet");
    OptionBuilder.hasArg();
    OptionBuilder
            .withDescription("retrieve instances of matching entities by C-MOVE to specified destination.");
    opts.addOption(OptionBuilder.create("cmove"));

    opts.addOption("nocfind", false,
            "retrieve instances without previous query - unique keys must be specified by -q options");

    opts.addOption("cget", false, "retrieve instances of matching entities by C-GET.");

    OptionBuilder.withArgName("cuid[:ts]");
    OptionBuilder.hasArgs();
    OptionBuilder.withDescription("negotiate support of specified Storage SOP Class and Transfer "
            + "Syntaxes. The Storage SOP Class may be specified by its UID "
            + "or by one of following key words:\n" + "CR  - Computed Radiography Image Storage\n"
            + "CT  - CT Image Storage\n" + "MR  - MRImageStorage\n" + "US  - Ultrasound Image Storage\n"
            + "NM  - Nuclear Medicine Image Storage\n" + "PET - PET Image Storage\n"
            + "SC  - Secondary Capture Image Storage\n" + "XA  - XRay Angiographic Image Storage\n"
            + "XRF - XRay Radiofluoroscopic Image Storage\n"
            + "DX  - Digital X-Ray Image Storage for Presentation\n"
            + "MG  - Digital Mammography X-Ray Image Storage for Presentation\n"
            + "PR  - Grayscale Softcopy Presentation State Storage\n"
            + "KO  - Key Object Selection Document Storage\n"
            + "SR  - Basic Text Structured Report Document Storage\n"
            + "The Transfer Syntaxes may be specified by a comma "
            + "separated list of UIDs or by one of following key " + "words:\n"
            + "IVRLE - offer only Implicit VR Little Endian " + "Transfer Syntax\n"
            + "LE - offer Explicit and Implicit VR Little Endian " + "Transfer Syntax\n"
            + "BE - offer Explicit VR Big Endian Transfer Syntax\n"
            + "DEFL - offer Deflated Explicit VR Little " + "Endian Transfer Syntax\n"
            + "JPLL - offer JEPG Loss Less Transfer Syntaxes\n" + "JPLY - offer JEPG Lossy Transfer Syntaxes\n"
            + "MPEG2 - offer MPEG2 Transfer Syntax\n" + "NOPX - offer No Pixel Data Transfer Syntax\n"
            + "NOPXD - offer No Pixel Data Deflate Transfer Syntax\n"
            + "If only the Storage SOP Class is specified, all "
            + "Transfer Syntaxes listed above except No Pixel Data "
            + "and No Pixel Data Delflate Transfer Syntax are " + "offered.");
    opts.addOption(OptionBuilder.create("cstore"));

    OptionBuilder.withArgName("dir");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("store received objects into files in specified directory <dir>."
            + " Do not store received objects by default.");
    opts.addOption(OptionBuilder.create("cstoredest"));

    opts.addOption("ivrle", false, "offer only Implicit VR Little Endian Transfer Syntax.");

    OptionBuilder.withArgName("maxops");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription(
            "maximum number of outstanding C-MOVE-RQ " + "it may invoke asynchronously, 1 by default.");
    opts.addOption(OptionBuilder.create("async"));

    OptionBuilder.withArgName("maxops");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("maximum number of outstanding storage operations performed "
            + "asynchronously, unlimited by default.");
    opts.addOption(OptionBuilder.create("storeasync"));

    opts.addOption("noextneg", false, "disable extended negotiation.");
    opts.addOption("rel", false, "negotiate support of relational queries and retrieval.");
    opts.addOption("datetime", false, "negotiate support of combined date and time attribute range matching.");
    opts.addOption("fuzzy", false, "negotiate support of fuzzy semantic person name attribute matching.");

    opts.addOption("retall", false,
            "negotiate private FIND SOP Classes " + "to fetch all available attributes of matching entities.");
    opts.addOption("blocked", false, "negotiate private FIND SOP Classes "
            + "to return attributes of several matching entities per FIND " + "response.");
    opts.addOption("vmf", false, "negotiate private FIND SOP Classes to "
            + "return attributes of legacy CT/MR images of one series as " + "virtual multiframe object.");
    opts.addOption("pdv1", false, "send only one PDV in one P-Data-TF PDU, pack command and data "
            + "PDV in one P-DATA-TF PDU by default.");
    opts.addOption("tcpdelay", false, "set TCP_NODELAY socket option to false, true by default");

    OptionBuilder.withArgName("ms");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("timeout in ms for TCP connect, no timeout by default");
    opts.addOption(OptionBuilder.create("connectTO"));

    OptionBuilder.withArgName("ms");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("delay in ms for Socket close after sending A-ABORT, 50ms by default");
    opts.addOption(OptionBuilder.create("soclosedelay"));

    OptionBuilder.withArgName("ms");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("period in ms to check for outstanding DIMSE-RSP, 10s by default");
    opts.addOption(OptionBuilder.create("reaper"));

    OptionBuilder.withArgName("ms");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("timeout in ms for receiving C-FIND-RSP, 60s by default");
    opts.addOption(OptionBuilder.create("cfindrspTO"));

    OptionBuilder.withArgName("ms");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("timeout in ms for receiving C-MOVE-RSP and C-GET RSP, 600s by default");
    opts.addOption(OptionBuilder.create("cmoverspTO"));

    OptionBuilder.withArgName("ms");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("timeout in ms for receiving C-GET-RSP and C-MOVE RSP, 600s by default");
    opts.addOption(OptionBuilder.create("cgetrspTO"));

    OptionBuilder.withArgName("ms");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("timeout in ms for receiving A-ASSOCIATE-AC, 5s by default");
    opts.addOption(OptionBuilder.create("acceptTO"));

    OptionBuilder.withArgName("ms");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("timeout in ms for receiving A-RELEASE-RP, 5s by default");
    opts.addOption(OptionBuilder.create("releaseTO"));

    OptionBuilder.withArgName("KB");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("maximal length in KB of received P-DATA-TF PDUs, 16KB by default");
    opts.addOption(OptionBuilder.create("rcvpdulen"));

    OptionBuilder.withArgName("KB");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("maximal length in KB of sent P-DATA-TF PDUs, 16KB by default");
    opts.addOption(OptionBuilder.create("sndpdulen"));

    OptionBuilder.withArgName("KB");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("set SO_RCVBUF socket option to specified value in KB");
    opts.addOption(OptionBuilder.create("sorcvbuf"));

    OptionBuilder.withArgName("KB");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("set SO_SNDBUF socket option to specified value in KB");
    opts.addOption(OptionBuilder.create("sosndbuf"));

    OptionBuilder.withArgName("KB");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("minimal buffer size to write received object to file, 1KB by default");
    opts.addOption(OptionBuilder.create("filebuf"));

    OptionGroup qrlevel = new OptionGroup();

    OptionBuilder.withDescription("perform patient level query, multiple "
            + "exclusive with -S and -I, perform study level query " + "by default.");
    OptionBuilder.withLongOpt("patient");
    qrlevel.addOption(OptionBuilder.create("P"));

    OptionBuilder.withDescription("perform series level query, multiple "
            + "exclusive with -P and -I, perform study level query " + "by default.");
    OptionBuilder.withLongOpt("series");
    qrlevel.addOption(OptionBuilder.create("S"));

    OptionBuilder.withDescription("perform instance level query, multiple "
            + "exclusive with -P and -S, perform study level query " + "by default.");
    OptionBuilder.withLongOpt("image");
    qrlevel.addOption(OptionBuilder.create("I"));

    OptionBuilder.withArgName("cuid");
    OptionBuilder.hasArgs();
    OptionBuilder.withDescription("negotiate addition private C-FIND SOP " + "class with specified UID");
    opts.addOption(OptionBuilder.create("cfind"));

    opts.addOptionGroup(qrlevel);

    OptionBuilder.withArgName("[seq/]attr=value");
    OptionBuilder.hasArgs();
    OptionBuilder.withValueSeparator('=');
    OptionBuilder.withDescription(
            "specify matching key. attr can be " + "specified by name or tag value (in hex), e.g. PatientName "
                    + "or 00100010. Attributes in nested Datasets can "
                    + "be specified by including the name/tag value of "
                    + "the sequence attribute, e.g. 00400275/00400009 "
                    + "for Scheduled Procedure Step ID in the Request " + "Attributes Sequence");
    opts.addOption(OptionBuilder.create("q"));

    OptionBuilder.withArgName("attr");
    OptionBuilder.hasArgs();
    OptionBuilder.withDescription(
            "specify additional return key. attr can " + "be specified by name or tag value (in hex).");
    opts.addOption(OptionBuilder.create("r"));

    opts.addOption("nodefret", false, "only inlcude return keys specified by -r into the request.");

    OptionBuilder.withArgName("num");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription(
            "cancel query after receive of specified " + "number of responses, no cancel by default");
    opts.addOption(OptionBuilder.create("C"));

    OptionBuilder.withArgName("aet");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("retrieve matching objects to specified " + "move destination.");
    opts.addOption(OptionBuilder.create("cmove"));

    opts.addOption("evalRetrieveAET", false, "Only Move studies not allready stored on destination AET");
    opts.addOption("lowprior", false, "LOW priority of the C-FIND/C-MOVE operation, MEDIUM by default");
    opts.addOption("highprior", false, "HIGH priority of the C-FIND/C-MOVE operation, MEDIUM by default");

    OptionBuilder.withArgName("num");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("repeat query (and retrieve) several times");
    opts.addOption(OptionBuilder.create("repeat"));

    OptionBuilder.withArgName("ms");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("delay in ms between repeated query (and retrieve), no delay by default");
    opts.addOption(OptionBuilder.create("repeatdelay"));

    opts.addOption("reuseassoc", false, "Reuse association for repeated query (and retrieve)");
    opts.addOption("closeassoc", false, "Close association between repeated query (and retrieve)");

    opts.addOption("h", "help", false, "print this message");
    opts.addOption("V", "version", false, "print the version information and exit");
    CommandLine cl = null;
    try {
        cl = new GnuParser().parse(opts, args);
    } catch (ParseException e) {
        exit("dcmqr: " + e.getMessage());
        throw new RuntimeException("unreachable");
    }
    if (cl.hasOption('V')) {
        Package p = DcmQR.class.getPackage();
        System.out.println("dcmqr v" + p.getImplementationVersion());
        System.exit(0);
    }
    if (cl.hasOption('h') || cl.getArgList().size() != 1) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(USAGE, DESCRIPTION, opts, EXAMPLE);
        System.exit(0);
    }

    return cl;
}

From source file:com.xruby.CommandLineOptions.java

@SuppressWarnings("unchecked")
public CommandLineOptions(String[] args) {
    if (args.length == 0) {
        return;/*  w w w .jav  a 2s  . co m*/
    }

    args = preProcessSingleQuote(args);
    args = preProcess_pe_i(args);

    CommandLineParser parser = new PosixParser();
    Options options = new Options();
    options.addOption("h", false, "display help");
    options.addOption("c", false, "compiler only");
    options.addOption("e", true, "eval one line");
    options.addOption("v", false, "print version number, then turn on verbose mode");
    options.addOption("s", false, "enable some switch parsing for switches after script name");
    options.addOption("x", false, "strip off text before #!ruby line");
    options.addOption("g", false, "enable debug");
    options.addOption("n", true, "provide class prefix name");

    CommandLine line;
    try {
        line = parser.parse(options, args, true);
    } catch (ParseException e) {
        throw new Error(e.toString());
    }

    if (line.hasOption("c")) {
        compileOnly_ = true;

        if (line.hasOption("g")) {
            enableDebug = true;
        }
        if (line.hasOption("v")) {
            verbose_ = true;
        }
        if (line.hasOption("n")) {
            String str = line.getOptionValue("n");
            com.xruby.compiler.codegen.NameFactory.name_classprefix_ = str;
        }

    } else if (line.hasOption("h")) {
        help_ = true;
    } else if (line.hasOption("v")) {
        verbose_ = true;
    } else if (line.hasOption("e")) {
        eval_one_line_ = true;
        eval_script_ = line.getOptionValue("e");
    } else if (line.hasOption("s")) {
        switch_ = true;
    } else if (line.hasOption("x")) {
        strip_ = true;
    }

    if (line.getArgList().size() > 0) {
        file_ = (String) line.getArgList().remove(0);
        args_.addAll(line.getArgList());
        if (switch_) {
            moveArgsToVars();
        }
    }
}