When I pass more than three options using apache commons CLI..the result is displaying as NULL for third option

349 views Asked by At

When I pass more than three options in cmd..the result is displaying as NULL

 package main.java;
import org.apache.commons.cli.*;

public class cli {

    public static void main(String[] args) throws Exception {
         Options options = new Options();
     Option token = new Option("t", "token", true, "token");
     token.setRequired(true);
     options.addOption(token);

     Option projectname = new Option("p", "projectname", true, "project");
     projectname.setRequired(true);
     options.addOption(projectname);
     
     Option branch = new Option("b", "branchname", true, "branch");
     branch.setRequired(true);
     options.addOption(branch);
     
     Option pullreq = new Option("PR", "pullreq", true, "pullreq");
     pullreq.setRequired(true);
     options.addOption(pullreq);
     CommandLineParser parser = new DefaultParser();
     HelpFormatter formatter = new HelpFormatter();
     CommandLine cmd = null;

     try {
         cmd = parser.parse(options, args);
     } catch (ParseException e) {
         System.out.println(e.getMessage());
         formatter.printHelp("utility-name", options);

         System.exit(1);
     }

     String token1 = cmd.getOptionValue("token");
     String projectname1 = cmd.getOptionValue("projectname");
     String branch1 = cmd.getOptionValue("branch");
     String pullreq1 = cmd.getOptionValue("pullreq");
     
   /*if(pullreq != null){
         String pullreq1 = cmd.getOptionValue("pullreq");
         System.out.println(pullreq1);
     }
     */
     System.out.println(token1);
     System.out.println(projectname1);
     System.out.println(branch1);

 }
    }

when I built it, the third and 4th option values are taken as null. java -jar testreport-1.0.2-SNAPSHOT.jar -t token -p project -b branch -PR pullreq

token project null

1

There are 1 answers

3
gthanop On BEST ANSWER

The problem lies in this line:

String branch1 = cmd.getOptionValue("branch");

You simply forgot that the corresponding option, as given to Options instance, has a long option property of "branchname" instead of only "branch". So you can simply change it to:

String branch1 = cmd.getOptionValue("branchname");

and it will work. At least for me it did.