Ejemplo n.º 1
0
 /**
  * Get all Flag instances parsed from class (via the loadOpts(Class<?> c) method) as a List.
  *
  * @return List containing Flag instances.
  */
 public List<Flag> getFlagsAsList() {
   final List<Flag> list = new ArrayList<Flag>();
   for (OptionHolder holder : options.values()) {
     list.add(holder.getFlag());
   }
   return list;
 }
Ejemplo n.º 2
0
 /**
  * Debugging method. Prints the Flags found and the corresponding Fields.
  *
  * @throws IllegalAccessException
  * @throws IllegalArgumentException
  */
 public void printFlags() {
   try {
     for (OptionHolder holder : options.values()) {
       System.out.println(
           "Field: "
               + holder.getField().toGenericString()
               + "\nFlag: name:"
               + holder.getFlag().name()
               + ", description:"
               + holder.getFlag().description()
               + ", type:"
               + holder.getType()
               + ", default:"
               + (holder.isInstanced()
                   ? holder.getField().get(holder.getObjectSource())
                   : holder.getField().get(holder.getClassSource())));
     }
   } catch (IllegalAccessException e) {
     throw new RuntimeException(e);
   }
 }
Ejemplo n.º 3
0
  /**
   * Try to set the arguments from main method on the fields loaded by loadOpts(Class<?> c).
   *
   * @param args - Arguments passed from main method.
   * @return this
   */
  public Flags parse(String[] args) {
    optionSet = optionParser.parse(args);

    // Store non option arguments
    nonOptionArguments = optionSet.nonOptionArguments();
    if (nonOptionArguments == null) {
      nonOptionArguments = new ArrayList<String>();
    }

    // do not parse options if "help" is a part of the arguments given
    if (helpFlagged()) {
      return this;
    }
    if (propertiesFlagged()) {
      List<String> files = optionSet.valuesOf(PROPERTIES_FILE);
      ArrayList<String> newArgs = new ArrayList<String>();
      for (String filename : files) {
        final Properties props = new Properties();
        try {
          final FileInputStream stream = new FileInputStream(filename);
          props.load(stream);
          for (Enumeration<?> keys = props.propertyNames(); keys.hasMoreElements(); ) {
            String flagName = (String) keys.nextElement();
            if (!options.containsKey(flagName) || optionSet.hasArgument(flagName)) {
              // Properties contains something not in options or is already set by commandline
              // argument
              // Command line argument takes precedence over properties file
              continue;
            }
            newArgs.add("--" + flagName);
            newArgs.add(props.getProperty(flagName));
          }

          stream.close();
        } catch (IOException e) {
          throw new RuntimeException("Could not parse property-file", e);
        }
      }
      Collections.addAll(newArgs, args);
      optionSet = optionParser.parse(newArgs.toArray(new String[newArgs.size()]));
    }

    for (OptionHolder holder : options.values()) {
      try {
        OptionSpec<?> optionSpec = holder.getOptionSpec();

        // Deal with the flags that were given on the command line.
        if (optionSet.has(optionSpec)) {
          switch (holder.getType()) {
            case INTEGER:
              if (holder.isInstanced()) {
                holder.getField().set(holder.getObjectSource(), optionSet.valueOf(optionSpec));
              } else {
                holder.getField().set(holder.getField().getClass(), optionSet.valueOf(optionSpec));
              }
              break;

            case LONG:
              if (holder.isInstanced()) {
                holder.getField().set(holder.getObjectSource(), optionSet.valueOf(optionSpec));
              } else {
                holder.getField().set(holder.getField().getClass(), optionSet.valueOf(optionSpec));
              }
              break;

            case STRING:
              if (holder.isInstanced()) {
                holder.getField().set(holder.getObjectSource(), optionSet.valueOf(optionSpec));
              } else {
                holder.getField().set(holder.getField().getClass(), optionSet.valueOf(optionSpec));
              }
              break;

            case BOOLEAN:
              Object value = optionSet.valueOf(optionSpec);
              if (holder.isInstanced()) {
                holder.getField().set(holder.getObjectSource(), (value == null) ? true : value);
              } else {
                holder.getField().set(holder.getField().getClass(), (value == null) ? true : value);
              }
              break;

            case ENUM:
              if (holder.isInstanced()) {
                try {
                  holder.getField().set(holder.getObjectSource(), optionSet.valueOf(optionSpec));
                } catch (Exception e) {
                  throw new IllegalArgumentException(
                      "Option given is not a valid option. Valid options are: "
                          + enumOptions.get(holder.flag.options()).toString()
                          + ".");
                }
              } else {
                try {
                  holder
                      .getField()
                      .set(holder.getField().getClass(), optionSet.valueOf(optionSpec));
                } catch (Exception e) {
                  throw new IllegalArgumentException(
                      "Option given is not a valid option. Valid options are: "
                          + enumOptions.get(holder.flag.options()).toString()
                          + ".");
                }
              }
              break;
          }

          // No further action needed for this field.
          continue;
        }

        // Check if flag that does not occur in command line was required.
        if (holder.getFlag().required()) {
          throw new IllegalArgumentException(
              "Required argument missing: " + holder.getFlag().name());
        }
      } catch (IllegalAccessException e) {
        throw new RuntimeException(
            "Programming error, illegal access for " + holder.getField().toGenericString());
      }
    }
    return this;
  }
