Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache Common CLI doesn't recognize options

I try to parse simple args using Common CLI but receive ParseException.

Here is my code:

@SuppressWarnings("static-access")
public class CmdParsingTest {
    private static final Options options;

    static {
        options = new Options();
        options.addOption(OptionBuilder.withLongOpt("schema-file")
                .withDescription("path to schema file")
                .hasArg()
                .withArgName("schemaFile")
                .create("source"));
        options.addOption( OptionBuilder.withLongOpt("state-url")
                .withDescription("state url")
                .hasArg()
                .withArgName("stateUrl")
                .create("url"));
        options.addOption( OptionBuilder.withLongOpt("update-number")
                .withDescription("update number to start from")
                .hasArg()
                .withArgName("updateNum")
                .create("update"));
        options.addOption(OptionBuilder.withLongOpt("result-file")
                .withDescription("use given file to save result")
                .hasArg()
                .withArgName("resultFile")
                .create("result"));
    }

    public static void main(String[] args) {
        args = new String[]{
                "-source /home/file/myfile.txt",
                "-url http://localhost/state",
                "-result result.txt"};
        // create the parser
        CommandLineParser parser = new BasicParser();
        try {
            // parse the command line arguments
            CommandLine cmd = parser.parse(options, args);
            //other cool code...    
        }
        catch( ParseException exp ) {
            System.err.println( "Parsing of command line args failed.  Reason: " + exp.getMessage() );
        }
    }
}

The result is:

Parsing of command line args failed. Reason: Unrecognized option: -source /home/file/myfile.txt

If I use args without a dash, than no exception is thrown, but cmd.hasOption("source") returns false.

P.S> Usage sample suggests using DefaultParser, but it will appear only in CLI 1.3 (according to 1.3 JavaDoc).

like image 968
Dragon Avatar asked Feb 16 '23 01:02

Dragon


1 Answers

Change

    args = new String[]{
            "-source /home/file/myfile.txt",
            "-url http://localhost/state",
            "-result result.txt"};

to

    args = new String[]{
            "-source", "/home/file/myfile.txt",
            "-url", "http://localhost/state",
            "-result", "result.txt"};

The second is how the JVM would package/pass command line args to your main method, and thus is what commons-cli is expecting.

like image 109
Keith Avatar answered Feb 18 '23 15:02

Keith