All the logic for parsing and validating options.

@param args
@return A struct containing validated options.
@throws IOException
339481
private static ConsistencyFixCLI.Options parseArgs(String[] args) {
        OptionParser parser = new OptionParser();
        parser.accepts("help", "print help information");
        parser.accepts("url", "The bootstrap url.")
              .withRequiredArg()
              .describedAs("bootstrapUrl")
              .ofType(String.class);
        parser.accepts("store", "The store name.")
              .withRequiredArg()
              .describedAs("storeName")
              .ofType(String.class);
        parser.accepts("bad-key-file-in",
                       "Name of bad-key-file-in. " + "Each key must be in hexadecimal format. "
                               + "Each key must be on a separate line in the file. ")
              .withRequiredArg()
              .describedAs("badKeyFileIn")
              .ofType(String.class);
        parser.accepts("orphan-format",
                       "Indicates format of bad-key-file-in is of 'orphan' key-values.");
        parser.accepts("dry-run",
                       "Indicates to go through all of the read actions until the point of issuing repair puts. Then, do a 'no-op'.");
        parser.accepts("parse-only",
                       "Indicates to only parse the input file. Does not perform any key queries or repair puts. "
                               + "Does bootstrap though so bootstrapUrl and storeName must be specified.");
        parser.accepts("bad-key-file-out",
                       "Name of bad-key-file-out. "
                               + "Keys that are not mae consistent are output to this file.")
              .withRequiredArg()
              .describedAs("badKeyFileOut")
              .ofType(String.class);
        parser.accepts("parallelism",
                       "Number of consistency fix messages outstanding in parallel. ")
              .withRequiredArg()
              .describedAs("parallelism [Default value: " + Options.defaultParallelism + "]")
              .ofType(Integer.class);
        parser.accepts("progress-period-ops",
                       "Number of operations between 'info' progress messages. ")
              .withRequiredArg()
              .describedAs("period (in operations) between outputting progress [Default value: "
                           + Options.defaultProgressPeriodOps + "]")
              .ofType(Long.class);
        parser.accepts("per-server-qps-limit",
                       "Number of operations that the consistency fixer will issue to any individual server in one second. ")
              .withRequiredArg()
              .describedAs("perServerQPSLimit [Default value: " + Options.defaultPerServerQPSLimit
                           + "]")
              .ofType(Long.class);

        OptionSet optionSet = parser.parse(args);

        if(optionSet.hasArgument("help")) {
            try {
                parser.printHelpOn(System.out);
            } catch(IOException e) {
                e.printStackTrace();
            }
            printUsage();
            System.exit(0);
        }
        if(!optionSet.hasArgument("url")) {
            printUsage("Missing required 'url' argument.", parser);
        }
        if(!optionSet.hasArgument("store")) {
            printUsage("Missing required 'store' argument.", parser);
        }
        if(!optionSet.has("bad-key-file-in")) {
            printUsage("Missing required 'bad-key-file-in' argument.", parser);
        }
        if(!optionSet.has("bad-key-file-out")) {
            printUsage("Missing required 'bad-key-file-out' argument.", parser);
        }

        Options options = new Options();

        options.url = (String) optionSet.valueOf("url");
        options.storeName = (String) optionSet.valueOf("store");
        options.badKeyFileIn = (String) optionSet.valueOf("bad-key-file-in");
        options.badKeyFileOut = (String) optionSet.valueOf("bad-key-file-out");
        if(optionSet.has("orphan-format")) {
            options.badKeyFileInOrphanFormat = true;
        }
        if(optionSet.has("parallelism")) {
            options.parallelism = (Integer) optionSet.valueOf("parallelism");
        }
        if(optionSet.has("progress-period-ops")) {
            options.progressPeriodOps = (Long) optionSet.valueOf("progress-period-ops");
        }
        if(optionSet.has("per-server-qps-limit")) {
            options.perServerQPSLimit = (Long) optionSet.valueOf("per-server-qps-limit");
        }
        if(optionSet.has("dry-run")) {
            options.dryRun = true;
        }
        if(optionSet.has("parse-only")) {
            options.parseOnly = true;
        }

        return options;
    }
