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

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

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:name.wagners.fssp.Main.java

/**
 * @param args/*from w ww .j a  v a  2s  .  com*/
 *            command-line arguments
 */
public static void main(final String[] args) {
    // create the command line parser
    CommandLineParser parser = new PosixParser();

    // create the Options
    Options options = new Options();

    options.addOption(OptionBuilder.hasArg().withArgName("gn").withLongOpt("generations")
            .withDescription("Number of generations [default: 50]").withType(Integer.valueOf(0)).create("g"));

    options.addOption(OptionBuilder.hasArg().withArgName("mp").withLongOpt("mutation")
            .withDescription("Mutation propability [default: 0.5]").withType(Double.valueOf(0)).create("m"));

    options.addOption(OptionBuilder.hasArg().withArgName("ps").withLongOpt("populationsize")
            .withDescription("Size of population [default: 20]").withType(Integer.valueOf(0)).create("p"));

    options.addOption(OptionBuilder.hasArg().withArgName("rp").withLongOpt("recombination")
            .withDescription("Recombination propability [default: 0.8]").withType(Double.valueOf(0))
            .create("r"));

    options.addOption(OptionBuilder.hasArg().withArgName("sp").withLongOpt("selectionpressure")
            .withDescription("Selection pressure [default: 4]").withType(Integer.valueOf(0)).create("s"));

    options.addOption(OptionBuilder.withLongOpt("help").withDescription("print this message").create("h"));

    options.addOption(OptionBuilder.hasArg().withArgName("filename").isRequired().withLongOpt("file")
            .withDescription("Problem file [default: \"\"]").withType(String.valueOf("")).create("f"));

    options.addOptionGroup(new OptionGroup()
            .addOption(OptionBuilder.withLongOpt("verbose").withDescription("be extra verbose").create("v"))
            .addOption(OptionBuilder.withLongOpt("quiet").withDescription("be extra quiet").create("q")));

    options.addOption(OptionBuilder.withLongOpt("version")
            .withDescription("print the version information and exit").create("V"));

    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        // validate that block-size has been set
        if (line.hasOption("h")) {
            // automatically generate the help statement
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("fssp", options);
        }

    } catch (MissingOptionException exp) {
        log.info("An option was missing:" + exp.getMessage(), exp);

        // automatically generate the help statement
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("fssp", options);
    } catch (MissingArgumentException exp) {
        log.info("An argument was missing:" + exp.getMessage(), exp);

        // automatically generate the help statement
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("fssp", options);
    } catch (AlreadySelectedException exp) {
        // automatically generate the help statement
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("fssp", options);
    } catch (ParseException exp) {
        log.info("Unexpected exception:" + exp.getMessage(), exp);

        // automatically generate the help statement
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("fssp", options);

        System.exit(1);
    }

    // Ausgabe der eingestellten Optionen

    log.info("Configuration");
    // log.info(" Datafile: {}", fname);
}

From source file:dk.netarkivet.harvester.tools.CreateIndex.java

/**
 * The main method that does the parsing of the commandline, and makes the actual index request.
 *
 * @param args the arguments//from w  w  w.  j  av  a  2  s. co m
 */
public static void main(String[] args) {
    Options options = new Options();
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    Option indexType = new Option("t", "type", true, "Type of index");
    Option jobList = new Option("l", "jobids", true, "list of jobids");
    indexType.setRequired(true);
    jobList.setRequired(true);
    options.addOption(indexType);
    options.addOption(jobList);

    try {
        // parse the command line arguments
        cmd = parser.parse(options, args);
    } catch (MissingOptionException e) {
        System.err.println("Some of the required parameters are missing: " + e.getMessage());
        dieWithUsage();
    } catch (ParseException exp) {
        System.err.println("Parsing of parameters failed: " + exp.getMessage());
        dieWithUsage();
    }

    String typeValue = cmd.getOptionValue(INDEXTYPE_OPTION);
    String jobidsValue = cmd.getOptionValue(JOBIDS_OPTION);
    String[] jobidsAsStrings = jobidsValue.split(",");
    Set<Long> jobIDs = new HashSet<Long>();
    for (String idAsString : jobidsAsStrings) {
        jobIDs.add(Long.valueOf(idAsString));
    }

    JobIndexCache cache = null;
    String indexTypeAstring = "";
    if (typeValue.equalsIgnoreCase("CDX")) {
        indexTypeAstring = "CDX";
        cache = IndexClientFactory.getCDXInstance();
    } else if (typeValue.equalsIgnoreCase("DEDUP")) {
        indexTypeAstring = "DEDUP";
        cache = IndexClientFactory.getDedupCrawllogInstance();
    } else if (typeValue.equalsIgnoreCase("CRAWLLOG")) {
        indexTypeAstring = "CRAWLLOG";
        cache = IndexClientFactory.getFullCrawllogInstance();
    } else {
        System.err.println("Unknown indextype '" + typeValue + "' requested.");
        dieWithUsage();
    }

    System.out.println("Creating " + indexTypeAstring + " index for ids: " + jobIDs);
    Index<Set<Long>> index = cache.getIndex(jobIDs);
    JMSConnectionFactory.getInstance().cleanup();
}

