Java Code Examples for org.kohsuke.args4j.CmdLineParser#parseArgument()

The following examples show how to use org.kohsuke.args4j.CmdLineParser#parseArgument() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Main.java    From snmpman with Apache License 2.0 7 votes vote down vote up
/**
 * The application entry-point.
 * <br>
 * All available command-line arguments are documented in the {@link com.oneandone.snmpman.CommandLineOptions} class.
 * <br>
 * If illegal command-line options were specified for execution, a usage help message will be printed out
 * on the {@link System#err} stream and the application will terminate. Otherwise the configuration will
 * be read and used for execution.
 *
 * @param args the command-line arguments
 */
public static void main(final String... args) {
    final CommandLineOptions commandLineOptions = new CommandLineOptions();
    final CmdLineParser cmdLineParser = new CmdLineParser(commandLineOptions);
    try {
        cmdLineParser.parseArgument(args);

        if (commandLineOptions.isShowHelp()) {
            cmdLineParser.printUsage(System.out);
        } else {
            Snmpman.start(commandLineOptions.getConfigurationFile());
        }
    } catch (final InitializationException | CmdLineException e) {
        log.error("could not parse or process command-line arguments", e);
        if (e.getMessage() != null && !e.getMessage().isEmpty()) {
            System.err.println("could not start application because of following error: ");
            System.err.println(e.getMessage());
        } else {
            System.err.println("failed to start application, check the logs for more information");
        }
        cmdLineParser.printUsage(System.err);
    }
}
 
Example 2
Source File: OptionsParser.java    From MOE with Apache License 2.0 6 votes vote down vote up
/**
 * Parses command-line flags, returning true if the parse was successful and no flags errors were
 * found.
 */
// TODO(cgruber) Rework this with JCommander so we can have plugin-specific flags
public boolean parseFlags(MoeOptions options) {
  CmdLineParser parser = new CmdLineParser(options);
  try {
    parser.parseArgument(preprocessedArgs);
    if (options.shouldDisplayHelp()) {
      parser.printUsage(System.err);
    }
    return true;
  } catch (CmdLineException e) {
    logger.log(Level.SEVERE, e.getMessage());
    parser.printUsage(System.err);
    return false;
  }
}
 
Example 3
Source File: CommandLineRunner.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
private void processFlagFile(PrintStream err)
          throws CmdLineException, IOException {
  File flagFileInput = new File(flags.flag_file);
  List<String> argsInFile = tokenizeKeepingQuotedStrings(
      Files.readLines(flagFileInput, Charset.defaultCharset()));

  flags.flag_file = "";
  List<String> processedFileArgs
      = processArgs(argsInFile.toArray(new String[] {}));
  CmdLineParser parserFileArgs = new CmdLineParser(flags);
  Flags.warningGuardSpec.clear();
  parserFileArgs.parseArgument(processedFileArgs.toArray(new String[] {}));

  // Currently we are not supporting this (prevent direct/indirect loops)
  if (!flags.flag_file.equals("")) {
    err.println("ERROR - Arguments in the file cannot contain "
        + "--flagfile option.");
    isConfigValid = false;
  }
}
 
Example 4
Source File: RhistMain.java    From monsoon with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Initialize the verifier, using command-line arguments.
 *
 * @param args The command-line arguments passed to the program.
 */
public RhistMain(String[] args) {
    final CmdLineParser parser = new CmdLineParser(this, ParserProperties.defaults().withUsageWidth(80));
    try {
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        System.err.println(e.getMessage());
        print_usage_and_exit_(parser);
        /* UNREACHABLE */
    }

    // If help is requested, simply print that.
    if (help) {
        print_usage_and_exit_(parser);
        /* UNREACHABLE */
    }

    // If there are no files, comlain with a non-zero exit code.
    if (dir == null)
        System.exit(EX_USAGE);

    path_ = FileSystems.getDefault().getPath(dir);
}
 
Example 5
Source File: Main.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
public static void mainInternal(String[] args) throws Exception {

        Options options = new Options();
        CmdLineParser parser = new CmdLineParser(options);
        try {
            parser.parseArgument(args);
        } catch (CmdLineException e) {
            helpScreen(parser);
            return;
        }

        try {
            List<String> configs = new ArrayList<>();
            if (options.configs != null) {
                configs.addAll(Arrays.asList(options.configs.split(",")));
            }
            ConfigSupport.applyConfigChange(ConfigSupport.getJBossHome(), configs, options.enable);
        } catch (ConfigException ex) {
            ConfigLogger.error(ex);
            throw ex;
        } catch (Throwable th) {
            ConfigLogger.error(th);
            throw th;
        }
    }
 
