Example usage for org.apache.commons.cli GnuParser GnuParser

List of usage examples for org.apache.commons.cli GnuParser GnuParser

Introduction

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

Prototype

GnuParser

Source Link

Usage

From source file:jlite.cli.JobMatch.java

public static void main(String[] args) {
    System.out.println(); // extra line
    CommandLineParser parser = new GnuParser();
    Options options = setupOptions();/*from  w w w .  j a v a  2  s.  co m*/
    HelpFormatter helpFormatter = new HelpFormatter();
    helpFormatter.setSyntaxPrefix("Usage: ");
    CommandLine line = null;
    try {
        line = parser.parse(options, args);
        if (line.hasOption("help")) {
            helpFormatter.printHelp(100, COMMAND, "\noptions:", options, "\n" + CLI.FOOTER, false);
            System.out.println(); // extra line
            System.exit(0);
        } else {
            if (line.hasOption("xml")) {
                System.out.println("<output>");
            }
            String[] remArgs = line.getArgs();
            if (remArgs.length == 1) {
                run(remArgs[0], line);
            } else if (remArgs.length == 0) {
                throw new MissingArgumentException("Missing required argument: <jdl_file>");
            } else {
                throw new UnrecognizedOptionException("Unrecognized extra arguments");
            }
        }
    } catch (ParseException e) {
        System.err.println(e.getMessage() + "\n");
        helpFormatter.printHelp(100, COMMAND, "\noptions:", options, "\n" + CLI.FOOTER, false);
        System.out.println(); // extra line
        System.exit(-1);
    } catch (Exception e) {
        if (line.hasOption("xml")) {
            System.out.println("<error>" + e.getMessage() + "</error>");
        } else {
            System.err.println(e.getMessage());
        }
    } finally {
        if (line.hasOption("xml")) {
            System.out.println("</output>");
        }
    }
    System.out.println(); // extra line
}

From source file:com.ibm.rdf.store.sparql11.DB2RDFQuery.java

public static void main(String[] args) {
    Options options = new Options();

    try {/*from  w w w . j  av  a2  s  .  co m*/
        // create Options object
        options.addOption("jdbcurl", true, "jdbc url");
        options.addOption("schema", true, "schema name");
        options.addOption("kb", true, "knowledge base");
        options.addOption("username", true, "db user name");
        options.addOption("password", true, "db password");
        options.addOption("queryFile", true, "query file");
        options.addOption("defaultUnionGraph", false, "default Union Graph semantics");

        CommandLineParser parser = new GnuParser();
        CommandLine cmd = parser.parse(options, args);
        boolean defUnion = cmd.hasOption("defaultUnionGraph")
                ? Boolean.parseBoolean(cmd.getOptionValue("defaultUnionGraph"))
                : false;
        DB2TestData data = new DB2TestData(cmd.getOptionValue("jdbcurl"), cmd.getOptionValue("kb"),
                cmd.getOptionValue("username"), cmd.getOptionValue("password"),
                cmd.getOptionValue("schemaName"), defUnion);

        DB2RDFQuery q = new DB2RDFQuery(new DB2Engine(), data);
        q.executeQuery(cmd.getOptionValue("queryFile"));
    } catch (Exception e) {
        e.printStackTrace();
        HelpFormatter help = new HelpFormatter();
        help.printHelp("DB2RDFQuery", options);
    }
}

From source file:jlite.cli.ProxyInfo.java

public static void main(String[] args) {
    System.out.println(); // extra line
    CommandLineParser parser = new GnuParser();
    Options options = setupOptions();//  ww w .  java 2s.c o  m
    HelpFormatter helpFormatter = new HelpFormatter();
    helpFormatter.setSyntaxPrefix("Usage: ");
    CommandLine line = null;
    try {
        line = parser.parse(options, args);
        if (line.hasOption("help")) {
            helpFormatter.printHelp(100, COMMAND, "\noptions:", options, "\n" + CLI.FOOTER + "\n", false);
            System.out.println(); // extra line
            System.exit(0);
        }
        if (line.hasOption("xml")) {
            System.out.println("<output>");
        }
        run(line);
    } catch (ParseException e) {
        System.err.println(e.getMessage() + "\n");
        helpFormatter.printHelp(100, COMMAND, "\noptions:", options, "\n" + CLI.FOOTER + "\n", false);
        System.out.println(); // extra line
        System.exit(-1);
    } catch (Exception e) {
        if (line.hasOption("xml")) {
            System.out.println("<error>" + e.getMessage() + "</error>");
        } else {
            System.err.println(e.getMessage());
        }
    } finally {
        if (line.hasOption("xml")) {
            System.out.println("</output>");
        }
    }
    System.out.println(); // extra line
}

