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

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

Introduction

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

Prototype

public String[] getOptionValues(char opt) 

Source Link

Document

Retrieves the array of values, if any, of an option.

Usage

From source file:gov.nih.nci.grididloader.BigIdCreator.java

/**
  * Main program.//  ww w.j  av  a  2 s .c om
  * Two mutually exclusive command line options are possible:
  * -I include the following entities
  * -E exclude the following entities
  * The entities are passed as a space delimited list like:
  * -I Taxon Cytoband
 * @param args
 */
public static void main(String[] args) throws Exception {

    String[] classFilter = null;
    boolean isInclude = true;

    Options options = new Options();
    options.addOption(OptionBuilder.withLongOpt("include").withDescription("classes to include")
            .hasOptionalArgs().create("I"));

    options.addOption(OptionBuilder.withLongOpt("exclude").withDescription("classes to exclude")
            .hasOptionalArgs().create("E"));

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);
    String[] include = cmd.getOptionValues("I");
    String[] exclude = cmd.getOptionValues("E");

    if (include != null) {
        if (exclude != null)
            argError();
        isInclude = true;
        classFilter = include;
    } else if (exclude != null) {
        if (include != null)
            argError();
        isInclude = false;
        classFilter = exclude;
    }

    long start = System.currentTimeMillis();
    BigIdCreator loader = new BigIdCreator();
    loader.createAndUpdate(classFilter, isInclude);
    //loader.printSQL();
    long stop = System.currentTimeMillis();
    System.err.println("All updates took " + (float) (stop - start) / 60000 + " min.");
}

From source file:it.geosolutions.unredd.apputil.AreaBuilder.java

public static void main(String[] args) {
    Option help = OptionBuilder.withLongOpt("help").withDescription("print help").create('?');

    Options helpOptions = new Options().addOption(help);

    Options options = new Options().addOption(help)
            .addOption(OptionBuilder.withLongOpt("extents").withArgName("n/e/s/w")
                    .withDescription("extents in the format n/e/s/w").hasArgs(4).withValueSeparator('/')
                    .isRequired().withType(Double.class).create(OPT_EXTENTS))
            .addOption(OptionBuilder.withLongOpt("size").withArgName("width,height")
                    .withDescription("size of output image in pixel in the format width,height").hasArgs(2)
                    .withValueSeparator(',').isRequired().withType(Integer.class).create(OPT_SIZE))
            .addOption(OptionBuilder.withLongOpt("outfile").withArgName("file")
                    .withDescription("the output tiff file").hasArg().isRequired().withType(String.class)
                    .create(OPT_OUTFILE))
            .addOption(OptionBuilder.withLongOpt("mem").withArgName("megabytes")
                    .withDescription("the max memory available for the operation").hasArg().create(OPT_MEM))
            .addOption(OptionBuilder.withLongOpt("threads").withArgName("numThreads")
                    .withDescription("number of threads JAI will use").hasArg().create(OPT_THREADS));

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

        //=== Create parser
        CommandLineParser parser = new PosixParser();
        CommandLine cmd = parser.parse(options, args);

        //=== Parse input params
        String sFile = cmd.getOptionValue(OPT_OUTFILE);

        String[] sSizeArr = cmd.getOptionValues(OPT_SIZE);
        if (sSizeArr.length != 2) {
            LOGGER.error("size requires 2 args");
            return;
        }
        String[] sExtArr = cmd.getOptionValues(OPT_EXTENTS);
        if (sExtArr.length != 4) {
            LOGGER.error("extents require 4 args");
            return;
        }

        File file = new File(sFile);
        LOGGER.info("Output file " + file);

        int w = Integer.parseInt(sSizeArr[0]);
        int h = Integer.parseInt(sSizeArr[1]);
        LOGGER.info("Image size " + w + " x " + h);

        double boxn = Double.parseDouble(sExtArr[0]);
        double boxe = Double.parseDouble(sExtArr[1]);
        double boxs = Double.parseDouble(sExtArr[2]);
        double boxw = Double.parseDouble(sExtArr[3]);
        LOGGER.info("Image bbox is n:" + boxn + "e:" + boxe + " s:" + boxs + " w:" + boxw);

        //=== Parse and set tilecache memory
        Long mega = 512l;
        if (cmd.hasOption(OPT_MEM)) {
            mega = Long.parseLong(cmd.getOptionValue(OPT_MEM));
            LOGGER.info("JAI tilecache memory set to " + mega + "MB");
        } else {
            LOGGER.info("JAI tilecache memory defaulting to " + mega + "MB");
        }

        JAI.getDefaultInstance().getTileCache().setMemoryCapacity(mega * MEGA);

        //=== Parse and set JAI parallelism level
        int threads = 4;
        if (cmd.hasOption(OPT_THREADS)) {
            threads = Integer.parseInt(cmd.getOptionValue(OPT_THREADS));
            LOGGER.info("JAI tile scheduler parallelism set to " + threads);
        } else {
            LOGGER.info("JAI tile scheduler parallelism defaulting to " + threads);
        }

        TileScheduler ts = JAI.getDefaultInstance().getTileScheduler();
        ts.setParallelism(threads);
        ts.setPrefetchParallelism(threads);

        //=== Create grid and save

        System.setProperty("org.geotools.referencing.forceXY", "true");
        GridCoverage2D grid = createAreaGrid(w, h, boxw, boxe, boxs, boxn);
        saveAreaGrid(grid, file);

    } catch (ParseException ex) {

        CommandLine cmd0 = null;
        try { // find out if an help was requested (it's missing mandatory params)
            CommandLineParser helpParser = new PosixParser();
            cmd0 = helpParser.parse(helpOptions, args);
        } catch (ParseException ex1) {
            LOGGER.error("Unexpected error: " + ex1);
        }

        if (cmd0 == null || !cmd0.hasOption("help")) {
            LOGGER.error("Parse error: " + ex);
        }

        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("createAreaLayer", options);
    } catch (Exception e) {
        LOGGER.error("Unexpected exception", e);
    }
}