Example 6
Source File: SingleStringSetOptionHandlerTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void failsIfNoValueBeforeNextOption() throws CmdLineException {
  expected.expect(CmdLineException.class);
  expected.expectMessage("Option \"--set\" takes one operand");
  TestBean bean = new TestBean();
  CmdLineParser parser = new CmdLineParser(bean);
  parser.parseArgument("--set", "--other", "a", "b", "c");
}
 
Example 7
Source File: StringSetOptionHandlerTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultValues() throws CmdLineException {
  TestBean bean = new TestBean();
  CmdLineParser parser = new CmdLineParser(bean);
  parser.parseArgument("--option2", "a", "b");
  assertEquals(ImmutableSet.of(), bean.getOption1());
  assertEquals(ImmutableSet.of("a", "b"), bean.getOption2());
}
 
Example 8
Source File: NetworkProxyServer.java    From Ardulink-1 with Apache License 2.0 5 votes vote down vote up
private void doMain(String[] args) {
	CmdLineParser cmdLineParser = new CmdLineParser(this);
	try {
		cmdLineParser.parseArgument(args);
	} catch (CmdLineException e) {
		System.err.println(e.getMessage());
		cmdLineParser.printUsage(System.err);
		return;
	}
	command.execute(portNumber);
}
 
Example 9
Source File: Main.java    From jbake with MIT License 5 votes vote down vote up
private LaunchOptions parseArguments(String[] args) {
    LaunchOptions res = new LaunchOptions();
    CmdLineParser parser = new CmdLineParser(res);

    try {
        parser.parseArgument(args);
    } catch (final CmdLineException e) {
        printUsage(res);
        throw new JBakeException("Invalid commandline arguments: " + e.getMessage(), e);
    }

    return res;
}
 
Example 10
Source File: DictionaryToRawIndexConverter.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
/**
 * Main method for the class.
 *
 * @param args Arguments for the converter
 * @throws Exception
 */
public static void main(String[] args)
    throws Exception {
  DictionaryToRawIndexConverter converter = new DictionaryToRawIndexConverter();
  CmdLineParser parser = new CmdLineParser(converter);
  parser.parseArgument(args);
  converter.convert();
}
 
Example 11
Source File: ReportDiffer.java    From testability-explorer with Apache License 2.0 5 votes vote down vote up
private void parseArgs(String[] args) throws CmdLineException {
  CmdLineParser parser = new CmdLineParser(this);
  try {
    parser.parseArgument(args);
  } catch (CmdLineException e) {
    System.err.println(e.getMessage() + "\n");
    parser.setUsageWidth(120);
    parser.printUsage(System.err);
    throw new CmdLineException("Exiting...");
  }
}
 
Example 12
Source File: Options.java    From clutz with MIT License 5 votes vote down vote up
Options(String[] args) throws CmdLineException {
  CmdLineParser parser = new CmdLineParser(this);
  parser.parseArgument(args);
  depgraph = Depgraph.parseFrom(depgraphFiles);

  if (arguments.isEmpty()) {
    throw new CmdLineException(parser, "No files were given");
  }
}
 
Example 13
Source File: ArtifactConfig.java    From buck with Apache License 2.0 5 votes vote down vote up
public static ArtifactConfig fromCommandLineArgs(String[] args)
    throws CmdLineException, IOException {

  CmdLineArgs parsedArgs = new CmdLineArgs();
  CmdLineParser parser = new CmdLineParser(parsedArgs);
  parser.parseArgument(args);

  if (parsedArgs.showHelp) {
    usage(parser);
  }

  ArtifactConfig artifactConfig;

  // If the -config argument was specified, load a config from JSON.
  if (parsedArgs.artifactConfigJson != null) {
    artifactConfig =
        ObjectMappers.readValue(Paths.get(parsedArgs.artifactConfigJson), ArtifactConfig.class);
  } else {
    artifactConfig = new ArtifactConfig();
  }

  if (artifactConfig.buckRepoRoot == null && parsedArgs.buckRepoRoot == null) {
    usage(parser);
  }

  artifactConfig.mergeCmdLineArgs(parsedArgs);

  return artifactConfig;
}
 
Example 14
Source File: ClosureCommandLineCompiler.java    From closure-stylesheets with Apache License 2.0 5 votes vote down vote up
/**
 * Processes the specified args to construct a corresponding
 * {@link Flags}. If the args are invalid, prints an appropriate error
 * message, invokes
 * {@link ExitCodeHandler#processExitCode(int)}, and returns null.
 */