From source file:edu.cwru.jpdg.JPDG.java

public static void main(String[] argv) throws pDG_Builder.Error {
    final Option helpOpt = new Option("h", "help", false, "print this message");
    final Option outputOpt = new Option("o", "output", true, "output file location");
    final Option baseOpt = new Option("b", "base-dir", true, "base directory to analyze");
    final Option excludeOpt = new Option("e", "exclude", true, "exclude these directories");
    final Option classOpt = new Option("c", "classpath", true, "classpath for soot");
    final Option labelOpt = new Option("l", "label-type", true,
            "label type, valid choices are: expr-tree, inst");
    final org.apache.commons.cli.Options options = new org.apache.commons.cli.Options();

    options.addOption(helpOpt);//from w ww  . j  a v a 2 s. c o  m
    options.addOption(outputOpt);
    options.addOption(baseOpt);
    options.addOption(classOpt);
    options.addOption(labelOpt);
    options.addOption(excludeOpt);

    String cp = null;
    String base_dir = null;
    String label_type = "expr-tree";
    String output_file = null;
    List<String> excluded = new ArrayList<String>();

    try {
        GnuParser parser = new GnuParser();
        CommandLine line = parser.parse(options, argv);

        if (line.hasOption(helpOpt.getLongOpt())) {
            Usage(options);
        }

        cp = line.getOptionValue(classOpt.getLongOpt());
        base_dir = line.getOptionValue(baseOpt.getLongOpt());
        label_type = line.getOptionValue(labelOpt.getLongOpt());
        output_file = line.getOptionValue(outputOpt.getLongOpt());
        String[] ex = line.getOptionValues(excludeOpt.getLongOpt());
        if (ex != null) {
            excluded = Arrays.asList(ex);
        }
    } catch (final MissingOptionException e) {
        System.err.println(e.getMessage());
        Usage(options);
    } catch (final UnrecognizedOptionException e) {
        System.err.println(e.getMessage());
        Usage(options);
    } catch (final ParseException e) {
        System.err.println(e.getMessage());
        System.exit(1);
    }

    List<String> dirs = new ArrayList<String>();
    dirs.add(base_dir);

    soot.Scene S = runSoot(cp, dirs, excluded);
    writeGraph(build_PDG(S, excluded, label_type), output_file);
}

From source file:imageviewer.util.PasswordGenerator.java

public static void main(String[] args) {

    Option help = new Option("help", "Print this message");
    Option file = OptionBuilder.withArgName("file").hasArg().withDescription("Password filename")
            .create("file");
    Option addUser = OptionBuilder.withArgName("add").hasArg().withDescription("Add user profile")
            .create("add");
    Option removeUser = OptionBuilder.withArgName("remove").hasArg().withDescription("Remove user profile")
            .create("remove");
    Option updateUser = OptionBuilder.withArgName("update").hasArg().withValueSeparator()
            .withDescription("Update user profile").create("update");

    file.setRequired(true);//  w  ww .  j a  va  2  s  .  c  om
    OptionGroup og = new OptionGroup();
    og.addOption(addUser);
    og.addOption(removeUser);
    og.addOption(updateUser);
    og.setRequired(true);

    Options o = new Options();
    o.addOption(help);
    o.addOption(file);
    o.addOptionGroup(og);

    try {
        CommandLineParser parser = new GnuParser();
        CommandLine line = parser.parse(o, args);
        PasswordGenerator pg = new PasswordGenerator(line);
        pg.execute();
    } catch (UnrecognizedOptionException uoe) {
        System.err.println("Unknown argument: " + uoe.getMessage());
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("PasswordGenerator", o);
        System.exit(1);
    } catch (MissingOptionException moe) {
        System.err.println("Missing argument: " + moe.getMessage());
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("PasswordGenerator", o);
        System.exit(1);
    } catch (Exception exc) {
        exc.printStackTrace();
    }
}