From source file:fr.tpt.s3.mcdag.scheduling.Main.java

public static void main(String[] args) throws IOException, InterruptedException {

    /* Command line options */
    Options options = new Options();

    Option input = new Option("i", "input", true, "MC-DAG XML Models");
    input.setRequired(true);/*from  w w  w.j  a  v a  2 s  . co m*/
    input.setArgs(Option.UNLIMITED_VALUES); // Sets maximum number of threads to be launched
    options.addOption(input);

    Option outSched = new Option("os", "out-scheduler", false, "Write the scheduling tables into a file.");
    outSched.setRequired(false);
    options.addOption(outSched);

    Option outPrism = new Option("op", "out-prism", false, "Write PRISM model into a file.");
    outPrism.setRequired(false);
    options.addOption(outPrism);

    Option jobs = new Option("j", "jobs", true, "Number of threads to be launched.");
    jobs.setRequired(false);
    options.addOption(jobs);

    Option debugOpt = new Option("d", "debug", false, "Enabling debug.");
    debugOpt.setRequired(false);
    options.addOption(debugOpt);

    Option preemptOpt = new Option("p", "preempt", false, "Count for preemptions.");
    preemptOpt.setRequired(false);
    options.addOption(preemptOpt);

    CommandLineParser parser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine cmd;

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        formatter.printHelp("MC-DAG framework", options);

        System.exit(1);
        return;
    }

    String inputFilePath[] = cmd.getOptionValues("input");
    boolean bOutSched = cmd.hasOption("out-scheduler");
    boolean bOutPrism = cmd.hasOption("out-prism");
    boolean debug = cmd.hasOption("debug");
    boolean preempt = cmd.hasOption("preempt");
    boolean levels = cmd.hasOption("n-levels");
    int nbFiles = inputFilePath.length;

    int nbJobs = 1;
    if (cmd.hasOption("jobs"))
        nbJobs = Integer.parseInt(cmd.getOptionValue("jobs"));

    if (debug)
        System.out.println("[DEBUG] Launching " + inputFilePath.length + " thread(s).");

    int i_files = 0;
    ExecutorService executor = Executors.newFixedThreadPool(nbJobs);

    /* Launch threads to solve allocation */
    while (i_files != nbFiles) {
        SchedulingThread ft = new SchedulingThread(inputFilePath[i_files], bOutSched, bOutPrism, debug,
                preempt);

        ft.setLevels(levels);
        executor.execute(ft);
        i_files++;
    }

    executor.shutdown();
    executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
    System.out.println("[FRAMEWORK Main] DONE");
}