@VisibleForTesting
static @Nullable Flags parseArgs(String[] args,
    ExitCodeHandler exitCodeHandler) {
  Flags flags = new Flags();
  CmdLineParser argsParser = new CmdLineParser(flags) {
    @Override
    public void printUsage(OutputStream out) {
      PrintWriter writer = new PrintWriter(new OutputStreamWriter(out));
      writer.write(Flags.USAGE_PREAMBLE);

      // Because super.printUsage() creates its own PrintWriter to wrap the
      // OutputStream, we call flush() on our PrinterWriter first to make sure
      // that everything from this PrintWriter is written to the OutputStream
      // before any usage information.
      writer.flush();
      super.printUsage(out);
    }
  };

  try {
    argsParser.parseArgument(args);
  } catch (CmdLineException e) {
    argsParser.printUsage(System.err);
    exitCodeHandler.processExitCode(ERROR_MESSAGE_EXIT_CODE);
    return null;
  }

  if (flags.arguments.isEmpty()) {
    System.err.println("\nERROR: No input files specified.\n");
    argsParser.printUsage(System.err);
    exitCodeHandler.processExitCode(
        AbstractCommandLineCompiler.ERROR_MESSAGE_EXIT_CODE);
    return null;
  } else {
    return flags;
  }
}
 
Example 15
Source File: MoveReplicaGroup.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args)
    throws Exception {
  MoveReplicaGroup mrg = new MoveReplicaGroup();

  CmdLineParser parser = new CmdLineParser(mrg);
  try {
    parser.parseArgument(args);
  } catch (CmdLineException e) {
    LOGGER.error("Failed to parse arguments: {}", e);
    parser.printUsage(System.err);
    System.exit(1);
  }
  mrg.execute();
}
 
Example 16
Source File: Closure_101_CommandLineRunner_t.java    From coming with MIT License 4 votes vote down vote up
private void initConfigFromFlags(
    String[] args, PrintStream err)
    throws CmdLineException {
  // Args4j has a different format that the old command-line parser.
  // So we use some voodoo to get the args into the format that args4j
  // expects.
  Pattern argPattern = Pattern.compile("(--[a-zA-Z_]+)=(.*)");
  Pattern quotesPattern = Pattern.compile("^['\"](.*)['\"]$");
  List<String> processedArgs = Lists.newArrayList();
  for (String arg : args) {
    Matcher matcher = argPattern.matcher(arg);
    if (matcher.matches()) {
      processedArgs.add(matcher.group(1));

      String value = matcher.group(2);
      Matcher quotesMatcher = quotesPattern.matcher(value);
      if (quotesMatcher.matches()) {
        processedArgs.add(quotesMatcher.group(1));
      } else {
        processedArgs.add(value);
      }
    } else {
      processedArgs.add(arg);
    }
  }

  CmdLineParser parser = new CmdLineParser(flags);
  try {
    parser.parseArgument(processedArgs.toArray(new String[] {}));
  } catch (CmdLineException e) {
    err.println(e.getMessage());
    parser.printUsage(err);
    throw e;
  }
  getCommandLineConfig()
      .setPrintTree(flags.print_tree)
      .setComputePhaseOrdering(flags.compute_phase_ordering)
      .setPrintAst(flags.print_ast)
      .setPrintPassGraph(flags.print_pass_graph)
      .setJscompDevMode(flags.jscomp_dev_mode)
      .setLoggingLevel(flags.logging_level)
      .setExterns(flags.externs)
      .setJs(flags.js)
      .setJsOutputFile(flags.js_output_file)
      .setModule(flags.module)
      .setVariableMapInputFile(flags.variable_map_input_file)
      .setPropertyMapInputFile(flags.property_map_input_file)
      .setVariableMapOutputFile(flags.variable_map_output_file)
      .setCreateNameMapFiles(flags.create_name_map_files)
      .setPropertyMapOutputFile(flags.property_map_output_file)
      .setThirdParty(flags.third_party)
      .setSummaryDetailLevel(flags.summary_detail_level)
      .setOutputWrapper(flags.output_wrapper)
      .setOutputWrapperMarker(flags.output_wrapper_marker)
      .setModuleWrapper(flags.module_wrapper)
      .setModuleOutputPathPrefix(flags.module_output_path_prefix)
      .setCreateSourceMap(flags.create_source_map)
      .setJscompError(flags.jscomp_error)
      .setJscompWarning(flags.jscomp_warning)
      .setJscompOff(flags.jscomp_off)
      .setDefine(flags.define)
      .setCharset(flags.charset);
}
 
