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.cloudera.csd.tools.MetricTools.java

public static void main(String[] args) throws Exception {
    CommandLineParser parser = new DefaultParser();
    try {// w w  w  . ja  va 2s  .co m
        CommandLine cmdLine = parser.parse(OPTIONS, args);
        if (!cmdLine.getArgList().isEmpty()) {
            throw new ParseException("Unexpected extra arguments: " + cmdLine.getArgList());
        }
        Main main = new Main(cmdLine);
        main.run();
    } catch (ParseException ex) {
        IOUtils.write("Error: " + ex.getMessage() + "\n", System.err);
        printUsageMessage(System.err);
        System.exit(1);
    }
}

From source file:com.cyberway.issue.io.Arc2Warc.java

/**
 * Command-line interface to Arc2Warc./*ww  w . j  ava 2 s .  c om*/
 *
 * @param args Command-line arguments.
 * @throws ParseException Failed parse of the command line.
 * @throws IOException
 * @throws java.text.ParseException
 */
public static void main(String[] args) throws ParseException, IOException, java.text.ParseException {
    Options options = new Options();
    options.addOption(new Option("h", "help", false, "Prints this message and exits."));
    options.addOption(new Option("f", "force", false, "Force overwrite of target file."));
    PosixParser parser = new PosixParser();
    CommandLine cmdline = parser.parse(options, args, false);
    List cmdlineArgs = cmdline.getArgList();
    Option[] cmdlineOptions = cmdline.getOptions();
    HelpFormatter formatter = new HelpFormatter();

    // If no args, print help.
    if (cmdlineArgs.size() <= 0) {
        usage(formatter, options, 0);
    }

    // Now look at options passed.
    boolean force = false;
    for (int i = 0; i < cmdlineOptions.length; i++) {
        switch (cmdlineOptions[i].getId()) {
        case 'h':
            usage(formatter, options, 0);
            break;

        case 'f':
            force = true;
            break;

        default:
            throw new RuntimeException("Unexpected option: " + +cmdlineOptions[i].getId());
        }
    }

    // If no args, print help.
    if (cmdlineArgs.size() != 2) {
        usage(formatter, options, 0);
    }
    (new Arc2Warc()).transform(new File(cmdlineArgs.get(0).toString()), new File(cmdlineArgs.get(1).toString()),
            force);
}

From source file:com.github.thesmartenergy.sparql.generate.generator.CMDGenerator.java

public static void main(String[] args) {

    List<String> formats = Arrays.asList("TTL", "TURTLE", "NTRIPLES", "TRIG", "RDFXML", "JSONLD");

    try {//from ww w  .  j  a  v  a 2  s  .co m
        CommandLine cl = CMDConfigurations.parseArguments(args);

        String query = "";
        String outputFormat = "TTL";

        if (cl.getArgList().size() == 0) {
            CMDConfigurations.displayHelp();
            return;
        }

        fileManager = FileManager.makeGlobal();
        if (cl.hasOption('l')) {
            Enumeration<String> loggers = LogManager.getLogManager().getLoggerNames();
            while (loggers.hasMoreElements()) {
                java.util.logging.Logger element = LogManager.getLogManager().getLogger(loggers.nextElement());
                element.setLevel(Level.OFF);
            }
            Logger.getRootLogger().setLevel(org.apache.log4j.Level.OFF);

        }
        LOG = Logger.getLogger(CMDGenerator.class);

        //get query file path
        //check if the file exists
        if (cl.hasOption("qf")) {
            String file_path = cl.getOptionValue("qf");
            File f = new File(file_path);
            if (f.exists() && !f.isDirectory()) {
                FileInputStream fisTargetFile = new FileInputStream(f);
                query = IOUtils.toString(fisTargetFile, "UTF-8");
                LOG.debug("\n\nRead SPARQL-Generate Query ..\n" + query + "\n\n");
            } else {
                LOG.error("File " + file_path + " not found.");
            }
        }

        //get query string
        if (cl.hasOption("qs")) {
            query = cl.getOptionValue("qs");
        }
        System.out.println("Query:" + query);

        //get and validate the output format
        if (cl.hasOption("f")) {
            String format = cl.getOptionValue("f");
            if (formats.contains(format)) {
                outputFormat = format;
            } else {
                LOG.error("Invalid output format," + cl.getOptionProperties("f").getProperty("description"));
                return;
            }
        }

        Model configurationModel = null;
        String conf = "";
        if (cl.hasOption("c")) {
            conf = cl.getOptionValue("c");
            configurationModel = ProcessQuery.generateConfiguration(conf);
        }

        String output = ProcessQuery.process(query, conf, outputFormat);
        System.out.println(output);

    } catch (org.apache.commons.cli.ParseException ex) {
        LOG.error(ex);
    } catch (FileNotFoundException ex) {
        LOG.error(ex);
    } catch (IOException ex) {
        LOG.error(ex);
    }

}

From source file:jena.RuleMap.java

/**
 * General command line utility to process one RDF file into another
 * by application of a set of forward chaining rules. 
 * <pre>// www. ja v a  2 s. c o  m
 * Usage:  RuleMap [-il inlang] [-ol outlang] -d infile rulefile
 * </pre>
 */