From source file:cross.io.PropertyFileGenerator.java

/**
 *
 * @param args/*  w  w w. ja  v a  2s  .  c o m*/
 */
public static void main(String[] args) {
    Options options = new Options();
    options.addOption("f", true, "base directory for output of files");
    Option provOptions = new Option("p", true,
            "Comma separated list of provider classes to create Properties for");
    provOptions.setRequired(true);
    provOptions.setValueSeparator(',');
    options.addOption(provOptions);
    CommandLineParser parser = new PosixParser();
    HelpFormatter hf = new HelpFormatter();
    try {
        File basedir = null;
        List<String> providers = Collections.emptyList();
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption("f")) {
            basedir = new File(cmd.getOptionValue("f"));
        } else {
            hf.printHelp("java -cp maltcms.jar " + PropertyFileGenerator.class, options);
        }
        if (cmd.hasOption("p")) {
            String[] str = cmd.getOptionValues("p");
            providers = Arrays.asList(str);
        } else {
            hf.printHelp("java -cp maltcms.jar " + PropertyFileGenerator.class, options);
        }
        for (String provider : providers) {
            createProperties(provider, basedir);
        }
    } catch (ParseException ex) {
        Logger.getLogger(PropertyFileGenerator.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.gordcorp.jira2db.App.java

public static void main(String[] args) throws Exception {
    File log4jFile = new File("log4j.xml");
    if (log4jFile.exists()) {
        DOMConfigurator.configure("log4j.xml");
    }//from w  w  w  .ja v a 2  s.  co m

    Option help = new Option("h", "help", false, "print this message");

    @SuppressWarnings("static-access")
    Option project = OptionBuilder.withLongOpt("project").withDescription("Only sync Jira project PROJECT")
            .hasArg().withArgName("PROJECT").create();

    @SuppressWarnings("static-access")
    Option property = OptionBuilder.withArgName("property=value").hasArgs(2).withValueSeparator()
            .withDescription("use value for given property").create("D");

    @SuppressWarnings("static-access")
    Option testJira = OptionBuilder.withLongOpt("test-jira")
            .withDescription("Test the connection to Jira and print the results").create();

    @SuppressWarnings("static-access")
    Option forever = OptionBuilder.withLongOpt("forever")
            .withDescription("Will continue polling Jira and syncing forever").create();

    Options options = new Options();
    options.addOption(help);
    options.addOption(project);
    options.addOption(property);
    options.addOption(testJira);
    options.addOption(forever);

    CommandLineParser parser = new GnuParser();
    try {

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

        if (line.hasOption(help.getOpt())) {
            printHelp(options);
            return;
        }

        // Overwrite the properties file with command line arguments
        if (line.hasOption("D")) {
            String[] values = line.getOptionValues("D");
            for (int i = 0; i < values.length; i = i + 2) {
                String key = values[i];
                // If user does not provide a value for this property, use
                // an empty string
                String value = "";
                if (i + 1 < values.length) {
                    value = values[i + 1];
                }

                log.info("Setting key=" + key + " value=" + value);
                PropertiesWrapper.set(key, value);
            }

        }

        if (line.hasOption("test-jira")) {
            testJira();
        } else {
            JiraSynchroniser jira = new JiraSynchroniser();

            if (line.hasOption("project")) {

                jira.setProjects(Arrays.asList(new String[] { line.getOptionValue("project") }));
            }

            if (line.hasOption("forever")) {
                jira.syncForever();
            } else {
                jira.syncAll();
            }
        }
    } catch (ParseException exp) {

        log.error("Parsing failed: " + exp.getMessage());
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
}

From source file:de.jackwhite20.japs.server.Main.java

public static void main(String[] args) throws Exception {

    Config config = null;/* w  ww.ja v  a 2 s . c om*/

    if (args.length > 0) {
        Options options = new Options();
        options.addOption("h", true, "Address to bind to");
        options.addOption("p", true, "Port to bind to");
        options.addOption("b", true, "The backlog");
        options.addOption("t", true, "Worker thread count");
        options.addOption("d", false, "If debug is enabled or not");
        options.addOption("c", true, "Add server as a cluster");
        options.addOption("ci", true, "Sets the cache check interval");
        options.addOption("si", true, "Sets the snapshot interval");

        CommandLineParser commandLineParser = new BasicParser();
        CommandLine commandLine = commandLineParser.parse(options, args);

        if (commandLine.hasOption("h") && commandLine.hasOption("p") && commandLine.hasOption("b")
                && commandLine.hasOption("t")) {

            List<ClusterServer> clusterServers = new ArrayList<>();

            if (commandLine.hasOption("c")) {
                for (String c : commandLine.getOptionValues("c")) {
                    String[] splitted = c.split(":");
                    clusterServers.add(new ClusterServer(splitted[0], Integer.parseInt(splitted[1])));
                }
            }

            config = new Config(commandLine.getOptionValue("h"),
                    Integer.parseInt(commandLine.getOptionValue("p")),
                    Integer.parseInt(commandLine.getOptionValue("b")), commandLine.hasOption("d"),
                    Integer.parseInt(commandLine.getOptionValue("t")), clusterServers,
                    (commandLine.hasOption("ci")) ? Integer.parseInt(commandLine.getOptionValue("ci")) : 300,
                    (commandLine.hasOption("si")) ? Integer.parseInt(commandLine.getOptionValue("si")) : -1);
        } else {
            System.out.println(
                    "Usage: java -jar japs-server.jar -h <Host> -p <Port> -b <Backlog> -t <Threads> [-c IP:Port IP:Port] [-d]");
            System.out.println(
                    "Example (with debugging enabled): java -jar japs-server.jar -h localhost -p 1337 -b 100 -t 4 -d");
            System.out.println(
                    "Example (with debugging enabled and cluster setup): java -jar japs-server.jar -h localhost -p 1337 -b 100 -t 4 -c localhost:1338 -d");
            System.exit(-1);
        }
    } else {
        File configFile = new File("config.json");
        if (!configFile.exists()) {
            try {
                Files.copy(JaPS.class.getClassLoader().getResourceAsStream("config.json"), configFile.toPath(),
                        StandardCopyOption.REPLACE_EXISTING);
            } catch (IOException e) {
                System.err.println("Unable to load default config!");
                System.exit(-1);
            }
        }

        try {
            config = new Gson().fromJson(
                    Files.lines(configFile.toPath()).map(String::toString).collect(Collectors.joining(" ")),
                    Config.class);
        } catch (IOException e) {
            System.err.println("Unable to load 'config.json' in current directory!");
            System.exit(-1);
        }
    }

    if (config == null) {
        System.err.println("Failed to create a Config!");
        System.err.println("Please check the program parameters or the 'config.json' file!");
    } else {
        System.err.println("Using Config: " + config);

        JaPS jaPS = new JaPS(config);
        jaPS.init();
        jaPS.start();
        jaPS.stop();
    }
}

From source file:com.zimbra.cs.mailbox.calendar.FixCalendarTZUtil.java

public static void main(String[] args) {
    CliUtil.toolSetup();// w  ww. j a va2  s .co  m
    FixCalendarTZUtil util = null;
    try {
        util = new FixCalendarTZUtil();
    } catch (ServiceException e) {
        System.err.println(e.getMessage());
        System.exit(1);
    }
    try {
        CommandLine cl = util.getCommandLine(args);
        if (cl == null)
            return;
        if (!cl.hasOption(O_RULEFILE))
            throw new ParseException("Missing required option --" + O_RULEFILE);
        String after = null;
        if (cl.hasOption(O_AFTER))
            after = cl.getOptionValue(O_AFTER);

        util.doit(getZAuthToken(cl), cl.getOptionValue(O_RULEFILE), cl.getOptionValues(O_ACCOUNT), after,
                cl.hasOption(O_SYNC));
        System.exit(0);
    } catch (ParseException e) {
        util.usage(e);
    } catch (Exception e) {
        System.err.println("Error occurred: " + e.getMessage());
        util.usage(null);
    }
    System.exit(1);
}

From source file:com.etsy.arbiter.Arbiter.java

public static void main(String[] args) throws ParseException, ConfigurationException, IOException,
        ParserConfigurationException, TransformerException {
    Options options = getOptions();/*from w ww . j  a  v a2s  .co m*/

    CommandLineParser cmd = new GnuParser();
    CommandLine parsed = cmd.parse(options, args);

    if (parsed.hasOption("h")) {
        printUsage(options);
    }

    if (!parsed.hasOption("i")) {
        throw new ParseException("Missing required argument: i");
    }

    if (!parsed.hasOption("o")) {
        throw new ParseException("Missing required argument: o");
    }

    String[] configFiles = parsed.getOptionValues("c");
    String[] lowPrecedenceConfigFiles = parsed.getOptionValues("l");

    String[] inputFiles = parsed.getOptionValues("i");
    String outputDir = parsed.getOptionValue("o");

    List<Config> parsedConfigFiles = readConfigFiles(configFiles, false);
    parsedConfigFiles.addAll(readConfigFiles(lowPrecedenceConfigFiles, true));
    Config merged = ConfigurationMerger.mergeConfiguration(parsedConfigFiles);

    List<Workflow> workflows = readWorkflowFiles(inputFiles);

    boolean generateGraphviz = parsed.hasOption("g");
    String graphvizFormat = parsed.getOptionValue("g", "svg");

    OozieWorkflowGenerator generator = new OozieWorkflowGenerator(merged);
    generator.generateOozieWorkflows(outputDir, workflows, generateGraphviz, graphvizFormat);
}

From source file:net.bobah.mail.Dupes.java

public static void main(String[] args) throws Exception {
    installDefaultUncaughtExceptionHandler(log);

    final CommandLineParser parser = new PosixParser();
    final Options options = new Options()
            .addOption("j", "threads", true, "number of parallel threads to use for analyzing")
            .addOption("hash", true,
                    "hash function to use, possible values: " + Arrays.toString(Hashes.values()))
            .addOption("dir", true, "add directory to search");
    final CommandLine cmdline = parser.parse(options, args);

    final int threads = Integer.valueOf(
            cmdline.getOptionValue("threads", String.valueOf(Runtime.getRuntime().availableProcessors())));
    final HashFunction hash = Hashes.valueOf(cmdline.getOptionValue("hash", "adler32")).hashfunc;
    final File[] dirs = Collections2
            .transform(Arrays.asList(cmdline.getOptionValues("dir")), new Function<String, File>() {
                @Override//  ww  w  .j a v a2 s  .  co m
                public File apply(String from) {
                    return new File(from);
                }
            }).toArray(new File[] {});

    log.info("hash: {}, threads: {}, dirs: {} in total", hash, threads, dirs.length);
    try {
        new Dupes(threads, hash, dirs).run();
    } finally {
        Utils.shutdownLogger();
    }
}

From source file:ed.util.LicenseHeaderCheck.java

public static void main(String args[]) throws Exception {

    Options o = new Options();
    o.addOption("r", false, "recursive");
    o.addOption("skip", true, "substrings not to match");

    CommandLine cl = (new BasicParser()).parse(o, args);

    if (cl.getArgList().size() < 2) {
        System.err.println("usage: LicenseHeaderCheck [-r] <header file> <dir or files>");
        return;/*from  w w  w .j  a va2 s .c o  m*/
    }

    LicenseHeaderCheck checker = new LicenseHeaderCheck(new File(cl.getArgList().get(0).toString()),
            cl.hasOption("r"));

    if (cl.getOptionValues("skip") != null)
        for (String skip : cl.getOptionValues("skip"))
            checker.addSkip(skip);

    for (int i = 1; i < cl.getArgList().size(); i++) {
        checker.go(new File(cl.getArgList().get(i).toString()));
    }
}