Example usage for org.apache.commons.cli MissingOptionException getMissingOptions

List of usage examples for org.apache.commons.cli MissingOptionException getMissingOptions

Introduction

In this page you can find the example usage for org.apache.commons.cli MissingOptionException getMissingOptions.

Prototype

public List getMissingOptions() 

Source Link

Document

Return the list of options (as strings) missing in the command line parsed.

Usage

From source file:com.boulmier.machinelearning.jobexecutor.JobExecutor.java

public static void main(String[] args) throws ParseException, IOException, InterruptedException {
    Options options = defineOptions();/*from   ww  w .j  av a 2  s. c  o m*/
    sysMon = new JavaSysMon();
    InetAddress vmscheduler_ip, mongodb_ip = null;
    Integer vmscheduler_port = null, mongodb_port = null;
    CommandLineParser parser = new BasicParser();

    try {
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption(JobExecutorConfig.OPTIONS.CMD.LONGPORTFIELD)) {
            vmscheduler_port = Integer.valueOf(cmd.getOptionValue(JobExecutorConfig.OPTIONS.CMD.LONGPORTFIELD));
        }
        mongodb_port = (int) (cmd.hasOption(JobExecutorConfig.OPTIONS.CMD.LONGMONGOPORTFIELD)
                ? cmd.hasOption(JobExecutorConfig.OPTIONS.CMD.LONGMONGOPORTFIELD)
                : JobExecutorConfig.OPTIONS.LOGGING.MONGO_DEFAULT_PORT);
        mongodb_ip = InetAddress.getByName(cmd.getOptionValue(JobExecutorConfig.OPTIONS.CMD.LONGMONGOIPFIELD));

        vmscheduler_ip = InetAddress.getByName(cmd.getOptionValue(JobExecutorConfig.OPTIONS.CMD.LONGIPFIELD));

        decryptKey = cmd.getOptionValue("decrypt-key");

        debugState = cmd.hasOption(JobExecutorConfig.OPTIONS.CMD.LONGDEBUGFIELD);

        logger = LoggerFactory.getLogger();
        logger.info("Attempt to connect on master @" + vmscheduler_ip + ":" + vmscheduler_port);

        new RequestConsumer().start();

    } catch (MissingOptionException moe) {
        logger.error(moe.getMissingOptions() + " are missing");
        HelpFormatter help = new HelpFormatter();
        help.printHelp(JobExecutor.class.getSimpleName(), options);

    } catch (UnknownHostException ex) {
        logger.error(ex.getMessage());
    } finally {
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                logger.info("JobExeutor is shutting down");
            }
        });
    }
}

From source file:net.ninjacat.stubborn.Stubborn.java

public static void main(String[] argv) throws ClassNotFoundException, ParseException {
    Options options = createOptions();/*  w w w  . j a  va  2  s  .c  o m*/
    if (argv.length == 0) {
        printHelp(options);
        return;
    }

    Class.forName(Bootstrapper.class.getCanonicalName());
    CommandLineParser parser = new GnuParser();

    try {
        CommandLine commandLine = parser.parse(options, argv);
        if (commandLine.hasOption("h")) {
            printHelp(options);
            return;
        }

        Context context = new Context(commandLine);

        Transformer transformer = Bootstrapper.get(Transformer.class);

        transformer.transform(context);
    } catch (MissingOptionException ex) {
        System.out.println("Missing required parameter " + ex.getMissingOptions());
        printHelp(options);
    } catch (TransformationException ex) {
        System.out.println("Failed to perform transformation caused by " + ex.getCause());
        System.out.println(ex.getMessage());
    }
}

From source file:net.kahowell.xsd.fuzzer.XmlGenerator.java

/**
 * Drives the application, parsing command-line arguments to determine
 * options.//from w  w w.  ja  va 2  s .co m
 * 
 * @param args command line args
 */