From source file:com.ingby.socbox.bischeck.migration.Properties2ServerProperties.java

public static void main(String[] args) throws Exception {
    CommandLineParser parser = new GnuParser();
    CommandLine line = null;/* w  w  w .  ja v  a2 s  . c o  m*/
    // create the Options
    Options options = new Options();
    options.addOption("u", "usage", false, "show usage.");
    options.addOption("v", "verbose", false, "verbose - do not write to files");
    options.addOption("s", "source", true, "directory old properties.xml is located");
    options.addOption("d", "destination", true, "directory where the new xml files while be stored");

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

    } catch (org.apache.commons.cli.ParseException e) {
        System.out.println("Command parse error:" + e.getMessage());
        Util.ShellExit(1);
    }

    if (line.hasOption("usage")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("DB2XMLConvert", options);
        Util.ShellExit(0);
    }

    Properties2ServerProperties converter = new Properties2ServerProperties();

    if (line.hasOption("source")) {
        String sourcedir = line.getOptionValue("source");
        String destdir = ".";
        if (line.hasOption("destination")) {
            destdir = line.getOptionValue("destination");
        }

        converter.createXMLServerProperties(sourcedir, destdir);

    }
}

From source file:com.benasmussen.tools.testeditor.ExtractorCLI.java

public static void main(String[] args) throws Exception {
    HelpFormatter formatter = new HelpFormatter();

    // cli options
    Options options = new Options();
    options.addOption(CMD_OPT_INPUT, true, "Input file");
    // options.addOption(CMD_OPT_OUTPUT, true, "Output file");

    try {//w w  w  .jav  a2s . com

        // evaluate command line options
        CommandLineParser parser = new GnuParser();
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption(CMD_OPT_INPUT)) {
            // option value
            String optionValue = cmd.getOptionValue(CMD_OPT_INPUT);

            // input file
            File inputFile = new File(optionValue);

            // id extractor
            IdExtractor idExtractor = new IdExtractor(inputFile);
            Vector<Vector> data = idExtractor.parse();

            // // TODO implement output folder
            // if (cmd.hasOption(CMD_OPT_OUTPUT))
            // {
            // // file output
            // throw new Exception("Not implemented");
            // }
            // else
            // {
            // console output
            System.out.println("Id;Value");
            for (Vector vector : data) {
                StringBuilder sb = new StringBuilder();
                if (vector.size() >= 1) {
                    sb.append(vector.get(0));
                }
                sb.append(";");
                if (vector.size() >= 2) {
                    sb.append(vector.get(1));
                }
                System.out.println(sb.toString());
            }
            // }
        } else {
            throw new IllegalArgumentException();
        }

    } catch (ParseException e) {
        formatter.printHelp("ExtractorCLI", options);
    } catch (IllegalArgumentException e) {
        formatter.printHelp("ExtractorCLI", options);
    }
}

From source file:cc.wikitools.lucene.FindWikipediaArticleId.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(/*from   w  w  w  . j ava  2s.c  o  m*/
            OptionBuilder.withArgName("path").hasArg().withDescription("index location").create(INDEX_OPTION));
    options.addOption(
            OptionBuilder.withArgName("string").hasArg().withDescription("article title").create(TITLE_OPTION));

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();
    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(TITLE_OPTION) || !cmdline.hasOption(INDEX_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(FindWikipediaArticleId.class.getName(), options);
        System.exit(-1);
    }

    File indexLocation = new File(cmdline.getOptionValue(INDEX_OPTION));
    if (!indexLocation.exists()) {
        System.err.println("Error: " + indexLocation + " does not exist!");
        System.exit(-1);
    }

    String title = cmdline.getOptionValue(TITLE_OPTION);

    PrintStream out = new PrintStream(System.out, true, "UTF-8");

    WikipediaSearcher searcher = new WikipediaSearcher(indexLocation);
    int id = searcher.getArticleId(title);

    out.println(title + ": id = " + id);

    searcher.close();
    out.close();
}