public static void main(String[] args) {
    try {

        // Parse the command line
        String usage = "Usage:  RuleMap [-il inlang] [-ol outlang] [-d] rulefile infile (- for stdin)";
        final CommandLineParser parser = new DefaultParser();
        Options options = new Options().addOption("il", "inputLang", true, "input language")
                .addOption("ol", "outputLang", true, "output language").addOption("d", "Deductions only?");
        CommandLine cl = parser.parse(options, args);
        final List<String> filenameArgs = cl.getArgList();
        if (filenameArgs.size() != 2) {
            System.err.println(usage);
            System.exit(1);
        }

        String inLang = cl.getOptionValue("inputLang");
        String fname = filenameArgs.get(1);
        Model inModel = null;
        if (fname.equals("-")) {
            inModel = ModelFactory.createDefaultModel();
            inModel.read(System.in, null, inLang);
        } else {
            inModel = FileManager.get().loadModel(fname, inLang);
        }

        String outLang = cl.hasOption("outputLang") ? cl.getOptionValue("outputLang") : "N3";

        boolean deductionsOnly = cl.hasOption('d');

        // Fetch the rule set and create the reasoner
        BuiltinRegistry.theRegistry.register(new Deduce());
        Map<String, String> prefixes = new HashMap<>();
        List<Rule> rules = loadRules(filenameArgs.get(0), prefixes);
        Reasoner reasoner = new GenericRuleReasoner(rules);

        // Process
        InfModel infModel = ModelFactory.createInfModel(reasoner, inModel);
        infModel.prepare();
        infModel.setNsPrefixes(prefixes);

        // Output
        try (PrintWriter writer = new PrintWriter(System.out)) {
            if (deductionsOnly) {
                Model deductions = infModel.getDeductionsModel();
                deductions.setNsPrefixes(prefixes);
                deductions.setNsPrefixes(inModel);
                deductions.write(writer, outLang);
            } else {
                infModel.write(writer, outLang);
            }
        }
    } catch (Throwable t) {
        System.err.println("An error occured: \n" + t);
        t.printStackTrace();
    }
}

From source file:com.cyberway.issue.io.Warc2Arc.java

/**
 * Command-line interface to Arc2Warc./*from   w  w  w .  j  a v  a  2 s.  c  o m*/
 *
 * @param args Command-line arguments.
 * @throws ParseException Failed parse of the command line.
 * @throws IOException
 * @throws java.text.ParseException
 */
public static void main(String[] args) throws ParseException, IOException, java.text.ParseException {
    Options options = new Options();
    options.addOption(new Option("h", "help", false, "Prints this message and exits."));
    options.addOption(new Option("f", "force", false, "Force overwrite of target file."));
    options.addOption(
            new Option("p", "prefix", true, "Prefix to use on created ARC files, else uses default."));
    options.addOption(
            new Option("s", "suffix", true, "Suffix to use on created ARC files, else uses default."));
    PosixParser parser = new PosixParser();
    CommandLine cmdline = parser.parse(options, args, false);
    List cmdlineArgs = cmdline.getArgList();
    Option[] cmdlineOptions = cmdline.getOptions();
    HelpFormatter formatter = new HelpFormatter();

    // If no args, print help.
    if (cmdlineArgs.size() < 0) {
        usage(formatter, options, 0);
    }

    // Now look at options passed.
    boolean force = false;
    String prefix = "WARC2ARC";
    String suffix = null;
    for (int i = 0; i < cmdlineOptions.length; i++) {
        switch (cmdlineOptions[i].getId()) {
        case 'h':
            usage(formatter, options, 0);
            break;

        case 'f':
            force = true;
            break;

        case 'p':
            prefix = cmdlineOptions[i].getValue();
            break;

        case 's':
            suffix = cmdlineOptions[i].getValue();
            break;

        default:
            throw new RuntimeException("Unexpected option: " + +cmdlineOptions[i].getId());
        }
    }

    // If no args, print help.
    if (cmdlineArgs.size() != 2) {
        usage(formatter, options, 0);
    }
    (new Warc2Arc()).transform(new File(cmdlineArgs.get(0).toString()), new File(cmdlineArgs.get(1).toString()),
            prefix, suffix, force);
}

From source file:hisqisnoten.HisqisNoten.java