188926
public static void main(String[] args) throws IOException {
    if (args.length == 0) {
      System.err.println("Usage: PosTaggerME [-td tagdict] model < tokenized_sentences");
      System.err.println("       PosTaggerME -test model \"sentence\"");
      System.exit(1);
    }
    int ai=0;
    boolean test = false;
    String tagdict = null;
    while(ai < args.length && args[ai].startsWith("-")) {
      if (args[ai].equals("-test")) {
        ai++;
        test=true;
      }
      else if (args[ai].equals("-td")) {
        tagdict = args[ai+1];
        ai+=2;
      }
    }
    POSTaggerME tagger;
    String modelFile = args[ai++];
    if (tagdict != null) {
      tagger = new PosTagger(modelFile, new POSDictionary(tagdict));
    }
    else {
      tagger = new PosTagger(modelFile);
    }
    if (test) {
      System.out.println(tagger.tag(args[ai]));
    }
    else {
      BufferedReader in = new BufferedReader(new InputStreamReader(System.in,"ISO-8859-1"));
      PrintStream out = new PrintStream(System.out,true,"ISO-8859-1");
      for (String line = in.readLine(); line != null; line = in.readLine()) {
        out.println(tagger.tag(line));
      }
    }
  }
171512
private int init(String[] args) throws IOException {
    try {
      fs = FileSystem.get(getConf());
    } catch (IOException ioe) {
      System.err.println("Can not initialize the file system: " +
          ioe.getLocalizedMessage());
      return -1;
    }
    int hostHashCode = hostname.hashCode();
    try {
      for (int i = 0; i < args.length; i++) { // parse command line
        if (args[i].equals("-readProbability")) {
          readPr = Double.parseDouble(args[++i]);
          if (readPr<0 || readPr>1) {
            System.err.println(
                "The read probability must be [0, 1]: " + readPr);
            return -1;
          }
        } else if (args[i].equals("-writeProbability")) {
          writePr = Double.parseDouble(args[++i]);
          if (writePr<0 || writePr>1) {
            System.err.println(
                "The write probability must be [0, 1]: " + writePr);
            return -1;
          }
        } else if (args[i].equals("-root")) {
          root = new Path(args[++i]);
        } else if (args[i].equals("-maxDelayBetweenOps")) {
          maxDelayBetweenOps = Integer.parseInt(args[++i]); // in milliseconds
        } else if (args[i].equals("-numOfThreads")) {
          numOfThreads = Integer.parseInt(args[++i]);
          if (numOfThreads <= 0) {
            System.err.println(
                "Number of threads must be positive: " + numOfThreads);
            return -1;
          }
        } else if (args[i].equals("-startTime")) {
          startTime = Long.parseLong(args[++i]);
        } else if (args[i].equals("-elapsedTime")) {
          elapsedTime = Long.parseLong(args[++i]);
        } else if (args[i].equals("-seed")) {
          r = new Random(Long.parseLong(args[++i])+hostHashCode);
        } else {
          System.err.println(USAGE);
          ToolRunner.printGenericCommandUsage(System.err);
          return -1;
        }
      }
    } catch (NumberFormatException e) {
      System.err.println("Illegal parameter: " + e.getLocalizedMessage());
      System.err.println(USAGE);
      return -1;
    }

    if (readPr+writePr <0 || readPr+writePr>1) {
      System.err.println(
          "The sum of read probability and write probability must be [0, 1]: " +
          readPr + " "+writePr);
      return -1;
    }

    if (r==null) {
      r = new Random(System.currentTimeMillis()+hostHashCode);
    }

    return initFileDirTables();
  }
626098
private static String[] readArgsFile(String argsFile) throws IOException {
    final ArrayList<String> lines = new ArrayList<String>();
    final BufferedReader reader = new BufferedReader(
        new InputStreamReader(
            new FileInputStream(argsFile), "UTF-8"));
    try {
      String line;
      while ((line = reader.readLine()) != null) {
        line = line.trim();
        if (!line.isEmpty() && !line.startsWith("#")) {
          lines.add(line);
        }
      }
    } finally {
      reader.close();
    }
    return lines.toArray(new String [lines.size()]);
  }