From source file:com.mosso.client.cloudfiles.sample.FilesCopy.java

public static void main(String args[]) throws NoSuchAlgorithmException, FilesException {
    //Build the command line options
    Options options = addCommandLineOptions();

    if (args.length <= 0)
        printHelp(options);/*w w  w. java2s  .  c o  m*/

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

        if (line.hasOption("help"))
            printHelp(options);

        if (line.hasOption("file") && line.hasOption("folder")) {
            System.err.println("Can not use both -file and -folder on the command line at the same time.");
            System.exit(-1);
        } //if (line.hasOption("file") && line.hasOption("folder"))

        if (line.hasOption("download")) {
            if (line.hasOption("folder")) {
                String localFolder = FilenameUtils.normalize(line.getOptionValue("folder"));
                String containerName = null;
                if (StringUtils.isNotBlank(localFolder)) {
                    File localFolderObj = new File(localFolder);
                    if (localFolderObj.exists() && localFolderObj.isDirectory()) {
                        if (line.hasOption("container")) {
                            containerName = line.getOptionValue("container");
                            if (!StringUtils.isNotBlank(containerName)) {
                                System.err.println(
                                        "You must provide a valid value for the  Container to upload to !");
                                System.exit(-1);
                            } //if (!StringUtils.isNotBlank(ontainerName))                            
                        } else {
                            System.err.println(
                                    "You must provide the -container for a copy operation to work as expected.");
                            System.exit(-1);
                        }

                        System.out.println("Downloading all objects from: " + containerName
                                + " to local folder: " + localFolder);

                        getContainerObjects(localFolderObj, containerName);

                    } else {
                        if (!localFolderObj.exists()) {
                            System.err.println("The local folder: " + localFolder
                                    + " does not exist.  Create it first and then run this command.");
                        }

                        if (!localFolderObj.isDirectory()) {
                            System.err.println(
                                    "The local folder name supplied : " + localFolder + " is not a folder !");
                        }

                        System.exit(-1);
                    }
                }
            }
            System.exit(0);
        } //if (line.hasOption("download"))

        if (line.hasOption("folder")) {
            String containerName = null;
            String folderPath = null;

            if (line.hasOption("container")) {
                containerName = line.getOptionValue("container");
                if (!StringUtils.isNotBlank(containerName)) {
                    System.err.println("You must provide a valid value for the  Container to upload to !");
                    System.exit(-1);
                } //if (!StringUtils.isNotBlank(containerName))

            } else {
                System.err.println("You must provide the -container for a copy operation to work as expected.");
                System.exit(-1);
            }

            folderPath = line.getOptionValue("folder");
            if (StringUtils.isNotBlank(folderPath)) {
                File folder = new File(FilenameUtils.normalize(folderPath));
                if (folder.isDirectory()) {
                    if (line.hasOption("z")) {
                        System.out.println("Zipping: " + folderPath);
                        System.out.println("Nested folders are ignored !");

                        File zipedFolder = zipFolder(folder);
                        String mimeType = FilesConstants.getMimetype(ZIPEXTENSION);
                        copyToCreateContainerIfNeeded(zipedFolder, mimeType, containerName);
                    } else {
                        File[] files = folder.listFiles();
                        for (File f : files) {
                            String mimeType = FilesConstants
                                    .getMimetype(FilenameUtils.getExtension(f.getName()));
                            System.out.println("Uploading :" + f.getName() + " to " + folder.getName());
                            copyToCreateContainerIfNeeded(f, mimeType, containerName);
                            System.out.println(
                                    "Upload :" + f.getName() + " to " + folder.getName() + " completed.");
                        }
                    }
                } else {
                    System.err.println("You must provide a valid folder value for the -folder option !");
                    System.err.println("The value provided is: " + FilenameUtils.normalize(folderPath));
                    System.exit(-1);
                }

            }
        } //if (line.hasOption("folder"))

        if (line.hasOption("file")) {
            String containerName = null;
            String fileNamePath = null;

            if (line.hasOption("container")) {
                containerName = line.getOptionValue("container");
                if (!StringUtils.isNotBlank(containerName) || containerName.indexOf('/') != -1) {
                    System.err.println("You must provide a valid value for the  Container to upload to !");
                    System.exit(-1);
                } //if (!StringUtils.isNotBlank(containerName))
            } else {
                System.err.println("You must provide the -container for a copy operation to work as expected.");
                System.exit(-1);
            }

            fileNamePath = line.getOptionValue("file");
            if (StringUtils.isNotBlank(fileNamePath)) {
                String fileName = FilenameUtils.normalize(fileNamePath);
                String fileExt = FilenameUtils.getExtension(fileNamePath);
                String mimeType = FilesConstants.getMimetype(fileExt);
                File file = new File(fileName);

                if (line.hasOption("z")) {
                    logger.info("Zipping " + fileName);
                    if (!file.isDirectory()) {
                        File zippedFile = zipFile(file);
                        mimeType = FilesConstants.getMimetype(ZIPEXTENSION);
                        copyTo(zippedFile, mimeType, containerName);
                        zippedFile.delete();
                    }

                } //if (line.hasOption("z"))
                else {

                    logger.info("Uploading " + fileName + ".");
                    if (!file.isDirectory())
                        copyTo(file, mimeType, containerName);
                    else {
                        System.err.println(
                                "The path you provided is a folder.  For uploading folders use the -folder option.");
                        System.exit(-1);
                    }
                }
            } //if (StringUtils.isNotBlank(file))
            else {
                System.err.println("You must provide a valid value for the file to upload !");
                System.exit(-1);
            }
        } //if (line.hasOption("file"))
    } //end try        
    catch (ParseException err) {
        System.err.println("Please see the logs for more details. Error Message: " + err.getMessage());
        err.printStackTrace(System.err);
    } //catch( ParseException err )
    catch (FilesAuthorizationException err) {
        logger.fatal("FilesAuthorizationException : Failed to login to your  account !" + err);
        System.err.println("Please see the logs for more details. Error Message: " + err.getMessage());
    } //catch (FilesAuthorizationException err)

    catch (IOException err) {
        logger.fatal("IOException : " + err);
        System.err.println("Please see the logs for more details. Error Message: " + err.getMessage());
    } //catch ( IOException err)
}