public static void main(String[] args) {
    try {
        setupLog4j();
        CommandLine commandLine = parser.parse(ConsoleOptions.OPTIONS, args);
        if (commandLine.hasOption("d")) {
            Logger.getLogger("net.kahowell.xsd.fuzzer").setLevel(Level.DEBUG);
        }
        for (Option option : commandLine.getOptions()) {
            if (option.getValue() != null) {
                log.debug("Using " + option.getDescription() + ": " + option.getValue());
            } else {
                log.debug("Using " + option.getDescription());
            }
        }

        Injector injector = Guice.createInjector(
                Modules.override(Modules.combine(new DefaultGeneratorsModule(), new DefaultOptionsModule()))
                        .with(new CommandLineArgumentsModule(commandLine)));

        log.debug(injector.getBindings());

        XsdParser xsdParser = injector.getInstance(XsdParser.class);
        XmlOptions xmlOptions = injector
                .getInstance(Key.get(XmlOptions.class, Names.named("xml save options")));
        XmlGenerator xmlGenerator = injector.getInstance(XmlGenerator.class);
        XmlGenerationOptions xmlGenerationOptions = injector.getInstance(XmlGenerationOptions.class);

        doPostModuleConfig(commandLine, xmlGenerationOptions, injector);

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        XmlObject generatedXml = xsdParser.generateXml(commandLine.getOptionValue("root"));
        generatedXml.save(stream, xmlOptions);
        if (commandLine.hasOption("v")) {
            if (xsdParser.validate(stream)) {
                log.info("Valid XML file produced.");
            } else {
                log.info("Invalid XML file produced.");
                System.exit(4);
            }
        }
        xmlGenerator.showOrSave(stream);
    } catch (MissingOptionException e) {
        if (e.getMissingOptions().size() != 0) {
            System.err.println("Missing argument(s): " + Arrays.toString(e.getMissingOptions().toArray()));
        }
        helpFormatter.printHelp(XmlGenerator.class.getSimpleName(), ConsoleOptions.OPTIONS);
        System.exit(1);
    } catch (ParseException e) {
        helpFormatter.printHelp(XmlGenerator.class.getSimpleName(), ConsoleOptions.OPTIONS);
        System.exit(2);
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(3);
    }
}

From source file:gpframework.RunExperiment.java

/**
 * Application's entry point./*  w ww .  j  ava 2s.com*/
 * 
 * @param args
 * @throws ParseException
 * @throws ParameterException 
 */
public static void main(String[] args) throws ParseException, ParameterException {
    // Failsafe parameters
    if (args.length == 0) {
        args = new String[] { "-f", "LasSortednessFunction", "-n", "5", "-ff", "JoinFactory", "-tf",
                "SortingElementFactory", "-pf", "SortingProgramFactory", "-s", "SMOGPSelection", "-a", "SMOGP",
                "-t", "50", "-e", "1000000000", "-mf", "SingleMutationFactory", "-d", "-bn", "other" };
    }

    // Create options
    Options options = new Options();
    setupOptions(options);

    // Read options from the command line
    CommandLineParser parser = new PosixParser();
    CommandLine cmd;

    // Print help if parameter requirements are not met
    try {
        cmd = parser.parse(options, args);
    }

    // If some parameters are missing, print help
    catch (MissingOptionException e) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("java -jar GPFramework \n", options);
        System.out.println();
        System.out.println("Missing parameters: " + e.getMissingOptions());
        return;
    }

    // Re-initialize PRNG
    long seed = System.currentTimeMillis();
    Utils.random = new Random(seed);

    // Set the problem size
    int problemSize = Integer.parseInt(cmd.getOptionValue("n"));

    // Set debug mode and cluster mode
    Utils.debug = cmd.hasOption("d");
    RunExperiment.cluster = cmd.hasOption("c");

    // Initialize fitness function and some factories
    FitnessFunction fitnessFunction = fromName(cmd.getOptionValue("f"), problemSize);
    MutationFactory mutationFactory = fromName(cmd.getOptionValue("mf"));
    Selection selectionCriterion = fromName(cmd.getOptionValue("s"));
    FunctionFactory functionFactory = fromName(cmd.getOptionValue("ff"));
    TerminalFactory terminalFactory = fromName(cmd.getOptionValue("tf"), problemSize);
    ProgramFactory programFactory = fromName(cmd.getOptionValue("pf"), functionFactory, terminalFactory);

    // Initialize algorithm
    Algorithm algorithm = fromName(cmd.getOptionValue("a"), mutationFactory, selectionCriterion);
    algorithm.setParameter("evaluationsBudget", cmd.getOptionValue("e"));
    algorithm.setParameter("timeBudget", cmd.getOptionValue("t"));

    // Initialize problem
    Problem problem = new Problem(programFactory, fitnessFunction);
    Program solution = algorithm.solve(problem);

    Utils.debug("Population results: ");
    Utils.debug(algorithm.getPopulation().toString());
    Utils.debug(algorithm.getPopulation().parse());

    Map<String, Object> entry = new HashMap<String, Object>();

    // Copy algorithm setup
    for (Object o : options.getRequiredOptions()) {
        Option option = options.getOption(o.toString());
        entry.put(option.getLongOpt(), cmd.getOptionValue(option.getOpt()));
    }
    entry.put("seed", seed);

    // Copy results
    entry.put("bestProgram", solution.toString());
    entry.put("bestSolution", fitnessFunction.normalize(solution));

    // Copy all statistics
    entry.putAll(algorithm.getStatistics());

    Utils.debug("Maximum encountered population size: "
            + algorithm.getStatistics().get("maxPopulationSizeToCompleteFront"));
    Utils.debug("Maximum encountered tree size: "
            + algorithm.getStatistics().get("maxProgramComplexityToCompleteFront"));
    Utils.debug("Solution complexity: " + solution.complexity() + "/" + (2 * problemSize - 1));
}

