/**
   * Parse the arguments according to the specified options and properties.
   *
   * @param options the specified Options
   * @param arguments the command line arguments
   * @param properties command line option name-value pairs
   * @param stopAtNonOption if <tt>true</tt> an unrecognized argument stops the parsing and the
   *     remaining arguments are added to the {@link CommandLine}s args list. If <tt>false</tt> an
   *     unrecognized argument triggers a ParseException.
   * @return the list of atomic option and value tokens
   * @throws ParseException if there are any problems encountered while parsing the command line
   *     tokens.
   */
  public CommandLine parse(
      Options options, String[] arguments, Properties properties, boolean stopAtNonOption)
      throws ParseException {
    this.options = options;
    this.stopAtNonOption = stopAtNonOption;
    skipParsing = false;
    currentOption = null;
    expectedOpts = new ArrayList(options.getRequiredOptions());

    // clear the data from the groups
    for (OptionGroup group : options.getOptionGroups()) {
      group.setSelected(null);
    }

    cmd = new CommandLine();

    if (arguments != null) {
      for (String argument : arguments) {
        handleToken(argument);
      }
    }

    // check the arguments of the last option
    checkRequiredArgs();

    // add the default options
    handleProperties(properties);

    checkRequiredOptions();

    return cmd;
  }
Exemple #2
0
  public void test12210() {
    // create the main options object which will handle the first parameter
    Options mainOptions = new Options();
    // There can be 2 main exclusive options:  -exec|-rep

    // Therefore, place them in an option group

    String[] argv = new String[] {"-exec", "-exec_opt1", "-exec_opt2"};
    OptionGroup grp = new OptionGroup();

    grp.addOption(new Option("exec", false, "description for this option"));

    grp.addOption(new Option("rep", false, "description for this option"));

    mainOptions.addOptionGroup(grp);

    // for the exec option, there are 2 options...
    Options execOptions = new Options();
    execOptions.addOption("exec_opt1", false, " desc");
    execOptions.addOption("exec_opt2", false, " desc");

    // similarly, for rep there are 2 options...
    Options repOptions = new Options();
    repOptions.addOption("repopto", false, "desc");
    repOptions.addOption("repoptt", false, "desc");

    // create the parser
    GnuParser parser = new GnuParser();

    // finally, parse the arguments:

    // first parse the main options to see what the user has specified
    // We set stopAtNonOption to true so it does not touch the remaining
    // options
    try {
      CommandLine cmd = parser.parse(mainOptions, argv, true);
      // get the remaining options...
      argv = cmd.getArgs();

      if (cmd.hasOption("exec")) {
        cmd = parser.parse(execOptions, argv, false);
        // process the exec_op1 and exec_opt2...
        assertTrue(cmd.hasOption("exec_opt1"));
        assertTrue(cmd.hasOption("exec_opt2"));
      } else if (cmd.hasOption("rep")) {
        cmd = parser.parse(repOptions, argv, false);
        // process the rep_op1 and rep_opt2...
      } else {
        fail("exec option not found");
      }
    } catch (ParseException exp) {
      fail("Unexpected exception: " + exp.getMessage());
    }
  }
  /**
   * Removes the option or its group from the list of expected elements.
   *
   * @param option
   */
  private void updateRequiredOptions(Option option) throws AlreadySelectedException {
    if (option.isRequired()) {
      expectedOpts.remove(option.getKey());
    }

    // if the option is in an OptionGroup make that option the selected option of the group
    if (options.getOptionGroup(option) != null) {
      OptionGroup group = options.getOptionGroup(option);

      if (group.isRequired()) {
        expectedOpts.remove(group);
      }

      group.setSelected(option);
    }
  }
 private void printOptionContainer(OptionContainer container, String groupChain, StringBuffer sb) {
   if (container instanceof OptionGroup) {
     OptionGroup group = (OptionGroup) container;
     String newChain = groupChain + (groupChain.isEmpty() ? "" : groupSeperator) + group.getName();
     sb.append(newLine);
     //			sb.append(newChain);
     //			sb.append(" -- ");
     sb.append(group.getDescription());
     sb.append(":");
     sb.append(newLine);
     for (OptionContainer child : group.getChildren()) {
       printOptionContainer(child, newChain, sb);
     }
   } else // actual option
   {
     sb.append(printOption((Option) container));
     sb.append(newLine);
   }
 }
  /**
   * Sets the values of Options using the values in <code>properties</code>.
   *
   * @param properties The value properties to be processed.
   */
  private void handleProperties(Properties properties) throws ParseException {
    if (properties == null) {
      return;
    }

    for (Enumeration<?> e = properties.propertyNames(); e.hasMoreElements(); ) {
      String option = e.nextElement().toString();

      Option opt = options.getOption(option);
      if (opt == null) {
        throw new UnrecognizedOptionException("Default option wasn't defined", option);
      }

      // if the option is part of a group, check if another option of the group has been selected
      OptionGroup group = options.getOptionGroup(opt);
      boolean selected = group != null && group.getSelected() != null;

      if (!cmd.hasOption(option) && !selected) {
        // get the value from the properties
        String value = properties.getProperty(option);

        if (opt.hasArg()) {
          if (opt.getValues() == null || opt.getValues().length == 0) {
            opt.addValueForProcessing(value);
          }
        } else if (!("yes".equalsIgnoreCase(value)
            || "true".equalsIgnoreCase(value)
            || "1".equalsIgnoreCase(value))) {
          // if the value is not yes, true or 1 then don't add the option to the CommandLine
          continue;
        }

        handleOption(opt);
        currentOption = null;
      }
    }
  }