Example 17
Source File: Closure_107_CommandLineRunner_s.java    From coming with MIT License 4 votes vote down vote up
private void initConfigFromFlags(String[] args, PrintStream err) {

    List<String> processedArgs = processArgs(args);

    CmdLineParser parser = new CmdLineParser(flags);
    Flags.guardLevels.clear();
    isConfigValid = true;
    try {
      parser.parseArgument(processedArgs.toArray(new String[] {}));
      // For contains --flagfile flag
      if (!flags.flagFile.equals("")) {
        processFlagFile(err);
      }
    } catch (CmdLineException e) {
      err.println(e.getMessage());
      isConfigValid = false;
    } catch (IOException ioErr) {
      err.println("ERROR - " + flags.flagFile + " read error.");
      isConfigValid = false;
    }

    if (flags.version) {
      err.println(
          "Closure Compiler (http://code.google.com/closure/compiler)\n" +
          "Version: " + Compiler.getReleaseVersion() + "\n" +
          "Built on: " + Compiler.getReleaseDate());
      err.flush();
    }

    if (flags.processCommonJsModules) {
      flags.processClosurePrimitives = true;
      flags.manageClosureDependencies = true;
      if (flags.commonJsEntryModule == null) {
        err.println("Please specify --common_js_entry_module.");
        err.flush();
        isConfigValid = false;
      }
      flags.closureEntryPoint = Lists.newArrayList(
          ProcessCommonJSModules.toModuleName(flags.commonJsEntryModule));
    }

    if (!isConfigValid || flags.displayHelp) {
      isConfigValid = false;
      parser.printUsage(err);
    } else {
      CodingConvention conv;
      if (flags.thirdParty) {
        conv = CodingConventions.getDefault();
      } else if (flags.processJqueryPrimitives) {
        conv = new JqueryCodingConvention();
      } else {
        conv = new ClosureCodingConvention();
      }

      getCommandLineConfig()
          .setPrintTree(flags.printTree)
          .setPrintAst(flags.printAst)
          .setPrintPassGraph(flags.printPassGraph)
          .setJscompDevMode(flags.jscompDevMode)
          .setLoggingLevel(flags.loggingLevel)
          .setExterns(flags.externs)
          .setJs(flags.getJsFiles())
          .setJsOutputFile(flags.jsOutputFile)
          .setModule(flags.module)
          .setVariableMapInputFile(flags.variableMapInputFile)
          .setPropertyMapInputFile(flags.propertyMapInputFile)
          .setVariableMapOutputFile(flags.variableMapOutputFile)
          .setCreateNameMapFiles(flags.createNameMapFiles)
          .setPropertyMapOutputFile(flags.propertyMapOutputFile)
          .setCodingConvention(conv)
          .setSummaryDetailLevel(flags.summaryDetailLevel)
          .setOutputWrapper(flags.outputWrapper)
          .setModuleWrapper(flags.moduleWrapper)
          .setModuleOutputPathPrefix(flags.moduleOutputPathPrefix)
          .setCreateSourceMap(flags.createSourceMap)
          .setSourceMapFormat(flags.sourceMapFormat)
          .setWarningGuardSpec(Flags.getWarningGuardSpec())
          .setDefine(flags.define)
          .setCharset(flags.charset)
          .setManageClosureDependencies(flags.manageClosureDependencies)
          .setOnlyClosureDependencies(flags.onlyClosureDependencies)
          .setClosureEntryPoints(flags.closureEntryPoint)
          .setOutputManifest(ImmutableList.of(flags.outputManifest))
          .setOutputModuleDependencies(flags.outputModuleDependencies)
          .setAcceptConstKeyword(flags.acceptConstKeyword)
          .setLanguageIn(flags.languageIn)
          .setProcessCommonJSModules(flags.processCommonJsModules)
          .setCommonJSModulePathPrefix(flags.commonJsPathPrefix)
          .setTransformAMDToCJSModules(flags.transformAmdModules)
          .setWarningsWhitelistFile(flags.warningsWhitelistFile)
          .setAngularPass(flags.angularPass)
          .setTracerMode(flags.tracerMode);
    }
  }
 