From source file:es.upm.oeg.tools.quality.ldsniffer.cmd.LDSnifferApp.java

public static void main(String[] args) {

    HelpFormatter help = new HelpFormatter();
    String header = "Assess a list of Linked Data resources using Linked Data Quality Model.";
    String footer = "Please report issues at https://github.com/nandana/ld-sniffer";

    try {/*from w  ww  .  j a va  2 s .c o m*/
        CommandLine line = parseArguments(args);
        if (line.hasOption("help")) {
            help.printHelp("LDSnifferApp", header, OPTIONS, footer, true);
            System.exit(0);
        }

        evaluationTimeout = Integer.parseInt(line.getOptionValue("t", "10"));

        if (line.hasOption("md")) {
            includeMetricDefinitions = true;
        }
        if (line.hasOption("rdf")) {
            rdfOutput = true;
        }

        logger.info("URL List: " + line.getOptionValue("ul"));
        logger.info("TDB Path: " + line.getOptionValue("tdb"));
        logger.info("Metrics Path: " + line.getOptionValue("ml"));
        logger.info("Include Metric definitions: " + line.getOptionValue("ml"));
        logger.info("RDF output: " + line.getOptionValue("rdf"));
        logger.info("Timeout (mins): " + evaluationTimeout);

        if (line.hasOption("ml")) {
            Path path = Paths.get(line.getOptionValue("ml"));
            if (!Files.exists(path)) {
                throw new IOException(path.toAbsolutePath().toString() + " : File doesn't exit.");
            }
        }

        //Set the TDB path
        String tdbDirectory;
        if (line.hasOption("tdb")) {
            tdbDirectory = line.getOptionValue("tdb");
        } else {
            Path tempPath = Files.createTempDirectory("tdb_");
            tdbDirectory = tempPath.toAbsolutePath().toString();
        }

        // Create the URL list for the evaluation
        if (!line.hasOption("ul") && !line.hasOption("url")) {
            System.out.println("One of the following parameters are required: url or urlList ");
            help.printHelp("LDSnifferApp", header, OPTIONS, footer, true);
            System.exit(0);
        } else if (line.hasOption("ul") && line.hasOption("url")) {
            System.out.println("You have to specify either url or urlList, not both.");
            help.printHelp("LDSnifferApp", header, OPTIONS, footer, true);
            System.exit(0);
        }

        List<String> urlList = null;
        if (line.hasOption("ul")) {
            Path path = Paths.get(line.getOptionValue("ul"));
            logger.info("Path : " + path.toAbsolutePath().toString());
            logger.info("Path exits : " + Files.exists(path));
            urlList = Files.readAllLines(path, Charset.defaultCharset());
        } else if (line.hasOption("url")) {
            urlList = new ArrayList<>();
            urlList.add(line.getOptionValue("url"));
        }

        Executor executor = new Executor(tdbDirectory, urlList);
        executor.execute();

    } catch (MissingOptionException e) {
        help.printHelp("LDSnifferApp", header, OPTIONS, footer, true);
        logger.error("Missing arguments.  Reason: " + e.getMessage(), e);
        System.exit(1);
    } catch (ParseException e) {
        logger.error("Parsing failed.  Reason: " + e.getMessage(), e);
        System.exit(1);
    } catch (IOException e) {
        logger.error("Execution failed.  Reason: " + e.getMessage(), e);
        System.exit(1);
    }

}

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