From source file:at.ac.tuwien.ims.latex2mobiformulaconv.app.Main.java

private static void parseCli(String[] args) {
    CommandLineParser parser = new PosixParser();
    try {/* ww w .j  av a  2  s.c o  m*/
        CommandLine cmd = parser.parse(options, args);

        // Show usage, ignore other parameters and quit
        if (cmd.hasOption('h')) {
            usage();
            logger.debug("Help called, main() exit.");
            System.exit(0);
        }

        if (cmd.hasOption('d')) {
            // Activate debug markup only - does not affect logging!
            debugMarkupOutput = true;
        }

        if (cmd.hasOption('m')) {
            exportMarkup = true;
        }

        if (cmd.hasOption('t')) {
            title = cmd.getOptionValue('t');
        }

        if (cmd.hasOption('f')) {
            filename = cmd.getOptionValue('f');
        }

        if (cmd.hasOption('n')) {
            exportMarkup = true; // implicit markup export
            noMobiConversion = true;
        }

        if (cmd.hasOption('i')) {
            String[] inputValues = cmd.getOptionValues('i');
            for (String inputValue : inputValues) {
                inputPaths.add(Paths.get(inputValue));
            }
        } else {
            logger.error("You have to specify an inputPath file or directory!");
            usage();
            System.exit(1);
        }

        if (cmd.hasOption('o')) {
            String outputDirectory = cmd.getOptionValue('o');

            outputPath = Paths.get(outputDirectory).toAbsolutePath();
            logger.debug("Output path: " + outputPath.toAbsolutePath().toString());
            if (!Files.isDirectory(outputPath) && Files.isRegularFile(outputPath)) {
                logger.error("Given output directory is a file! Exiting...");

                System.exit(1);
            }

            if (!Files.exists(outputPath)) {
                Files.createDirectory(outputPath);
            }

            if (!Files.isWritable(outputPath)) {
                logger.error("Given output directory is not writable! Exiting...");
                logger.debug(outputPath.toAbsolutePath().toString());
                System.exit(1);
            }
            logger.debug("Output path: " + outputPath.toAbsolutePath().toString());

        } else {
            // Set default output directory if none is given
            outputPath = workingDirectory;
        }

        // If set, replace LaTeX Formulas with PNG images, created by
        if (cmd.hasOption("r")) {
            logger.debug("Picture Flag set");
            replaceWithPictures = true;
        }

        if (cmd.hasOption("u")) {
            logger.debug("Use calibre instead of kindlegen");
            useCalibreInsteadOfKindleGen = true;
        }

        // Executable configuration
        LatexToHtmlConverter latexToHtmlConverter = (LatexToHtmlConverter) applicationContext
                .getBean("latex2html-converter");
        if (cmd.hasOption(latexToHtmlConverter.getExecOption().getOpt())) {
            String execValue = cmd.getOptionValue(latexToHtmlConverter.getExecOption().getOpt());
            logger.info("LaTeX to HTML Executable argument was given: " + execValue);
            Path execPath = Paths.get(execValue);
            latexToHtmlConverter.setExecPath(execPath);
        }

        String htmlToMobiConverterBean = KINDLEGEN_HTML2MOBI_CONVERTER;
        if (useCalibreInsteadOfKindleGen) {
            htmlToMobiConverterBean = CALIBRE_HTML2MOBI_CONVERTER;
        }

        HtmlToMobiConverter htmlToMobiConverter = (HtmlToMobiConverter) applicationContext
                .getBean(htmlToMobiConverterBean);
        Option htmlToMobiOption = htmlToMobiConverter.getExecOption();
        if (cmd.hasOption(htmlToMobiOption.getOpt())) {
            String execValue = cmd.getOptionValue(htmlToMobiOption.getOpt());
            logger.info("HTML to Mobi Executable argument was given: " + execValue);
            try {
                Path execPath = Paths.get(execValue);
                htmlToMobiConverter.setExecPath(execPath);
            } catch (InvalidPathException e) {
                logger.error("Invalid path given for --" + htmlToMobiOption.getLongOpt() + " <"
                        + htmlToMobiOption.getArgName() + ">");
                logger.error("I will try to use your system's PATH variable...");
            }
        }

    } catch (MissingOptionException m) {

        Iterator<String> missingOptionsIterator = m.getMissingOptions().iterator();
        while (missingOptionsIterator.hasNext()) {
            logger.error("Missing required options: " + missingOptionsIterator.next() + "\n");
        }
        usage();
        System.exit(1);
    } catch (MissingArgumentException a) {
        logger.error("Missing required argument for option: " + a.getOption().getOpt() + "/"
                + a.getOption().getLongOpt() + "<" + a.getOption().getArgName() + ">");
        usage();
        System.exit(2);
    } catch (ParseException e) {
        logger.error("Error parsing command line arguments, exiting...");
        logger.error(e.getMessage(), e);
        System.exit(3);
    } catch (IOException e) {
        logger.error("Error creating output path at " + outputPath.toAbsolutePath().toString());
        logger.error(e.getMessage(), e);
        logger.error("Exiting...");
        System.exit(4);
    }
}