Ejemplo n.º 4
0
  /**
   * Prints the help to the specified output stream.
   *
   * @param out the OutputStream we wish to print the help output to.
   */
  public void printHelp(OutputStream out) {
    PrintWriter w = new PrintWriter(out);

    Map<String, List<OptionHolder>> holdersByClass = new TreeMap<String, List<OptionHolder>>();

    // Iterate over all the options we have gathered and stash them by class.
    for (OptionHolder holder : options.values()) {
      // Fetch list corresponding to source class name
      final String className;
      if (holder.isInstanced()) {
        className = holder.getObjectSource().getClass().getName();
      } else {
        className = holder.getClassSource().getName();
      }
      List<OptionHolder> holderList = holdersByClass.get(className);
      if (null == holderList) {
        // The list did not exist.  Create it.
        holderList = new LinkedList<OptionHolder>();
        holdersByClass.put(className, holderList);
      }

      holderList.add(holder);
    }

    // Output options by class
    for (Map.Entry<String, List<OptionHolder>> ent : holdersByClass.entrySet()) {
      String className = ent.getKey();
      List<OptionHolder> holderList = ent.getValue();

      // Sort the options. In Java, sorting collections is worse
      // than watching Pandas f**k.
      Collections.sort(
          holderList,
          new Comparator<OptionHolder>() {
            @Override
            public int compare(OptionHolder a, OptionHolder b) {
              return a.getFlag().name().toLowerCase().compareTo(b.getFlag().name().toLowerCase());
            }
          });

      StringBuffer buff = new StringBuffer();

      buff.append("\n\n")
          .append(className)
          .append("\n")
          .append("------------------------------------------------------------------------")
          .append("\n");

      for (OptionHolder holder : holderList) {
        // Mark required flags with a "*"
        buff.append(holder.getFlag().required() ? "* " : "  ");

        String s;
        try {
          s =
              "  --"
                  + holder.getFlag().name()
                  + " <"
                  + holder.getType()
                  + "> default: "
                  + (holder.isInstanced()
                      ? holder.getField().get(holder.getObjectSource())
                      : holder.getField().get(holder.getClassSource()));
        } catch (IllegalAccessException e) {
          throw new RuntimeException(e);
        }

        // TODO: handle enum options
        if (holder.getFlag().options() != NoOption.class) {
          s = s + " options: " + enumOptions.get(holder.getFlag().options()).toString();
        }

        // Avert your eyes.
        int spaces = 50 - s.length();
        spaces = spaces < 0 ? 0 : spaces;
        buff.append(s)
            .append("  . . . . . . . . . . . . . . . . . . . . . . . . ".substring(0, spaces))
            .append("| " + holder.getFlag().description())
            .append("\n");
      }
      w.println(buff.toString());
    }
    w.flush();
  }
Ejemplo n.º 5
0
 public static <OptionHolder> OptionSchema newOptionSchema(OptionHolder optionHolder) {
   return newOptionSchema(optionHolder.getClass());
 }