Example usage for org.apache.commons.cli Option getOpt

List of usage examples for org.apache.commons.cli Option getOpt

Introduction

In this page you can find the example usage for org.apache.commons.cli Option getOpt.

Prototype

public String getOpt() 

Source Link

Document

Retrieve the name of this Option.

Usage

From source file:rdfstats.generate.java

/**
 * @param args/* ww w. java2  s  .co  m*/
 */
public static void main(String[] args) {
    Option config = new Option("c", "config-file", true,
            "RDFStats configuration file (either use this and optionally -e OR only use the other command line parameters)");
    config.setArgName("filename");

    Option endpoint = new Option("e", "endpoint", true, "SPARQL endpoint URI");
    endpoint.setArgName("endpoint-uri");

    Option document = new Option("d", "document", true,
            "RDF document URL (format will be guessed by extension)");
    document.setArgName("document-url");

    Option hSize = new Option("s", "size", true,
            "Size of histograms (amount of bins), default is " + RDFStatsConfiguration.DEFAULT_PREFSIZE);
    hSize.setArgName("size");

    Option output = new Option("o", "out", true,
            "Model file (loaded if exsists as base model; output is written to screen if omitted)");
    output.setArgName("filename");

    Option format = new Option("f", "format", true,
            "File format (RDF/XML, N3, or N-TRIPLES), guessed based on file extension if omitted");
    format.setArgName("key");

    Option strHistMaxLen = new Option("m", "strhist-maxlen", true,
            "Maximum length of strings processed for StringOrderedHistogram, default is "
                    + RDFStatsConfiguration.DEFAULT_STRHIST_MAXLEN);
    strHistMaxLen.setArgName("length");

    Option quickMode = new Option("q", "quick", false,
            "Only generate histograms for new classes or if the number of total instances has changed");

    Option timeZone = new Option("t", "timezone", true,
            "The time zone to use when parsing date values (default is your locale: "
                    + TimeZone.getDefault().getDisplayName() + ")");
    timeZone.setArgName("timezone");

    //      Option classSpecHists = new Option("p", "class-specific", false, "Generate class-specific histograms (and an additional one for all untyped resources)");

    opts = new Options();
    opts.addOption(config);
    opts.addOption(endpoint);
    opts.addOption(document);
    opts.addOption(hSize);
    opts.addOption(output);
    opts.addOption(format);
    opts.addOption(strHistMaxLen);
    opts.addOption(quickMode);
    opts.addOption(timeZone);
    //      opts.addOption(classSpecHists);

    // create the parser
    CommandLineParser parser = new BasicParser();
    try {
        CommandLine cmd = parser.parse(opts, args);

        // valid if either config file, an endpointUri, or documentUrl are specified...
        if (cmd.hasOption("c") || cmd.hasOption("e") || cmd.hasOption("d")) {

            try {
                RDFStatsConfiguration cfg;

                // using config file
                if (cmd.hasOption("c")) {
                    log.info("Using config file: " + cmd.getOptionValue("c")
                            + " ignoring command line parameters except -" + endpoint.getOpt() + " ...");
                    Model cfgModel = FileManager.get().loadModel(cmd.getOptionValue("c"));
                    cfg = RDFStatsConfiguration.create(cfgModel);
                    if (cmd.getOptionValue("e") != null)
                        cfg.addEndpoint(cmd.getOptionValue("e"));
                }

                // using command line parameters
                else {
                    log.info("No config file (option -" + config.getOpt() + " specified).");
                    List<String> endpointUris = new ArrayList<String>();
                    if (cmd.hasOption("e"))
                        endpointUris.add(cmd.getOptionValue("e"));

                    List<String> documentUrls = new ArrayList<String>();
                    if (cmd.hasOption("d"))
                        documentUrls.add(cmd.getOptionValue("d"));

                    // declare format
                    String fmt = null;

                    // prepare output model (FileModel)
                    Model model = null;
                    if (cmd.hasOption("o")) {
                        if (!cmd.hasOption("f"))
                            fmt = FileUtils.guessLang(cmd.getOptionValue("o"));
                        else
                            fmt = cmd.getOptionValue("f");

                        //FileManager.get().loadModel(cmd.getOptionValue("o"), fmt);
                        File file = new File(cmd.getOptionValue("o"));
                        if (file.exists())
                            log.info("Loading model '" + file + "'...");
                        else if (file.canWrite()) {
                            log.error("File " + file + " is not writable!");
                            return;
                        }
                        model = new FileModelAssembler().createFileModel(file, fmt, !file.exists(), true,
                                ReificationStyle.Standard);
                    } else
                        model = ModelFactory.createDefaultModel();

                    cfg = RDFStatsConfiguration.create(model, endpointUris, documentUrls,
                            //                          cmd.hasOption("p"),
                            (cmd.hasOption("s")) ? Integer.parseInt(cmd.getOptionValue("s")) : null,
                            cmd.getOptionValue("o"), cmd.getOptionValue("f"),
                            (cmd.hasOption("m")) ? Integer.parseInt(cmd.getOptionValue("m")) : null,
                            cmd.hasOption("q"),
                            cmd.hasOption("t") ? TimeZone.getTimeZone(cmd.getOptionValue("t")) : null);
                }

                if (cfg.getEndpoints().size() > 0)
                    log.info("Processing " + cfg.getEndpoints().size() + " endpoint"
                            + ((cfg.getEndpoints().size() != 1) ? "s" : "") + "...");
                if (cfg.getDocumentURLs().size() > 0)
                    log.info("Processing " + cfg.getDocumentURLs().size() + " document"
                            + ((cfg.getDocumentURLs().size() != 1) ? "s" : "") + "...");
                //                 if (cfg.classSpecificHistograms())
                //                    log.info("Generating class-specific histograms");
                log.info("Preferred histogram size is " + cfg.getPrefSize() + " bins");
                log.info("Default time zone is " + cfg.getDefaultTimeZone().getDisplayName());
                log.info("Maximum length of strings processed for StringOrderedHistogram: "
                        + cfg.getStrHistMaxLength() + " characters");
                log.info("Quick mode " + ((cfg.quickMode()) ? "ENABLED" : "DISABLED"));

                GeneratorMultiple multiGen = new GeneratorMultiple(cfg);
                Model stats = multiGen.generate();

                // else (but only if not using config file) write to stdout
                if (!cmd.hasOption("o") && !cmd.hasOption("c")) {
                    log.info(
                            "No output file specified and no custom configuration used, printing to screen...");
                    stats.write(System.out, cmd.getOptionValue("f"), cmd.getOptionValue("f", "N3"));
                }

                log.info("Processed " + cfg.getEndpoints().size() + " endpoint"
                        + ((cfg.getEndpoints().size() != 1) ? "s" : ""));
                log.info("Processed " + cfg.getDocumentURLs().size() + " document"
                        + ((cfg.getDocumentURLs().size() != 1) ? "s" : ""));
                stats.close();
            } catch (GeneratorException e) {
                log.error(e.getMessage(), e);
            } catch (NumberFormatException e) {
                log.error(e.getMessage(), e);
            } catch (ConfigurationException e) {
                log.error(e.getMessage(), e);
            }
        } else {
            printUsage(
                    "Invalid arguments. Please specify at least a config file (-c), SPARQL endpoint URI (-e), or document URL (-d).");
        }
    } catch (ParseException exp) {
        printUsage(exp.getMessage());
        return;
    }

}