public static void main(String[] args) {
    options = new Options();
    options.addOption("h", "help", false, "this help");
    options.addOption("u", "user", true, "username for hisqis");
    options.addOption("p", "pass", true, "password for hisqis");
    options.addOption("c", "console", false, "console mode instead of gui mode");

    CommandLineParser parser = new PosixParser();

    try {/*from w ww . jav  a2s.c o  m*/
        CommandLine cmdline = parser.parse(options, args);

        if (cmdline.hasOption("help")) {
            printHelp();
            System.exit(0);
        }

        if (cmdline.getArgList().size() != 0) {
            System.err.println("Please use the new commandline options.");
            System.out.println();

            printHelp();
            System.exit(1);
        }

        HisqisSettings settings = null;
        HisqisSettings.genConfigPath();

        for (File configpath : HisqisSettings.configpath) {
            if (configpath.exists() && configpath.canRead()) {
                settings = HisqisSettingsReader.loadDocument(configpath);

                if (settings != null) {
                    break;
                }
            }
        }

        if (settings == null) {
            settings = new HisqisSettings();
        }

        String user = cmdline.getOptionValue("user", null);
        String pass = cmdline.getOptionValue("pass", null);

        if (user != null) {
            settings.username = user;
        }
        if (pass != null) {
            settings.password = pass;
        }

        if (cmdline.hasOption("console")) {
            new HisqisConsole(settings);
        } else {
            new HisqisGUI(settings);
        }
    } catch (ParseException e) {
        printHelp();
    }
}

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   www. j a  va 2 s.c om*/
    }

    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()));
    }
}

From source file:com.cyberway.issue.crawler.extractor.ExtractorTool.java

public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(new Option("h", "help", false, "Prints this message and exits."));
    StringBuffer defaultExtractors = new StringBuffer();
    for (int i = 0; i < DEFAULT_EXTRACTORS.length; i++) {
        if (i > 0) {
            defaultExtractors.append(", ");
        }/*from w  w w  .j  a v a  2 s  .c o m*/
        defaultExtractors.append(DEFAULT_EXTRACTORS[i]);
    }
    options.addOption(new Option("e", "extractor", true,
            "List of comma-separated extractor class names. " + "Run in order listed. "
                    + "If no extractors listed, runs following: " + defaultExtractors.toString() + "."));
    options.addOption(
            new Option("s", "scratch", true, "Directory to write scratch files to. Default: '/tmp'."));
    PosixParser parser = new PosixParser();
    CommandLine cmdline = parser.parse(options, args, false);
    List cmdlineArgs = cmdline.getArgList();
    Option[] cmdlineOptions = cmdline.getOptions();
    HelpFormatter formatter = new HelpFormatter();
    // If no args, print help.
    if (cmdlineArgs.size() <= 0) {
        usage(formatter, options, 0);
    }

    // Now look at options passed.
    String[] extractors = DEFAULT_EXTRACTORS;
    String scratch = null;
    for (int i = 0; i < cmdlineOptions.length; i++) {
        switch (cmdlineOptions[i].getId()) {
        case 'h':
            usage(formatter, options, 0);
            break;

        case 'e':
            String value = cmdlineOptions[i].getValue();
            if (value == null || value.length() <= 0) {
                // Allow saying NO extractors so we can see
                // how much it costs just reading through
                // ARCs.
                extractors = new String[0];
            } else {
                extractors = value.split(",");
            }
            break;

        case 's':
            scratch = cmdlineOptions[i].getValue();
            break;

        default:
            throw new RuntimeException("Unexpected option: " + +cmdlineOptions[i].getId());
        }
    }

    ExtractorTool tool = new ExtractorTool(extractors, scratch);
    for (Iterator i = cmdlineArgs.iterator(); i.hasNext();) {
        tool.extract((String) i.next());
    }
}

From source file:com.nexmo.client.examples.TestVoiceCall.java

public static void main(String[] argv) throws Exception {
    Options options = new Options().addOption("v", "Verbosity")
            .addOption("f", "from", true, "Phone number to call from")
            .addOption("t", "to", true, "Phone number to call")
            .addOption("h", "webhook", true, "URL to call for instructions");
    CommandLineParser parser = new DefaultParser();

    CommandLine cli;
    try {// w  w w . j a  va2s. c  o m
        cli = parser.parse(options, argv);
    } catch (ParseException exc) {
        System.err.println("Parsing failed: " + exc.getMessage());
        System.exit(128);
        return;
    }

    Queue<String> args = new LinkedList<String>(cli.getArgList());
    String from = cli.getOptionValue("f");
    String to = cli.getOptionValue("t");
    System.out.println("From: " + from);
    System.out.println("To: " + to);

    NexmoClient client = new NexmoClient(new JWTAuthMethod("951614e0-eec4-4087-a6b1-3f4c2f169cb0",
            FileSystems.getDefault().getPath("valid_application_key.pem")));
    client.getVoiceClient().createCall(
            new Call(to, from, "https://nexmo-community.github.io/ncco-examples/first_call_talk.json"));
}

From source file:com.puppycrawl.tools.checkstyle.JavadocPropertiesGenerator.java

/**
 * TokenTypes.properties generator entry point.
 * @param args the command line arguments
 * @throws CheckstyleException if parser or lexer failed or if there is an IO problem
 * @throws ParseException if the command line can not be passed
 **//*from ww w.ja v  a 2s .  c om*/
public static void main(String... args) throws CheckstyleException, ParseException {
    final CommandLine commandLine = parseCli(args);
    if (commandLine.getArgList().size() == 1) {
        final File inputFile = new File(commandLine.getArgList().get(0));
        final File outputFile = new File(commandLine.getOptionValue(OPTION_DEST_FILE));
        writePropertiesFile(inputFile, outputFile);
    } else {
        printUsage();
    }
}