1374343
public static Struct toStruct(Argument arg) {
	Struct trg = new StructImpl();
	StructImpl.copy(arg, trg, false);
	return trg;
    }
1241810
@Override
    public void processArguments(String[] args) throws IOException {
        List<File> classFiles = new ArrayList<File>();
        List<File> jarFiles = new ArrayList<File>();
        String[] fileArgs = null;

        for (int i = 0; i < args.length; i++) {
            if (args[i].equalsIgnoreCase("--debug") || args[i].equals("-d")) {
                setDebug(true);
            } else if (args[i].equalsIgnoreCase("--config")) {
                // TODO: Handle config file parsing
                File configFile = new File(args[++i]);
                System.out.println("Config file not currently supported" + configFile);
            } else if (args[i].equalsIgnoreCase("--ffdc")) {
                addFfdc = true;
            } else if (args[i].equalsIgnoreCase("--static")) {
                injectStatic = true;
            } else if (args[i].equalsIgnoreCase("--liberty")) {
                defaultTraceType = TraceType.LIBERTY;
            } else if (args[i].equalsIgnoreCase("--tr")) {
                defaultTraceType = TraceType.TR;
            } else if (args[i].equalsIgnoreCase("--java-logging")) {
                defaultTraceType = TraceType.JAVA_LOGGING;
            } else {
                fileArgs = new String[args.length - i];
                System.arraycopy(args, i, fileArgs, 0, fileArgs.length);
                break;
            }
        }

        if (fileArgs == null || fileArgs.length == 0) {
            throw new IllegalArgumentException("No file specified");
        }

        // Add jar files, zip files, and class files to the appropriate collections
        for (int i = 0; i < fileArgs.length; i++) {
            File f = new File(fileArgs[i]);
            if (!f.exists()) {
                throw new IllegalArgumentException("File \"" + f + "\" does not exist");
            } else if (f.isDirectory()) {
                classFiles.addAll(getClassFiles(f, null));
                jarFiles.addAll(getJarFiles(f, null));
            } else if (f.getName().endsWith(".class")) {
                classFiles.add(f);
            } else if (f.getName().endsWith(".jar")) {
                jarFiles.add(f);
            } else if (f.getName().endsWith(".zip")) {
                jarFiles.add(f);
            } else {
                System.err.println(f + " is an unexpected file type; ignoring");
            }
        }

        setClassFiles(classFiles);
        setJarFiles(jarFiles);
    }
1228645
@SuppressWarnings("unchecked")
        public static void executeCommand(String[] args) throws IOException {

            OptionParser parser = getParser();

            // declare parameters
            List<String> metaKeys = null;
            String url = null;
            List<Integer> nodeIds = null;
            Boolean allNodes = true;
            List<String> storeNames = null;

            // parse command-line input
            args = AdminToolUtils.copyArrayAddFirst(args, "--" + OPT_HEAD_META_GET_RO);
            OptionSet options = parser.parse(args);
            if(options.has(AdminParserUtils.OPT_HELP)) {
                printHelp(System.out);
                return;
            }

            // check required options and/or conflicting options
            AdminParserUtils.checkRequired(options, OPT_HEAD_META_GET_RO);
            AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL);
            AdminParserUtils.checkOptional(options,
                                           AdminParserUtils.OPT_NODE,
                                           AdminParserUtils.OPT_ALL_NODES);
            AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_STORE);

            // load parameters
            metaKeys = (List<String>) options.valuesOf(OPT_HEAD_META_GET_RO);
            url = (String) options.valueOf(AdminParserUtils.OPT_URL);
            if(options.has(AdminParserUtils.OPT_NODE)) {
                nodeIds = (List<Integer>) options.valuesOf(AdminParserUtils.OPT_NODE);
                allNodes = false;
            }
            storeNames = (List<String>) options.valuesOf(AdminParserUtils.OPT_STORE);

            // execute command
            AdminClient adminClient = AdminToolUtils.getAdminClient(url);

            if(allNodes) {
                nodeIds = AdminToolUtils.getAllNodeIds(adminClient);
            }

            if(metaKeys.size() == 1 && metaKeys.get(0).equals(METAKEY_ALL)) {
                metaKeys = Lists.newArrayList();
                metaKeys.add(KEY_MAX_VERSION);
                metaKeys.add(KEY_CURRENT_VERSION);
                metaKeys.add(KEY_STORAGE_FORMAT);
            }

            doMetaGetRO(adminClient, nodeIds, storeNames, metaKeys);
        }