From source file:ro.cs.products.Executor.java

private static void printCommandLine(CommandLine cmd) {
    Logger.getRootLogger().debug("Executing with the following arguments:");
    for (Option option : cmd.getOptions()) {
        if (option.hasArgs()) {
            Logger.getRootLogger().debug(option.getOpt() + "=" + String.join(" ", option.getValues()));
        } else if (option.hasArg()) {
            Logger.getRootLogger().debug(option.getOpt() + "=" + option.getValue());
        } else {/*from www. ja  va  2 s.co  m*/
            Logger.getRootLogger().debug(option.getOpt());
        }
    }
}

From source file:ru.icc.cells.ssdc.App.java

@SuppressWarnings("static-access")
private static void parseCommandLineParams(String[] args) {
    // Creating command line parameters
    Option inputExcelFileOpt = OptionBuilder.withArgName("excel file").hasArg()
            .withDescription("an input excel workbook (*.xlsx) file").isRequired().create("i");

    Option sheetIndexesOpt = OptionBuilder.withArgName("sheet indexes").hasArg()
            .withDescription("sheet indexes (e.g. \"0-2,4,5,7-10\") in the input excel workbook").create("s");

    Option drlFileOpt = OptionBuilder.withArgName("drl or dslr file").hasArg()
            .withDescription("a rule (*.drl or *.dslr) file").isRequired().create("k");

    Option catDirectoryOpt = OptionBuilder.withArgName("cat directory").hasArg()
            .withDescription("directory with *.cat files").create("c");

    Option withoutSuperscriptOpt = OptionBuilder.withArgName("true|false").hasArg()
            .withDescription("use true to ignore superscript text in cells").create("ss");

    Option useCellValueOpt = OptionBuilder.withArgName("true|false").hasArg()
            .withDescription("use true to use cell values as text").create("v");

    Option outputDirectoryOpt = OptionBuilder.withArgName("output directory").hasArg()
            .withDescription("a directory for outputting results").create("o");

    Option debuggingModeOpt = OptionBuilder.withArgName("true|false").hasArg()
            .withDescription("use true to turn on debugging mode").create("m");

    Options options = new Options();

    options.addOption(inputExcelFileOpt);
    options.addOption(sheetIndexesOpt);/*from  ww w  . j a va2 s .c o m*/
    options.addOption(drlFileOpt);
    options.addOption(catDirectoryOpt);
    options.addOption(withoutSuperscriptOpt);
    options.addOption(useCellValueOpt);
    options.addOption(outputDirectoryOpt);
    options.addOption(debuggingModeOpt);

    CommandLineParser parser = new BasicParser();

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

        String inputExcelFileParam = cmd.getOptionValue(inputExcelFileOpt.getOpt());
        inputExcelFile = parseInputExcelFileParam(inputExcelFileParam);

        String sheetIndexesParam = cmd.getOptionValue(sheetIndexesOpt.getOpt());
        sheetIndexes = parseSheetIndexesParam(sheetIndexesParam);

        String drlFileParam = cmd.getOptionValue(drlFileOpt.getOpt());
        drlFile = parseDrlFileParam(drlFileParam);

        String catDirectoryParam = cmd.getOptionValue(catDirectoryOpt.getOpt());
        catDirectory = parseCatDirectoryParam(catDirectoryParam);

        String withoutSuperscriptParam = cmd.getOptionValue(withoutSuperscriptOpt.getOpt());
        withoutSuperscript = parseWithoutSuperscriptParam(withoutSuperscriptParam);

        String useCellValuParam = cmd.getOptionValue(useCellValueOpt.getOpt());
        useCellValue = parseUseCellValueParam(useCellValuParam);

        String outputDirectoryParam = cmd.getOptionValue(outputDirectoryOpt.getOpt());
        outputDirectory = parseOutputDirectoryParam(outputDirectoryParam);

        String debuggingModeParam = cmd.getOptionValue(debuggingModeOpt.getOpt());
        debuggingMode = parseDebuggingModeParam(debuggingModeParam);
    } catch (ParseException e) {
        e.printStackTrace();
        System.exit(0);
    }
}

