Java源码示例:org.kohsuke.args4j.CmdLineParser
示例1
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;
}
}
示例2
/**
* Executes the command
*/
@Override
public void execute() {
if (help) {
System.out.println("Publish the content in the current Griffin directory.");
System.out.println("usage: griffin publish [option]");
System.out.println("Options: " + LINE_SEPARATOR);
CmdLineParser parser = new CmdLineParser(this, ParserProperties.defaults().withUsageWidth(120));
parser.printUsage(System.out);
return;
}
try {
Griffin griffin = new Griffin();
griffin.printAsciiGriffin();
griffin.publish(fastParse, rebuild);
System.out.println("All done for now! I will be bach!");
}
catch (IOException | InterruptedException ex) {
Logger.getLogger(PublishCommand.class.getName()).log(Level.SEVERE, null, ex);
}
}
示例3
private static void parseCommandLineArgumentsAndRun(String[] args) {
CommandLineParameters parameters = new CommandLineParameters();
AmidstMetaData metadata = createMetadata();
CmdLineParser parser = new CmdLineParser(
parameters,
ParserProperties.defaults().withShowDefaults(false).withUsageWidth(120).withOptionSorter(null));
try {
parser.parseArgument(args);
run(parameters, metadata, parser);
} catch (CmdLineException e) {
System.out.println(metadata.getVersion().createLongVersionString());
System.err.println(e.getMessage());
parser.printUsage(System.out);
System.exit(2);
}
}
示例4
private void processFlagFile(PrintStream err)
throws CmdLineException, IOException {
File flagFileInput = new File(flags.flagFile);
List<String> argsInFile = tokenizeKeepingQuotedStrings(
Files.readLines(flagFileInput, Charset.defaultCharset()));
flags.flagFile = "";
List<String> processedFileArgs
= processArgs(argsInFile.toArray(new String[] {}));
CmdLineParser parserFileArgs = new CmdLineParser(flags);
// Command-line warning levels should override flag file settings,
// which means they should go last.
List<GuardLevel> previous = Lists.newArrayList(Flags.guardLevels);
Flags.guardLevels.clear();
parserFileArgs.parseArgument(processedFileArgs.toArray(new String[] {}));
Flags.guardLevels.addAll(previous);
// Currently we are not supporting this (prevent direct/indirect loops)
if (!flags.flagFile.equals("")) {
err.println("ERROR - Arguments in the file cannot contain "
+ "--flagfile option.");
isConfigValid = false;
}
}
示例5
private void parseArguments(String[] args) {
CmdLineParser parser = new CmdLineParser(this);
try {
parser.parseArgument(args);
} catch (CmdLineException e) {
// if there's a problem in the command line,
// you'll get this exception. this will report
// an error message.
System.err.println(e.getMessage());
System.err.println("java -jar reddit-history.jar [options...] arguments...");
// print the list of available options
parser.printUsage(System.err);
System.err.println();
System.exit(0);
return;
}
}
示例6
public static void main(String[] args) throws Exception {
System.out.println(TOOL);
Main m = new Main();
CmdLineParser parser = new CmdLineParser(m);
try {
parser.parseArgument(args);
m.setupLogger();
m.command.postProcessCmdLineArgs(new CmdLineParser(m.command));
m.command.run();
} catch (CmdLineException e) {
System.err.println(e.getMessage());
e.getParser().printSingleLineUsage(System.err);
System.err.println();
e.getParser().printUsage(System.err);
System.exit(1023);
}
}
示例7
public static void parseArgs(String[] args) throws CmdLineException,
IOException {
ArrayList<String> argsList = new ArrayList<String>(Arrays.asList(args));
for (int i = 0; i < args.length; i++) {
if (i % 2 == 0 && !LaserArgument.VALID_ARGUMENTS.contains(args[i])) {
argsList.remove(args[i]);
argsList.remove(args[i + 1]);
}
}
final LaserArgument laserArgument = new LaserArgument();
new CmdLineParser(laserArgument).parseArgument(argsList
.toArray(new String[argsList.size()]));
Configuration conf = Configuration.getInstance();
LOG.info("Load configure, {}", laserArgument.getConfigure());
Path path = new Path(laserArgument.getConfigure());
FileSystem fs = FileSystem
.get(new org.apache.hadoop.conf.Configuration());
conf.load(path, fs);
}
示例8
/**
* 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);
}
示例9
/**
* Initialize the verifier, using command-line arguments.
* @param args The command-line arguments passed to the program.
*/
public Verify(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 (files.isEmpty())
System.exit(EX_USAGE);
}
示例10
private static void parseArguments(Config config, String... args) {
CmdLineParser parser = new CmdLineParser(config);
try {
parser.parseArgument(args);
}
catch (CmdLineException e) {
// handling of wrong arguments
System.err.println(e.getMessage());
printUsage(System.err, parser);
System.exit(1);
}
if (config.needHelp()) {
printUsage(System.out, parser);
System.exit(0);
}
}
示例11
private static void run(CommandLineParameters parameters, AmidstMetaData metadata, CmdLineParser parser) {
initFileLogger(parameters.logFile);
String versionString = metadata.getVersion().createLongVersionString();
if (parameters.printHelp) {
System.out.println(versionString);
parser.printUsage(System.out);
} else if (parameters.printVersion) {
System.out.println(versionString);
} else {
AmidstLogger.info(versionString);
logTimeAndProperties();
enableGraphicsAcceleration();
osxMenuProperties();
startApplication(parameters, metadata, createSettings());
}
}
示例12
public void doMain(String[] args) throws DependencyCollectionException, CmdLineException {
CmdLineParser parser = new CmdLineParser(this);
parser.parseArgument(args);
if (artifactNames.isEmpty()) {
System.out.print("Usage: java -jar bazel-deps-1.0-SNAPSHOT");
parser.printSingleLineUsage(System.out);
System.out.println();
parser.printUsage(System.out);
System.out.println(
"\nExample: java -jar bazel-deps-1.0-SNAPSHOT com.fasterxml.jackson.core:jackson-databind:2.5.0");
System.exit(1);
}
System.err.println("Fetching dependencies from maven...\n");
Map<Artifact, Set<Artifact>> dependencies = fetchDependencies(artifactNames);
Set<Artifact> excludeDependencies =
excludeArtifact != null ? Maven.transitiveDependencies(new DefaultArtifact(excludeArtifact))
: ImmutableSet.of();
printWorkspace(dependencies, excludeDependencies);
printBuildEntries(dependencies, excludeDependencies);
}
示例13
@Test
public void shouldMergeCmdLineArgsCorrectly() throws IOException, CmdLineException {
String jsonString =
"{\"repositories\": [{\"url\":\"https://example.com\"}],"
+ "\"third_party\":\"tp0\","
+ "\"repo\":\"br\","
+ "\"visibility\":[\"r1\"],"
+ "\"artifacts\":[\"artifact1\"]}";
ArtifactConfig base = ObjectMappers.readValue(jsonString, ArtifactConfig.class);
ArtifactConfig.CmdLineArgs args = new ArtifactConfig.CmdLineArgs();
CmdLineParser parser = new CmdLineParser(args);
parser.parseArgument(
"-third-party", "tp1", "-maven", "http://bar.co", "artifact2", "-visibility", "r2");
base.mergeCmdLineArgs(args);
assertEquals("tp1", base.thirdParty);
assertEquals(base.artifacts, Lists.newArrayList("artifact1", "artifact2"));
assertEquals(base.visibility, Lists.newArrayList("r1", "r2"));
assertEquals("br", base.buckRepoRoot);
assertEquals("https://example.com", base.repositories.get(0).getUrl());
assertEquals("http://bar.co", base.repositories.get(1).getUrl());
}
示例14
public boolean parseArgs(String[] args) {
var parser = new CmdLineParser(this);
try {
parser.parseArgument(args);
return true;
} catch (CmdLineException e) {
LOGGER.error("Could not parse command line arguments: {}", e.getLocalizedMessage());
return false;
}
}
示例15
@Test
public void test1() throws CmdLineException, IOException {
Main m = new Main();
CmdLineParser cmdLineParser = new CmdLineParser(m);
File f = File.createTempFile("aaa", ".jpg");
cmdLineParser.parseArgument(f.getParent() + "/*.jpg[vtiles=5,htiles=6,thduration=7]");
Assert.assertEquals("5", m.i.getOutputOptions().get("vtiles"));
Assert.assertEquals("6", m.i.getOutputOptions().get("htiles"));
Assert.assertEquals("7", m.i.getOutputOptions().get("thduration"));
}
示例16
@Override
public void execute(Configuration conf, String[] args) throws Exception {
CmdLineParser parser = new CmdLineParser(this);
try {
parser.parseArgument(args);
} catch (CmdLineException e) {
System.err.println(e.getMessage());
System.err.println("s3mper meta delete_ts [options]");
// print the list of available options
parser.printUsage(System.err);
System.err.println();
System.err.println(" Example: s3mper meta delete_ts "+parser.printExample(OptionHandlerFilter.ALL));
return;
}
MetastoreJanitor janitor = new MetastoreJanitor();
janitor.initalize(PathUtil.S3N, conf);
janitor.setScanLimit(readUnits);
janitor.setDeleteLimit(writeUnits);
janitor.setScanThreads(scanThreads);
janitor.setDeleteThreads(deleteThreads);
janitor.deleteTimeseries(TimeUnit.valueOf(unitType.toUpperCase()), unitCount);
}
示例17
public static void main(String[] args) throws NoSuchMethodException, MissingDissectorsException, InvalidDissectorException {
PojoGenerator generator = new PojoGenerator();
CmdLineParser parser = new CmdLineParser(generator);
try {
parser.parseArgument(args);
generator.run();
} catch (CmdLineException e) {
// handling of wrong arguments
System.err.println(e.getMessage());
parser.printUsage(System.err);
}
}
示例18
@Test
public void bakeNoArgs() throws Exception {
String[] args = {};
LaunchOptions res = new LaunchOptions();
CmdLineParser parser = new CmdLineParser(res);
parser.parseArgument(args);
assertThat(res.isHelpNeeded()).isTrue();
assertThat(res.isRunServer()).isFalse();
assertThat(res.isInit()).isFalse();
assertThat(res.isBake()).isFalse();
assertThat(res.getSource().getPath()).isEqualTo(System.getProperty("user.dir"));
assertThat(res.getDestination().getPath()).isEqualTo(System.getProperty("user.dir") + File.separator + "output");
}
示例19
public static void main(String[] args)
throws Exception {
VerifySegmentState verifier = new VerifySegmentState();
CmdLineParser cmdLineParser = new CmdLineParser(verifier);
try {
cmdLineParser.parseArgument(args);
} catch (CmdLineException e) {
LOGGER.error("Failed to read command line arguments: ", e);
cmdLineParser.printUsage(System.err);
System.exit(1);
}
verifier.execute();
}
示例20
private void showGPUList(CmdLineParser parser) {
try {
parser.parseArgument("--show-gpu");
}
catch (CmdLineException e) {
System.err.println(String.format("ERROR: Unable to parse the provided parameter [%s]", e.getMessage()));
}
}
示例21
/**
* Validate arguments which are mandatory only in some circumstances.
*
* @param parser
* the command line parser.
* @return the {@link Collection} of genconf {@link URI}
* @throws CmdLineException
* if the arguments are not valid.
*/
private Collection<URI> validateArguments(CmdLineParser parser) throws CmdLineException {
Collection<URI> result = new ArrayList<URI>();
/*
* some arguments are required if one is missing or invalid throw a
* CmdLineException
*/
if (genconfs == null || genconfs.length == 0) {
throw new CmdLineException(parser, "You must specify genconfs models.");
}
for (String modelPath : genconfs) {
URI rawURI = null;
try {
rawURI = URI.createURI(modelPath, true);
} catch (IllegalArgumentException e) {
/*
* the passed uri is not in the URI format and should be
* considered as a direct file denotation.
*/
}
if (rawURI != null && !rawURI.hasAbsolutePath()) {
rawURI = URI.createFileURI(modelPath);
}
result.add(rawURI);
}
return result;
}
示例22
public OptionalOptionHandler(
CmdLineParser parser, OptionDef option, Setter<? super Optional<?>> setter
) {
super(parser, option, setter);
final Field f = (Field) setter.asFieldSetter().asAnnotatedElement();
final ParameterizedType p = (ParameterizedType) f.getGenericType();
this.type = p.getActualTypeArguments()[0];
}
示例23
@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());
}
示例24
public FileConvert(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 verbose mode is requested, dial up the log spam.
if (verbose) {
Logger.getLogger("com.groupon.lex").setLevel(Level.INFO);
Logger.getLogger("com.github.groupon.monsoon").setLevel(Level.INFO);
}
// If there are no files, comlain with a non-zero exit code.
if (srcdir == null)
System.exit(EX_USAGE);
srcdir_path_ = FileSystems.getDefault().getPath(srcdir);
}
示例25
@Override
protected void configure() {
// For printing errors to the caller
bind(PrintStream.class).annotatedWith(Output.class).toInstance(System.out);
bind(PrintStream.class).annotatedWith(Error.class).toInstance(System.err);
CommandLineConfig config = new CommandLineConfig(out, err);
CmdLineParser parser = new CmdLineParser(config);
// We actually do this work in configure, since we want to bind the parsed command line
// options at this time
try {
parser.parseArgument(args);
config.validate();
bind(ClassPath.class).toInstance(new ClassPathFactory().createFromPath(config.cp));
bind(ReportFormat.class).toInstance(config.format);
} catch (CmdLineException e) {
err.println(e.getMessage() + "\n");
parser.setUsageWidth(120);
parser.printUsage(err);
err.println("Exiting...");
}
bind(CommandLineConfig.class).toInstance(config);
bind(ReportOptions.class).toInstance(new ReportOptions(
config.cyclomaticMultiplier, config.globalMultiplier, config.constructorMultiplier,
config.maxExcellentCost, config.maxAcceptableCost, config.worstOffenderCount,
config.maxMethodCount, config.maxLineCount, config.printDepth, config.minCost,
config.srcFileLineUrl, config.srcFileUrl));
bindConstant().annotatedWith(Names.named("printDepth")).to(config.printDepth);
bind(new TypeLiteral<List<String>>() {}).toInstance(config.entryList);
//TODO: install the appropriate language-specific module
install(new JavaTestabilityModule(config));
}
示例26
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;
}
示例27
@Test
public void testGetAgents() throws Exception {
final CommandLineOptions commandLineOptions = new CommandLineOptions();
final CmdLineParser cmdLineParser = new CmdLineParser(commandLineOptions);
cmdLineParser.parseArgument("-c", "src/test/resources/configuration/configuration.yaml");
assertEquals(commandLineOptions.getConfigurationFile().getName(), "configuration.yaml");
assertTrue(commandLineOptions.getConfigurationFile().exists());
assertTrue(commandLineOptions.getConfigurationFile().isFile());
}
示例28
/**
* 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;
}
}
示例29
/**
* Initialize the verifier, using command-line arguments.
*
* @param args The command-line arguments passed to the program.
*/
public FileConvert(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 verbose mode is requested, dial up the log spam.
if (verbose)
Logger.getLogger("com.groupon.lex").setLevel(Level.INFO);
// If there are no files, comlain with a non-zero exit code.
if (srcdir == null || dstdir == null)
System.exit(EX_USAGE);
srcdir_path_ = FileSystems.getDefault().getPath(srcdir);
dstdir_path_ = FileSystems.getDefault().getPath(dstdir);
}
示例30
@Test
public void init() throws Exception {
String[] args = {"-i"};
LaunchOptions res = new LaunchOptions();
CmdLineParser parser = new CmdLineParser(res);
parser.parseArgument(args);
assertThat(res.isInit()).isTrue();
assertThat(res.getTemplate()).isEqualTo("freemarker");
}