1187681
static public String getString(String msg, int arg)
	{
		return getString(msg, new Object[] { Integer.toString(arg) });
	}
674911
public String[] parse(final String[] args) {
    parsed = new HashMap<String, String>(options.size());
    ArrayList<String> unparsed = null;
    for (int i = 0; i < args.length; i++) {
      final String arg = args[i];
      String[] opt = options.get(arg);
      if (opt != null) {  // Perfect match: got --foo
        if (opt[0] != null) {  // This option requires an argument.
          if (++i < args.length) {
            parsed.put(arg, args[i]);
          } else {
            throw new IllegalArgumentException("Missing argument for " + arg);
          }
        } else {
          parsed.put(arg, null);
        }
        continue;
      }
      // Is it a --foo=blah?
      final int equal = arg.indexOf('=', 1);
      if (equal > 0) {  // Looks like so.
        final String name = arg.substring(0, equal);
        opt = options.get(name);
        if (opt != null) {
          parsed.put(name, arg.substring(equal + 1, arg.length()));
          continue;
        }
      }
      // Not a flag.
      if (unparsed == null) {
        unparsed = new ArrayList<String>(args.length - i);
      }
      if (!arg.isEmpty() && arg.charAt(0) == '-') {
        if (arg.length() == 2 && arg.charAt(1) == '-') {  // `--'
          for (i++; i < args.length; i++) {
            unparsed.add(args[i]);
          }
          break;
        }
        throw new IllegalArgumentException("Unrecognized option " + arg);
      }
      unparsed.add(arg);
    }
    if (unparsed != null) {
      return unparsed.toArray(new String[unparsed.size()]);
    } else {
      return new String[0];
    }
  }
1138027
public List<String> load(String[] args) throws IOException {
    setLogLevel(Level.WARNING);

    mappings.addJreMappings();

    // Create a temporary directory as the sourcepath's first entry, so that
    // modified sources will take precedence over regular files.
    fileUtil.setSourcePathEntries(new ArrayList<>());

    ArgProcessor processor = new ArgProcessor();
    processor.processArgs(args);
    postProcessArgs();

    return processor.sourceFiles;
  }
496361
private void parseCLI(final String[] args) throws IOException {
    try {
      this.parsedArguments = this.argParser.parseArgs(args);
      System.err.println("CLI options: " + this.parsedArguments);
      switch (args[0]) {
      case SEQ_TRAINER_NAME:
        seqTrain();
        break;
      case PARSE_TRAINER_NAME:
        parserTrain();
        break;
      case DOC_TRAINER_NAME:
        docTrain();
        break;
      case SEQEVAL_PARSER_NAME:
        seqeval();
        break;
      case PARSEVAL_PARSER_NAME:
        parseval();
        break;
      case DOCEVAL_PARSER_NAME:
        doceval();
        break;
      case TOKEVAL_PARSER_NAME:
        tokeval();
        break;
      case CROSSSEQ_PARSER_NAME:
        sequenceCrossValidate();
        break;
      case CROSSDOC_PARSER_NAME:
        docCrossValidate();
      }
    } catch (final ArgumentParserException e) {
      this.argParser.handleError(e);
      System.out.println("Run java -jar target/ixa-pipe-ml-" + this.version
          + "-exec.jar (" + SEQ_TRAINER_NAME + "|" + PARSE_TRAINER_NAME + "|"
          + DOC_TRAINER_NAME
          + "|seqeval|parseval|doceval|tokeval|crosseq|crossdoc) -help for details");
      System.exit(1);
    }
  }