From source file:scoutdoc.main.Main.java

private static void ensureNotSet(CommandLine cmd, Option option, Operation operation)
        throws MissingArgumentException {
    if (cmd.hasOption(option.getOpt())) {
        throw new MissingArgumentException("Source <" + option.getLongOpt() + "> is not allowed for the <"
                + operation.name() + "> operation.");
    }//  w w  w .j ava 2 s  . co  m
}

From source file:scoutdoc.main.Main.java

private static <T extends Enum<T>> List<T> readOptionEnum(CommandLine cmd, Option option, Class<T> c)
        throws MissingArgumentException {
    List<T> operations = Lists.newArrayList();
    for (String name : cmd.getOptionValues(option.getOpt())) {
        try {//from w ww  .ja v  a  2 s  . com
            T operation = Enum.valueOf(c, name);
            operations.add(operation);
        } catch (IllegalArgumentException e) {
            throw new MissingArgumentException(
                    "Unknown value '" + name + "' for '--" + option.getLongOpt() + "'");
        }
    }
    return operations;
}

From source file:scoutdoc.main.Main.java

private static List<Task> readTasks(CommandLine cmd, Option option) throws MissingArgumentException {
    List<Task> result = Lists.newArrayList();
    if (cmd.hasOption(option.getOpt())) {
        for (String name : cmd.getOptionValues(option.getOpt())) {
            try {
                Task task = TaskUtility.toTask(name);
                result.add(task);/*from  w w  w.ja v a2s  .com*/
            } catch (IOException e) {
                throw new MissingArgumentException("IOException for file '" + name + "' for '--"
                        + option.getLongOpt() + "' : " + e.getMessage());
            }
        }
    }
    return result;
}

From source file:scoutdoc.main.Main.java