Example 18
Source File: Repl.java    From es6draft with MIT License 4 votes vote down vote up
private static void parseOptions(Options options, String[] args) {
    ParserProperties properties = ParserProperties.defaults().withUsageWidth(128);
    CmdLineParser parser = new CmdLineParser(options, properties);
    try {
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        System.err.println(e.getMessage());
        System.err.println(getUsageString(parser, false));
        System.exit(1);
    }
    if (options.showVersion) {
        System.out.println(getVersionString());
        System.exit(0);
    }
    if (options.showHelp) {
        System.out.println(getUsageString(parser, false));
        System.exit(0);
    }
    if (options.showExtendedHelp) {
        System.out.println(getUsageString(parser, true));
        System.exit(0);
    }
    if (options.printCode || options.printCodeWithTypes || options.debugInfo) {
        // Disable interpreter when bytecode is requested
        options.noInterpreter = true;
    }
    if (options.fileName != null) {
        // Execute as last script
        if (options.fileName.toString().equals("-")) {
            // "-" is a short-hand to request reading from System.in
            if (System.console() == null) {
                // System.in is not interactive
                options.evalScripts.add(new EvalString(read(System.in)));
            } else {
                options.interactive = true;
            }
        } else {
            options.evalScripts.add(new EvalPath(options.fileName, EvalPath.Type.Script));
        }
    }
    if (options.evalScripts.isEmpty()) {
        // Default to interactive mode when no files or expressions were set
        options.interactive = true;
    }
}
 
Example 19
Source File: Closure_101_CommandLineRunner_s.java    From coming with MIT License 4 votes vote down vote up
private void initConfigFromFlags(
    String[] args, PrintStream err)
    throws CmdLineException {
  // Args4j has a different format that the old command-line parser.
  // So we use some voodoo to get the args into the format that args4j
  // expects.
  Pattern argPattern = Pattern.compile("(--[a-zA-Z_]+)=(.*)");
  Pattern quotesPattern = Pattern.compile("^['\"](.*)['\"]$");
  List<String> processedArgs = Lists.newArrayList();
  for (String arg : args) {
    Matcher matcher = argPattern.matcher(arg);
    if (matcher.matches()) {
      processedArgs.add(matcher.group(1));

      String value = matcher.group(2);
      Matcher quotesMatcher = quotesPattern.matcher(value);
      if (quotesMatcher.matches()) {
        processedArgs.add(quotesMatcher.group(1));
      } else {
        processedArgs.add(value);
      }
    } else {
      processedArgs.add(arg);
    }
  }

  CmdLineParser parser = new CmdLineParser(flags);
  try {
    parser.parseArgument(processedArgs.toArray(new String[] {}));
  } catch (CmdLineException e) {
    err.println(e.getMessage());
    parser.printUsage(err);
    throw e;
  }
  getCommandLineConfig()
      .setPrintTree(flags.print_tree)
      .setComputePhaseOrdering(flags.compute_phase_ordering)
      .setPrintAst(flags.print_ast)
      .setPrintPassGraph(flags.print_pass_graph)
      .setJscompDevMode(flags.jscomp_dev_mode)
      .setLoggingLevel(flags.logging_level)
      .setExterns(flags.externs)
      .setJs(flags.js)
      .setJsOutputFile(flags.js_output_file)
      .setModule(flags.module)
      .setVariableMapInputFile(flags.variable_map_input_file)
      .setPropertyMapInputFile(flags.property_map_input_file)
      .setVariableMapOutputFile(flags.variable_map_output_file)
      .setCreateNameMapFiles(flags.create_name_map_files)
      .setPropertyMapOutputFile(flags.property_map_output_file)
      .setThirdParty(flags.third_party)
      .setSummaryDetailLevel(flags.summary_detail_level)
      .setOutputWrapper(flags.output_wrapper)
      .setOutputWrapperMarker(flags.output_wrapper_marker)
      .setModuleWrapper(flags.module_wrapper)
      .setModuleOutputPathPrefix(flags.module_output_path_prefix)
      .setCreateSourceMap(flags.create_source_map)
      .setJscompError(flags.jscomp_error)
      .setJscompWarning(flags.jscomp_warning)
      .setJscompOff(flags.jscomp_off)
      .setDefine(flags.define)
      .setCharset(flags.charset);
}
 
Example 20
Source File: StringSetOptionHandlerTest.java    From buck with Apache License 2.0 4 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testOptionSpecifiedWithoutElements() throws CmdLineException {
  TestBean bean = new TestBean();
  CmdLineParser parser = new CmdLineParser(bean);
  parser.parseArgument("--option1", "a", "--option2", "c", "d", "--option1", "--option2", "f");
}