1109288
public static void main(String[] args) throws IOException, InterruptedException {

        // read the options
        Properties opt = readOptions(args);
        if (opt == null)
            throw new RuntimeException("Unable to find options file path, it must be provided as an argument to the call.");

        // validate the options
        if (opt.getProperty(_OPTION_INPUT_FOLDER) == null || opt.getProperty(_OPTION_INPUT_FOLDER).isEmpty())
            throw new RuntimeException("Option " + _OPTION_INPUT_FOLDER + " is required.");
        File inputDir = new File(opt.getProperty(_OPTION_INPUT_FOLDER));
        if (!inputDir.exists())
            throw new RuntimeException("Invalid input folder.");
        Pattern incRegex = opt.getProperty(_OPTION_INPUT_REGEX_INCLUDE) == null ? null : Pattern.compile(opt.getProperty(_OPTION_INPUT_REGEX_INCLUDE));
        Pattern excRegex = opt.getProperty(_OPTION_INPUT_REGEX_EXCLUDE) == null ? null : Pattern.compile(opt.getProperty(_OPTION_INPUT_REGEX_EXCLUDE));
        String mode = opt.getProperty(_OPTION_PROCESSING_MODE);
        if (mode == null)
            throw new RuntimeException("Option " + _OPTION_PROCESSING_MODE + " is required.");
        if (!"flat-to-xml".equals(mode) && !"xml-to-flat".equals(mode))
            throw new RuntimeException("Invalid mode (must be flat-to-xml or xml-to-flat).");
        String rawErrorCodes = opt.getProperty(_OPTION_PROCESSING_ERROR_CODES);
        List<String> errorCodes = null;
        if (rawErrorCodes != null && !rawErrorCodes.isEmpty()) {
            errorCodes = new ArrayList<>();
            for (String s : StringUtils.split(rawErrorCodes, ','))
                errorCodes.add(s.trim());
        }
        int numThreads = Math.min(Runtime.getRuntime().availableProcessors() + 1, 5);
        if (opt.getProperty(_OPTION_PROCESSING_NUM_THREADS) != null && !opt.getProperty(_OPTION_PROCESSING_NUM_THREADS).isEmpty())
            numThreads = Integer.parseInt(opt.getProperty(_OPTION_PROCESSING_NUM_THREADS));
        if (opt.getProperty(_OPTION_OUTPUT_FOLDER) == null || opt.getProperty(_OPTION_OUTPUT_FOLDER).isEmpty())
            throw new RuntimeException("Option " + _OPTION_OUTPUT_FOLDER + " is required.");
        String compression = opt.getProperty(_OPTION_PROCESSING_COMPRESSION);
        if (compression != null && !compression.equals("gz") && !compression.equals("xz") && !compression.equals("none") && !compression.equals("as-input"))
            throw new RuntimeException("Invalid compression (must be gz, xz, none, or as-input).");
        File outputDir = new File(opt.getProperty(_OPTION_OUTPUT_FOLDER));
        if (!outputDir.exists())
            throw new RuntimeException("Invalid outupt folder.");
        boolean cleanCreatedFiles = opt.getProperty(_OPTION_OUTPUT_CLEAN_CREATED_FILES) == null ? false : Boolean.valueOf(opt.getProperty(_OPTION_OUTPUT_CLEAN_CREATED_FILES));
        boolean createReport = opt.getProperty(_OPTION_OUTPUT_CREATE_REPORT) == null ? false : Boolean.valueOf(opt.getProperty(_OPTION_OUTPUT_CREATE_REPORT));
        String reportName = opt.getProperty(_OPTION_OUTPUT_REPORT_NAME) == null ? "report.txt" : opt.getProperty(_OPTION_OUTPUT_REPORT_NAME);
        boolean deidentify = opt.getProperty(_OPTION_OUTPUT_DEIDENTIFY_FILES) == null ? false : Boolean.valueOf(opt.getProperty(_OPTION_OUTPUT_DEIDENTIFY_FILES));

        // gather the files to process
        List<File> toProcess = new ArrayList<>();
        File[] files = inputDir.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory())
                    continue;
                boolean add = true;
                if (incRegex != null || excRegex != null) {
                    if (incRegex != null && !incRegex.matcher(file.getName()).matches())
                        add = false;
                    if (excRegex != null && excRegex.matcher(file.getName()).matches())
                        add = false;
                }
                if (add)
                    toProcess.add(file);
            }
        }

        // we will report the information in this collection
        Map<String, List<String>> reportData = new TreeMap<>();
        Map<String, AtomicInteger> globalCounts = new HashMap<>();
        Map<String, Set<String>> globalDetails = new HashMap<>();
        AtomicInteger globalTumorCount = new AtomicInteger();

        // create the work
        long start = System.currentTimeMillis();
        ExecutorService executor = Executors.newFixedThreadPool(numThreads);
        for (File inputFile : toProcess) {
            String outputFilename = invertFilename(inputFile, compression);
            @SuppressWarnings("ConstantConditions")
            File outputFile = new File(outputDir, outputFilename);
            if (inputFile.equals(outputFile))
                throw new RuntimeException("Was about to write output file into the input file, this can't be good!");
            if (cleanCreatedFiles)
                outputFile.deleteOnExit();
            List<String> data = new ArrayList<>();
            reportData.put(inputFile.getName(), data);
            executor.execute(new FileProcessor(inputFile, outputFile, data, cleanCreatedFiles, "flat-to-xml".equals(mode), globalCounts, globalDetails, globalTumorCount, errorCodes));
        }
        executor.shutdown();

        // wait for the work to be completed
        executor.awaitTermination(1, TimeUnit.DAYS);

        // write the report
        if (createReport) {
            Writer reportWriter = new OutputStreamWriter(new FileOutputStream(new File(outputDir, reportName)), StandardCharsets.UTF_8);

            reportWriter.write("Report created on " + new Date() + "\n\n");
            reportWriter.write("total number of files: " + formatNumber(toProcess.size()) + "\n");
            reportWriter.write("total processing time: " + formatTime(System.currentTimeMillis() - start) + "\n");
            reportWriter.write("total number of processed tumors: " + formatNumber(globalTumorCount.get()) + "\n");
            reportWriter.write("combined warnings:\n");

            int globalCount = 0;
            for (String code : NaaccrErrorUtils.getAllValidationErrors().keySet()) {
                if (errorCodes != null && !errorCodes.contains(code))
                    continue;
                int count = globalCounts.containsKey(code) ? globalCounts.get(code).get() : 0;
                if (count > 0) {
                    reportWriter.write("      " + code + ": " + formatNumber(count) + " cases\n");
                    if (globalDetails.containsKey(code)) {
                        List<String> list = new ArrayList<>(globalDetails.get(code));
                        Collections.sort(list);
                        reportWriter.write("         involved item(s): " + list.size() + " " + list + "\n");
                    }
                }
                globalCount += count;
            }
            if (globalCount == 0)
                reportWriter.write("      no warning found\n");

            for (Entry<String, List<String>> entry : reportData.entrySet()) {
                reportWriter.write("\n\n");
                reportWriter.write(deidentify ? "<de-identified file name>" : entry.getKey());
                reportWriter.write("\n");
                for (String line : entry.getValue()) {
                    reportWriter.write(line);
                    reportWriter.write("\n");
                }
            }
            reportWriter.close();
        }
    }