public static void main(String[] argv) throws ClassNotFoundException, ParseException {
    Options options = createOptions();// ww  w  . ja  va  2s .  co  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:kellinwood.zipsigner.cmdline.Main.java

public static void main(String[] args) {
    try {/*from w  w w  .j a  v a 2  s. com*/

        Options options = new Options();
        CommandLine cmdLine = null;
        Option helpOption = new Option("h", "help", false, "Display usage information");

        Option modeOption = new Option("m", "keymode", false,
                "Keymode one of: auto, auto-testkey, auto-none, media, platform, shared, testkey, none");
        modeOption.setArgs(1);

        Option keyOption = new Option("k", "key", false, "PCKS#8 encoded private key file");
        keyOption.setArgs(1);

        Option pwOption = new Option("p", "keypass", false, "Private key password");
        pwOption.setArgs(1);

        Option certOption = new Option("c", "cert", false, "X.509 public key certificate file");
        certOption.setArgs(1);

        Option sbtOption = new Option("t", "template", false, "Signature block template file");
        sbtOption.setArgs(1);

        Option keystoreOption = new Option("s", "keystore", false, "Keystore file");
        keystoreOption.setArgs(1);

        Option aliasOption = new Option("a", "alias", false, "Alias for key/cert in the keystore");
        aliasOption.setArgs(1);

        options.addOption(helpOption);
        options.addOption(modeOption);
        options.addOption(keyOption);
        options.addOption(certOption);
        options.addOption(sbtOption);
        options.addOption(pwOption);
        options.addOption(keystoreOption);
        options.addOption(aliasOption);

        Parser parser = new BasicParser();

        try {
            cmdLine = parser.parse(options, args);
        } catch (MissingOptionException x) {
            System.out.println("One or more required options are missing: " + x.getMessage());
            usage(options);
        } catch (ParseException x) {
            System.out.println(x.getClass().getName() + ": " + x.getMessage());
            usage(options);
        }

        if (cmdLine.hasOption(helpOption.getOpt()))
            usage(options);

        Properties log4jProperties = new Properties();
        log4jProperties.load(new FileReader("log4j.properties"));
        PropertyConfigurator.configure(log4jProperties);
        LoggerManager.setLoggerFactory(new Log4jLoggerFactory());

        List<String> argList = cmdLine.getArgList();
        if (argList.size() != 2)
            usage(options);

        ZipSigner signer = new ZipSigner();

        signer.addAutoKeyObserver(new Observer() {
            @Override
            public void update(Observable observable, Object o) {
                System.out.println("Signing with key: " + o);
            }
        });

        Class bcProviderClass = Class.forName("org.bouncycastle.jce.provider.BouncyCastleProvider");
        Provider bcProvider = (Provider) bcProviderClass.newInstance();

        KeyStoreFileManager.setProvider(bcProvider);

        signer.loadProvider("org.spongycastle.jce.provider.BouncyCastleProvider");

        PrivateKey privateKey = null;
        if (cmdLine.hasOption(keyOption.getOpt())) {
            if (!cmdLine.hasOption(certOption.getOpt())) {
                System.out.println("Certificate file is required when specifying a private key");
                usage(options);
            }

            String keypw = null;
            if (cmdLine.hasOption(pwOption.getOpt()))
                keypw = pwOption.getValue();
            else {
                keypw = new String(readPassword("Key password"));
                if (keypw.equals(""))
                    keypw = null;
            }
            URL privateKeyUrl = new File(keyOption.getValue()).toURI().toURL();

            privateKey = signer.readPrivateKey(privateKeyUrl, keypw);
        }

        X509Certificate cert = null;
        if (cmdLine.hasOption(certOption.getOpt())) {

            if (!cmdLine.hasOption(keyOption.getOpt())) {
                System.out.println("Private key file is required when specifying a certificate");
                usage(options);
            }

            URL certUrl = new File(certOption.getValue()).toURI().toURL();
            cert = signer.readPublicKey(certUrl);
        }

        byte[] sigBlockTemplate = null;
        if (cmdLine.hasOption(sbtOption.getOpt())) {
            URL sbtUrl = new File(sbtOption.getValue()).toURI().toURL();
            sigBlockTemplate = signer.readContentAsBytes(sbtUrl);
        }

        if (cmdLine.hasOption(keyOption.getOpt())) {
            signer.setKeys("custom", cert, privateKey, sigBlockTemplate);
            signer.signZip(argList.get(0), argList.get(1));
        } else if (cmdLine.hasOption(modeOption.getOpt())) {
            signer.setKeymode(modeOption.getValue());
            signer.signZip(argList.get(0), argList.get(1));
        } else if (cmdLine.hasOption((keystoreOption.getOpt()))) {
            String alias = null;

            if (!cmdLine.hasOption(aliasOption.getOpt())) {

                KeyStore keyStore = KeyStoreFileManager.loadKeyStore(keystoreOption.getValue(), (char[]) null);
                for (Enumeration<String> e = keyStore.aliases(); e.hasMoreElements();) {
                    alias = e.nextElement();
                    System.out.println("Signing with key: " + alias);
                    break;
                }
            } else
                alias = aliasOption.getValue();

            String keypw = null;
            if (cmdLine.hasOption(pwOption.getOpt()))
                keypw = pwOption.getValue();
            else {
                keypw = new String(readPassword("Key password"));
                if (keypw.equals(""))
                    keypw = null;
            }

            CustomKeySigner.signZip(signer, keystoreOption.getValue(), null, alias, keypw.toCharArray(),
                    "SHA1withRSA", argList.get(0), argList.get(1));
        } else {
            signer.setKeymode("auto-testkey");
            signer.signZip(argList.get(0), argList.get(1));
        }

    } catch (Throwable t) {
        t.printStackTrace();
    }
}

From source file:net.sf.markov4jmeter.behaviormodelextractor.BehaviorModelExtractor.java

/**
 * Main method of the application./*from w  ww .  j a v a 2  s  .c o m*/
 * 
 * @param argv
 *            Command-line arguments vector.
 */
public static void main(final String[] argv) {

    try {

        System.out.println("****************************");
        System.out.println("Start BehaviorModelExtractor");
        System.out.println("****************************");

        // ---- read command-line parameters ----;

        // initialize arguments handler for retrieving the command line
        // options; might throw a NullPointer-, IllegalArgument- or
        // ParseException;
        CommandLineArgumentsHandler.init(argv);

        final String inputFile = CommandLineArgumentsHandler.getInputFile();

        final String outputDirectory = CommandLineArgumentsHandler.getOutputDirectory();

        // template file is optional;
        final String templateFile = CommandLineArgumentsHandler.getTemplateFile();

        // use case mapping file is optional;
        final String useCaseMappingFile = CommandLineArgumentsHandler.getUseCaseMappingFile();

        // line-break type of CSV-files is optional;
        final int lineBreakType = CommandLineArgumentsHandler.getLineBreakType();

        // clustering method is optional;
        final String clusteringMethod = CommandLineArgumentsHandler.getClusteringMethod();

        // ---- initialize and start the Behavior Model Extractor ----

        final BehaviorModelExtractor behaviorModelExtractor = new BehaviorModelExtractor();

        // might throw a FileNotFound- or IOException;
        behaviorModelExtractor.init(useCaseMappingFile, templateFile, lineBreakType);

        // might throw an IO-, Parse- or ExtractionException;
        behaviorModelExtractor.extract(inputFile, outputDirectory, clusteringMethod);

        System.out.println("****************************");
        System.out.println("END BehaviorModelExtractor");
        System.out.println("****************************");

    } catch (final MissingOptionException ex) {

        // this exception type indicates that no argument has been passed;
        CommandLineArgumentsHandler.printUsage();

    } catch (final Exception ex) {

        System.err.println(ex.getMessage());
        CommandLineArgumentsHandler.printUsage();
    }
}

From source file:com.octo.mbo.CopyNotes.java

static CommandLine parseCommandLine(String[] args) throws CommandLineException {
    Options options = new Options();
    Option optSource = new Option("s",
            "Source file where the comments can be extracted (only pptx format supported)");
    optSource.setRequired(true);/* w w w. j  a v  a 2  s . co  m*/
    optSource.setArgs(1);
    optSource.setLongOpt("source");
    options.addOption(optSource);

    Option optTarget = new Option("t", "Target file where the comments are merged (case of pptx format)");
    optTarget.setRequired(true);
    optTarget.setArgs(1);
    optTarget.setLongOpt("target");
    options.addOption(optTarget);

    HelpFormatter formatter = new HelpFormatter();
    final String header = "CopyNotes allows to extract, copy and merge notes of pptx files. \n"
            + "Notes can be merged with the notes of an existing files \n"
            + "Notes can be exported to a xml file with a custom format or imported \n"
            + "from this xml format and merged into an existing pptx document. \n"
            + "The target file is updated \n";
    final String footer = "";

    CommandLineParser cliParser = new DefaultParser();
    try {
        return cliParser.parse(options, args);
    } catch (MissingOptionException mex) {
        log.error(mex.getMessage());
        log.debug("Error parsing command line", mex);
        formatter.printHelp(
                "java -jar copypptxnotes-<version>-jar-with-dependencies.jar -s <source> -t <target>", header,
                options, footer);
        throw new CommandLineException("Missing option", mex);
    } catch (ParseException pex) {
        log.debug("Error parsing the command line. Please use CopyComment --help", pex);
        formatter.printHelp(
                "java -jar copypptxnotes-<version>-jar-with-dependencies.jar  -s <source> -t <target>", header,
                options, footer);
        throw new CommandLineException("Parse Exception", pex);
    }
}

From source file:com.j2biz.pencil.Starter.java

private static void exitCauseMissingOption(MissingOptionException e) {
    System.err.println("Missing Option: " + e.getMessage());
    System.exit(-1);/*from w ww  .ja v a2s .  c om*/
}