private static void printHelpAndExit(Options options) {
    HelpFormatter helpFormatter = new HelpFormatter();
    helpFormatter.setWidth(200);/*www  .  j  a  v  a2 s  .  co m*/
    helpFormatter.setOptionComparator(new Comparator<Option>() {

        @Override
        public int compare(Option opt1, Option opt2) {
            return ComparisonChain.start()
                    .compare(opt1.getOpt(), opt2.getOpt(),
                            Ordering.explicit(HELP_ID, PROP_ID, SOURCE_TASKS_ID, SOURCE_ALL_PAGES_ID,
                                    SOURCE_LIST_ID, SOURCE_RECENT_CHANGES_ID, SOURCE_RSS_ID, SOURCE_FILTER_ID,
                                    OPERATION_ID, OUTPUT_CHECKSTYLE_ID, OUTPUT_DASHBOARD_ID))
                    .result();
        }
    });
    helpFormatter.printHelp("scoutdoc.main.Main", options);
    System.exit(1);
}

From source file:se.sics.ktoolbox.echo.StunEchoLauncher.java

private static void parseArgs(String[] args) {
    Options options = new Options();
    Option ping = new Option("ping", true, "ping target address");
    Option self = new Option("self", true, "public self ip or own nat address");
    options.addOption(ping);//from  w  ww  . ja va  2 s. c om
    options.addOption(self);
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException ex) {
        LOG.error("command line parsing error");
        System.exit(1);
    }

    if (cmd.hasOption(ping.getOpt())) {
        StunEchoLauncher.type = Type.PING;
        InetAddress ip = null;
        try {
            ip = InetAddress.getByName(cmd.getOptionValue(ping.getOpt()));
        } catch (UnknownHostException ex) {
            LOG.error("ping target binding error");
            System.exit(1);
        }
        StunEchoLauncher.pingTarget = new DecoratedAddress(new BasicAddress(ip, 34543, 1));
    } else {
        StunEchoLauncher.type = Type.PONG;
    }
    if (cmd.hasOption(self.getOpt())) {
        InetAddress ip = null;
        try {
            ip = InetAddress.getByName(cmd.getOptionValue(self.getOpt()));
        } catch (UnknownHostException ex) {
            LOG.error("self binding error");
            System.exit(1);
        }
        switch (StunEchoLauncher.type) {
        case PING:
            StunEchoLauncher.self = new DecoratedAddress(new BasicAddress(ip, 34543, 0));
            break;
        case PONG:
            StunEchoLauncher.self = new DecoratedAddress(new BasicAddress(ip, 34543, 1));
            break;
        }
    } else {
        LOG.error("missing self address");
        System.exit(1);
    }
}

From source file:singlepacketdump.Main.java

public void start(String args[]) throws DecoderException, ParseException {
    final byte[] packet;
    byte[] x = null;
    final Option packetOption = Option.builder("p").required().longOpt("packet")
            .desc("TS?hex").hasArg().type(String.class).build();

    Options opts = new Options();
    opts.addOption(packetOption);/*from w  w w. java2  s .  c  o  m*/
    try {

        CommandLineParser parser = new DefaultParser();
        CommandLine cl = parser.parse(opts, args);

        x = Hex.decodeHex(cl.getOptionValue(packetOption.getOpt()).toCharArray());

    } catch (DecoderException ex) {
        LOG.fatal("hex???????", ex);
        x = null;
        throw ex;
    } catch (ParseException ex) {
        LOG.fatal("??????", ex);
        x = null;
        throw ex;
    } finally {
        packet = x;
        if (packet == null) {
            this.printHelp(opts);
        }
    }

    TsPacket p = new TsPacket(packet);
    System.out.println(p);

}

From source file:singlesectiondump.Main.java

public void start(String args[]) throws DecoderException, ParseException {
    final byte[] section;
    byte[] x = null;
    final Option packetOption = Option.builder("s").required().longOpt("section")
            .desc("?hex").hasArg().type(String.class).build();

    Options opts = new Options();
    opts.addOption(packetOption);/*from  w w  w . j a v a 2 s.  co m*/
    try {

        CommandLineParser parser = new DefaultParser();
        CommandLine cl = parser.parse(opts, args);

        x = Hex.decodeHex(cl.getOptionValue(packetOption.getOpt()).toCharArray());

    } catch (DecoderException ex) {
        LOG.fatal("hex???????", ex);
        x = null;
        throw ex;
    } catch (ParseException ex) {
        LOG.fatal("??????", ex);
        x = null;
        throw ex;
    } finally {
        section = x;
        if (section == null) {
            this.printHelp(opts);
        }
    }

    Section s = new Section(section);
    System.out.println(s);

}