508838
public static String fmtMsg(final String fmt, final int arg) {
    Object[] o = new Object[1];
    o[0] = new Integer(arg);

    return MessageFormat.format(fmt, o);
  }
132716
@Override
    public boolean parseArguments(final PrintStream messageStream, final String[] args) {
        this.argv = args;
        this.messageStream = messageStream;
        if (prefix.isEmpty()) {
            commandLine = callerOptions.getClass().getSimpleName();
        }
        for (int i = 0; i < args.length; ++i) {
            final String arg = args[i];
            if (arg.equals("-h") || arg.equals("--help")) {
                messageStream.append(usage(false, true));
                return false;
            }
            if (arg.equals("-H") || arg.equals("--stdhelp")) {
                messageStream.append(usage(true, true));
                return false;
            }

            if (arg.equals("--version")) {
                messageStream.println(getVersion());
                return false;
            }

            final String[] pair = arg.split("=", 2);
            if (pair.length == 2) {
                if (pair[1].isEmpty() && i < args.length - 1) {
                    pair[1] = args[++i];
                }
                if (!parseOption(pair[0], pair[1], false)) {
                    messageStream.println();
                    messageStream.append(usage(true, true));
                    return false;
                }
            } else if (!parsePositionalArgument(arg)) {
                messageStream.println();
                messageStream.append(usage(false, true));
                return false;
            }
        }
        if (!checkNumArguments()) {
            messageStream.println();
            messageStream.append(usage(false, true));
            return false;
        }

        return true;
    }