From source file:com.databasepreservation.cli.CLI.java

/**
 * Obtains the arguments needed to create new import and export modules
 *
 * @param factoriesPair/*w w  w.  j  a v  a2s . co  m*/
 *          A pair of DatabaseModuleFactory objects containing the selected
 *          import and export module factories
 * @param args
 *          The command line arguments
 * @return A DatabaseModuleFactoriesArguments containing the arguments to
 *         create the import and export modules
 * @throws ParseException
 *           If the arguments could not be parsed or are invalid
 */
private DatabaseModuleFactoriesArguments getModuleArguments(DatabaseModuleFactoriesPair factoriesPair,
        List<String> args) throws ParseException, OperationNotSupportedException {
    DatabaseModuleFactory importModuleFactory = factoriesPair.getImportModuleFactory();
    DatabaseModuleFactory exportModuleFactory = factoriesPair.getExportModuleFactory();

    // get appropriate command line options
    CommandLineParser commandLineParser = new DefaultParser();
    CommandLine commandLine;
    Options options = new Options();

    HashMap<String, Parameter> mapOptionToParameter = new HashMap<String, Parameter>();

    for (Parameter parameter : importModuleFactory.getImportModuleParameters().getParameters()) {
        Option option = parameter.toOption("i", "import");
        options.addOption(option);
        mapOptionToParameter.put(getUniqueOptionIdentifier(option), parameter);
    }
    for (ParameterGroup parameterGroup : importModuleFactory.getImportModuleParameters().getGroups()) {
        OptionGroup optionGroup = parameterGroup.toOptionGroup("i", "import");
        options.addOptionGroup(optionGroup);

        for (Parameter parameter : parameterGroup.getParameters()) {
            mapOptionToParameter.put(getUniqueOptionIdentifier(parameter.toOption("i", "import")), parameter);
        }
    }
    for (Parameter parameter : exportModuleFactory.getExportModuleParameters().getParameters()) {
        Option option = parameter.toOption("e", "export");
        options.addOption(option);
        mapOptionToParameter.put(getUniqueOptionIdentifier(option), parameter);
    }
    for (ParameterGroup parameterGroup : exportModuleFactory.getExportModuleParameters().getGroups()) {
        OptionGroup optionGroup = parameterGroup.toOptionGroup("e", "export");
        options.addOptionGroup(optionGroup);

        for (Parameter parameter : parameterGroup.getParameters()) {
            mapOptionToParameter.put(getUniqueOptionIdentifier(parameter.toOption("e", "export")), parameter);
        }
    }

    Option importOption = Option.builder("i").longOpt("import").hasArg().optionalArg(false).build();
    Option exportOption = Option.builder("e").longOpt("export").hasArg().optionalArg(false).build();
    Option pluginOption = Option.builder("p").longOpt("plugin").hasArg().optionalArg(false).build();
    options.addOption(importOption);
    options.addOption(exportOption);
    options.addOption(pluginOption);

    // new HelpFormatter().printHelp(80, "dbptk", "\nModule Options:", options,
    // null, true);

    // parse the command line arguments with those options
    try {
        commandLine = commandLineParser.parse(options, args.toArray(new String[] {}), false);
        if (!commandLine.getArgList().isEmpty()) {
            throw new ParseException("Unrecognized option: " + commandLine.getArgList().get(0));
        }
    } catch (MissingOptionException e) {
        // use long names instead of short names in the error message
        List<String> missingShort = e.getMissingOptions();
        List<String> missingLong = new ArrayList<String>();
        for (String shortOption : missingShort) {
            missingLong.add(options.getOption(shortOption).getLongOpt());
        }
        LOGGER.debug("MissingOptionException (the original, unmodified exception)", e);
        throw new MissingOptionException(missingLong);
    }

    // create arguments to pass to factory
    HashMap<Parameter, String> importModuleArguments = new HashMap<Parameter, String>();
    HashMap<Parameter, String> exportModuleArguments = new HashMap<Parameter, String>();
    for (Option option : commandLine.getOptions()) {
        Parameter p = mapOptionToParameter.get(getUniqueOptionIdentifier(option));
        if (p != null) {
            if (isImportModuleOption(option)) {
                if (p.hasArgument()) {
                    importModuleArguments.put(p, option.getValue(p.valueIfNotSet()));
                } else {
                    importModuleArguments.put(p, p.valueIfSet());
                }
            } else if (isExportModuleOption(option)) {
                if (p.hasArgument()) {
                    exportModuleArguments.put(p, option.getValue(p.valueIfNotSet()));
                } else {
                    exportModuleArguments.put(p, p.valueIfSet());
                }
            } else {
                throw new ParseException("Unexpected parse exception occurred.");
            }
        }
    }
    return new DatabaseModuleFactoriesArguments(importModuleArguments, exportModuleArguments);
}

From source file:org.apache.felix.ipojo.task.IPojoc.java

/**
 * The main entry point/*from   w w w  .j  a va2s.c  o m*/
 * @param args the arguments
 */
public static void main(String[] args) {
    Options options = buildOptions();
    CommandLine cmd = null;
    try {
        cmd = buildCommandLine(args, options);
        if (cmd.hasOption('h')) {
            printHelp(options);
        } else {
            IPojoc compiler = new IPojoc();
            compiler.execute(cmd);
        }
    } catch (MissingOptionException e) {
        for (String opt : (List<String>) e.getMissingOptions()) {
            System.err.println("The '" + opt + "' option is missing");
        }
        printHelp(options);
    } catch (MissingArgumentException e) {
        System.err.println("The option '" + e.getOption() + "' requires an argument");
        printHelp(options);
    } catch (Exception e) {
        System.out.printf("Manipulation failed: %s%n", e.getMessage());
        if ((cmd != null) && cmd.hasOption('X')) {
            e.printStackTrace(System.out);
        } else {
            System.out.printf("Use -X option to print the full stack trace%n");
        }
    }
}