From source file:au.id.hazelwood.xmltvguidebuilder.runner.Main.java

public static void main(String[] args) throws Exception {
    SLF4JBridgeHandler.install();//from  ww w. ja  va  2  s .  c  o  m

    Options options = new Options();
    options.addOption(createOptionWithArg("config", true, "file", File.class, "Config file location"));
    options.addOption(createOptionWithArg("out", true, "file", File.class, "Output file name"));

    try {
        CommandLineParser parser = new GnuParser();
        CommandLine line = parser.parse(options, args);
        App app = new App();
        app.run((File) line.getParsedOptionValue("config"), (File) line.getParsedOptionValue("out"));
    } catch (ParseException exp) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Main", options, true);
    }
}

From source file:list.Main.java

public static void main(String[] args) throws Exception {
    Options options = getOptions();/*from   w  w  w  .ja  va 2s.  co  m*/
    try {

        CommandLineParser parser = new GnuParser();

        CommandLine line = parser.parse(options, args);
        File dir = new File(line.getOptionValue("dir", "."));
        Collection files = ListFile.list(dir);
        System.out.println("listing files in " + dir);
        for (Iterator it = files.iterator(); it.hasNext();) {
            System.out.println("\t" + it.next() + "\n");
        }
    } catch (ParseException exp) {
        // oops, something went wrong
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());

        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("list", options);
    }
}

From source file:com.rapleaf.hank.cli.AddRingGroup.java

public static void main(String[] args) throws IOException, ParseException, InvalidConfigurationException {
    Options options = new Options();
    options.addOption("r", "ring-group", true, "the name of the ring group to be created");
    options.addOption("d", "domain-group", true,
            "the name of the domain group that this ring group will be linked to");
    options.addOption("c", "config", true,
            "path of a valid config file with coordinator connection information");
    try {/*from  w  w w  .  j av a 2 s.  c  o m*/
        CommandLine line = new GnuParser().parse(options, args);
        CommandLineChecker.check(line, options, new String[] { "config", "ring-group", "domain-group" },
                AddRingGroup.class);
        ClientConfigurator configurator = new YamlClientConfigurator(line.getOptionValue("config"));
        addRingGroup(configurator, line.getOptionValue("ring-group"), line.getOptionValue("domain-group"));
    } catch (ParseException e) {
        new HelpFormatter().printHelp("add_domain", options);
        throw e;
    }
}