444819
@SuppressWarnings("unchecked")
        public static void executeCommand(String[] args) throws IOException {

            OptionParser parser = getParser();

            // declare parameters
            List<String> metaKeys = null;
            String url = null;
            String dir = null;
            List<Integer> nodeIds = null;
            Boolean allNodes = true;
            Boolean verbose = false;

            // parse command-line input
            args = AdminToolUtils.copyArrayAddFirst(args, "--" + OPT_HEAD_META_GET);
            OptionSet options = parser.parse(args);
            if(options.has(AdminParserUtils.OPT_HELP)) {
                printHelp(System.out);
                return;
            }

            // check required options and/or conflicting options
            AdminParserUtils.checkRequired(options, OPT_HEAD_META_GET);
            AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL);
            AdminParserUtils.checkOptional(options,
                                           AdminParserUtils.OPT_NODE,
                                           AdminParserUtils.OPT_ALL_NODES);

            // load parameters
            metaKeys = (List<String>) options.valuesOf(OPT_HEAD_META_GET);
            url = (String) options.valueOf(AdminParserUtils.OPT_URL);
            if(options.has(AdminParserUtils.OPT_DIR)) {
                dir = (String) options.valueOf(AdminParserUtils.OPT_DIR);
            }
            if(options.has(AdminParserUtils.OPT_NODE)) {
                nodeIds = (List<Integer>) options.valuesOf(AdminParserUtils.OPT_NODE);
                allNodes = false;
            }
            if(options.has(OPT_VERBOSE)) {
                verbose = true;
            }

            // execute command
            File directory = AdminToolUtils.createDir(dir);
            AdminClient adminClient = AdminToolUtils.getAdminClient(url);

            if(allNodes) {
                nodeIds = AdminToolUtils.getAllNodeIds(adminClient);
            }

            if(metaKeys.size() == 1 && metaKeys.get(0).equals(METAKEY_ALL)) {
                metaKeys = Lists.newArrayList();
                for(Object key: MetadataStore.METADATA_KEYS) {
                    metaKeys.add((String) key);
                }
            }

            doMetaGet(adminClient, nodeIds, metaKeys, directory, verbose);
        }
458896
boolean parseCmdLineArgs(String[] args) throws IllegalArgumentException {
        for (int i = 0; i < args.length; i++) {
            if (args[i].toLowerCase().contains("help") || args[i].toLowerCase().contains("usage")) {
                // print the usage information and exit.
                printUsage();
                return true;
            }
            boolean accepted = false;
            for (Option option : options) {
                if (args[i].equalsIgnoreCase(option.name)) {
                    if (i + option.nargs < args.length) {
                        i += option.accept(args, i + 1);
                    } else {
                        throw new IllegalArgumentException(getLocalizedParmString("CWTRA0022E",
                                                                                  new Object[] { option.name, option.nargs }));
                    }
                    accepted = true;
                    break;
                }
            }
            if (!accepted) {
                throw new IllegalArgumentException(getLocalizedParmString("CWTRA0023E", new Object[] { args[i] }));
            }
        }
        return false;
    }