Exemple #6
0
  public void test13935() {
    OptionGroup directions = new OptionGroup();

    Option left = new Option("l", "left", false, "go left");
    Option right = new Option("r", "right", false, "go right");
    Option straight = new Option("s", "straight", false, "go straight");
    Option forward = new Option("f", "forward", false, "go forward");
    forward.setRequired(true);

    directions.addOption(left);
    directions.addOption(right);
    directions.setRequired(true);

    Options opts = new Options();
    opts.addOptionGroup(directions);
    opts.addOption(straight);

    CommandLineParser parser = new PosixParser();
    boolean exception = false;

    String[] args = new String[] {};
    try {
      CommandLine line = parser.parse(opts, args);
    } catch (ParseException exp) {
      exception = true;
    }

    if (!exception) {
      fail("Expected exception not caught.");
    }

    exception = false;

    args = new String[] {"-s"};
    try {
      CommandLine line = parser.parse(opts, args);
    } catch (ParseException exp) {
      exception = true;
    }

    if (!exception) {
      fail("Expected exception not caught.");
    }

    exception = false;

    args = new String[] {"-s", "-l"};
    try {
      CommandLine line = parser.parse(opts, args);
    } catch (ParseException exp) {
      fail("Unexpected exception: " + exp.getClass().getName() + ":" + exp.getMessage());
    }

    opts.addOption(forward);
    args = new String[] {"-s", "-l", "-f"};
    try {
      CommandLine line = parser.parse(opts, args);
    } catch (ParseException exp) {
      fail("Unexpected exception: " + exp.getClass().getName() + ":" + exp.getMessage());
    }
  }
  private JPanel createGeneralOptionsPanel() {
    OptionGroup group = new OptionGroup(ApplicationBundle.message("title.general"));
    myCbUseSingleClassImports =
        new JCheckBox(ApplicationBundle.message("checkbox.use.single.class.import"));
    group.add(myCbUseSingleClassImports);

    myCbUseFQClassNames =
        new JCheckBox(ApplicationBundle.message("checkbox.use.fully.qualified.class.names"));
    group.add(myCbUseFQClassNames);

    myCbInsertInnerClassImports =
        new JCheckBox(ApplicationBundle.message("checkbox.insert.imports.for.inner.classes"));
    group.add(myCbInsertInnerClassImports);

    myFqnInJavadocOption = new FullyQualifiedNamesInJavadocOptionProvider(mySettings);
    group.add(myFqnInJavadocOption.getPanel());

    myClassCountField = new JTextField(3);
    myNamesCountField = new JTextField(3);
    final JPanel panel = new JPanel(new GridBagLayout());
    panel.add(
        new JLabel(ApplicationBundle.message("editbox.class.count.to.use.import.with.star")),
        new GridBagConstraints(
            0,
            GridBagConstraints.RELATIVE,
            1,
            1,
            0.0,
            0.0,
            GridBagConstraints.WEST,
            GridBagConstraints.NONE,
            new Insets(0, 3, 0, 0),
            0,
            0));
    panel.add(
        myClassCountField,
        new GridBagConstraints(
            1,
            GridBagConstraints.RELATIVE,
            1,
            1,
            1.0,
            0.0,
            GridBagConstraints.WEST,
            GridBagConstraints.NONE,
            new Insets(0, 1, 0, 0),
            0,
            0));
    panel.add(
        new JLabel(ApplicationBundle.message("editbox.names.count.to.use.static.import.with.star")),
        new GridBagConstraints(
            0,
            GridBagConstraints.RELATIVE,
            1,
            1,
            0.0,
            1.0,
            GridBagConstraints.WEST,
            GridBagConstraints.NONE,
            new Insets(0, 3, 0, 0),
            0,
            0));
    panel.add(
        myNamesCountField,
        new GridBagConstraints(
            1,
            GridBagConstraints.RELATIVE,
            1,
            1,
            1.0,
            1.0,
            GridBagConstraints.WEST,
            GridBagConstraints.NONE,
            new Insets(0, 1, 0, 0),
            0,
            0));

    group.add(panel);
    return group.createPanel();
  }
  private Component buildProfileTab() {
    HorizontalLayout root = new HorizontalLayout();
    root.setCaption("Profile");
    root.setIcon(FontAwesome.USER);
    root.setWidth(100.0f, Unit.PERCENTAGE);
    root.setSpacing(true);
    root.setMargin(true);
    root.addStyleName("profile-form");

    VerticalLayout pic = new VerticalLayout();
    pic.setSizeUndefined();
    pic.setSpacing(true);
    Image profilePic = new Image(null, new ThemeResource("img/profile-pic-300px.jpg"));
    profilePic.setWidth(100.0f, Unit.PIXELS);
    pic.addComponent(profilePic);

    Button upload =
        new Button(
            "Change…",
            event -> {
              Notification.show("Not implemented in this demo");
            });
    upload.addStyleName(ValoTheme.BUTTON_TINY);
    pic.addComponent(upload);

    root.addComponent(pic);

    FormLayout details = new FormLayout();
    details.addStyleName(ValoTheme.FORMLAYOUT_LIGHT);
    root.addComponent(details);
    root.setExpandRatio(details, 1);

    firstNameField = new TextField("First Name");
    details.addComponent(firstNameField);
    lastNameField = new TextField("Last Name");
    details.addComponent(lastNameField);

    titleField = new ComboBox("Title");
    titleField.setInputPrompt("Please specify");
    titleField.addItem("Mr.");
    titleField.addItem("Mrs.");
    titleField.addItem("Ms.");
    titleField.setNewItemsAllowed(true);
    details.addComponent(titleField);

    sexField = new OptionGroup("Sex");
    sexField.addItem(Boolean.FALSE);
    sexField.setItemCaption(Boolean.FALSE, "Female");
    sexField.addItem(Boolean.TRUE);
    sexField.setItemCaption(Boolean.TRUE, "Male");
    sexField.addStyleName("horizontal");
    details.addComponent(sexField);

    Label section = new Label("Contact Info");
    section.addStyleName(ValoTheme.LABEL_H4);
    section.addStyleName(ValoTheme.LABEL_COLORED);
    details.addComponent(section);

    emailField = new TextField("Email");
    emailField.setWidth("100%");
    emailField.setRequired(true);
    emailField.setNullRepresentation("");
    details.addComponent(emailField);

    locationField = new TextField("Location");
    locationField.setWidth("100%");
    locationField.setNullRepresentation("");
    locationField.setComponentError(new UserError("This address doesn't exist"));
    details.addComponent(locationField);

    phoneField = new TextField("Phone");
    phoneField.setWidth("100%");
    phoneField.setNullRepresentation("");
    details.addComponent(phoneField);

    newsletterField = new OptionalSelect<>();
    newsletterField.addOption(0, "Daily");
    newsletterField.addOption(1, "Weekly");
    newsletterField.addOption(2, "Monthly");
    details.addComponent(newsletterField);

    section = new Label("Additional Info");
    section.addStyleName(ValoTheme.LABEL_H4);
    section.addStyleName(ValoTheme.LABEL_COLORED);
    details.addComponent(section);

    websiteField = new TextField("Website");
    websiteField.setInputPrompt("http://");
    websiteField.setWidth("100%");
    websiteField.setNullRepresentation("");
    details.addComponent(websiteField);

    bioField = new TextArea("Bio");
    bioField.setWidth("100%");
    bioField.setRows(4);
    bioField.setNullRepresentation("");
    details.addComponent(bioField);

    return root;
  }