520837
public String[] processOptions(String args[])
    {
        targetPackage = "";        // default to no package
        compilerEnv.setGenerateDebugInfo(false);   // default to no symbols
        for (int i=0; i < args.length; i++) {
            String arg = args[i];
            if (!arg.startsWith("-")) {
                int tail = args.length - i;
                if (targetName != null && tail > 1) {
                    addError("msg.multiple.js.to.file", targetName);
                    return null;
                }
                String[] result = new String[tail];
                for (int j = 0; j != tail; ++j) {
                    result[j] = args[i + j];
                }
                return result;
            }
            if (arg.equals("-help") || arg.equals("-h")
                || arg.equals("--help"))
            {
                printHelp = true;
                return null;
            }

            try {
                if (arg.equals("-version") && ++i < args.length) {
                    int version = Integer.parseInt(args[i]);
                    compilerEnv.setLanguageVersion(version);
                    continue;
                }
                if ((arg.equals("-opt") || arg.equals("-O"))  &&
                    ++i < args.length)
                {
                    int optLevel = Integer.parseInt(args[i]);
                    compilerEnv.setOptimizationLevel(optLevel);
                    continue;
                }
            }
            catch (NumberFormatException e) {
                badUsage(args[i]);
                return null;
            }
            if (arg.equals("-nosource")) {
                compilerEnv.setGeneratingSource(false);
                continue;
            }
            if (arg.equals("-debug") || arg.equals("-g")) {
                compilerEnv.setGenerateDebugInfo(true);
                continue;
            }
            if (arg.equals("-main-method-class") && ++i < args.length) {
                compiler.setMainMethodClass(args[i]);
                continue;
            }
            if (arg.equals("-encoding") && ++i < args.length) {
                characterEncoding = args[i];
                continue;
            }
            if (arg.equals("-o") && ++i < args.length) {
                String name = args[i];
                int end = name.length();
                if (end == 0
                    || !Character.isJavaIdentifierStart(name.charAt(0)))
                {
                    addError("msg.invalid.classfile.name", name);
                    continue;
                }
                for (int j = 1; j < end; j++) {
                    char c = name.charAt(j);
                    if (!Character.isJavaIdentifierPart(c)) {
                        if (c == '.') {
                            // check if it is the dot in .class
                            if (j == end - 6 && name.endsWith(".class")) {
                                name = name.substring(0, j);
                                break;
                            }
                        }
                        addError("msg.invalid.classfile.name", name);
                        break;
                    }
                }
                targetName = name;
                continue;
            }
            if (arg.equals("-observe-instruction-count")) {
                compilerEnv.setGenerateObserverCount(true);
            }
            if (arg.equals("-package") && ++i < args.length) {
                String pkg = args[i];
                int end = pkg.length();
                for (int j = 0; j != end; ++j) {
                    char c = pkg.charAt(j);
                    if (Character.isJavaIdentifierStart(c)) {
                        for (++j; j != end; ++j) {
                            c = pkg.charAt(j);
                            if (!Character.isJavaIdentifierPart(c)) {
                                break;
                            }
                        }
                        if (j == end) {
                            break;
                        }
                        if (c == '.' && j != end - 1) {
                            continue;
                        }
                    }
                    addError("msg.package.name", targetPackage);
                    return null;
                }
                targetPackage = pkg;
                continue;
            }
            if (arg.equals("-extends") && ++i < args.length) {
                String targetExtends = args[i];
                Class<?> superClass;
                try {
                    superClass = Class.forName(targetExtends);
                } catch (ClassNotFoundException e) {
                    throw new Error(e.toString()); // TODO: better error
                }
                compiler.setTargetExtends(superClass);
                continue;
            }
            if (arg.equals("-implements") && ++i < args.length) {
                // TODO: allow for multiple comma-separated interfaces.
                String targetImplements = args[i];
                StringTokenizer st = new StringTokenizer(targetImplements,
                                                         ",");
                List<Class<?>> list = new ArrayList<Class<?>>();
                while (st.hasMoreTokens()) {
                    String className = st.nextToken();
                    try {
                        list.add(Class.forName(className));
                    } catch (ClassNotFoundException e) {
                        throw new Error(e.toString()); // TODO: better error
                    }
                }
                Class<?>[] implementsClasses = list.toArray(new Class<?>[list.size()]);
                compiler.setTargetImplements(implementsClasses);
                continue;
            }
            if (arg.equals("-d") && ++i < args.length) {
                destinationDir = args[i];
                continue;
            }
            badUsage(arg);
            return null;
        }
        // no file name
        p(ToolErrorReporter.getMessage("msg.no.file"));
        return null;
    }