org.kohsuke.args4j.CmdLineParser Java Examples

The following examples show how to use org.kohsuke.args4j.CmdLineParser. 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 newts with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example #2
Source File: LaserArgument.java    From laser with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #3
Source File: Amidst.java    From amidst with GNU General Public License v3.0 6 votes vote down vote up
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);
	}
}
 
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: ArtifactConfigTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #6
Source File: Closure_107_CommandLineRunner_s.java    From coming with MIT License 6 votes vote down vote up
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;
  }
}
 
Example #7
Source File: BazelDeps.java    From bazel-deps with MIT License 6 votes vote down vote up
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);
}
 
Example #8
Source File: Verify.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 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);
}
 
Example #9
Source File: PublishCommand.java    From griffin with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example #10
Source File: ChatService.java    From flowchat with GNU General Public License v3.0 6 votes vote down vote up
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;
    }
}
 
Example #11
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 #12
Source File: Amidst.java    From amidst with GNU General Public License v3.0 6 votes vote down vote up
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());
	}
}
 
Example #13
Source File: Main.java    From dashencrypt with Mozilla Public License 2.0 6 votes vote down vote up
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);
    }

}
 
Example #14
Source File: FileConvert.java    From monsoon with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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);
}
 
Example #15
Source File: PojoGenerator.java    From logparser with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #16
Source File: ConfigModule.java    From testability-explorer with Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example #17
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 #18
Source File: NewtsDaemon.java    From newts with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        CommandLine cmdLine = new CommandLine();
        CmdLineParser parser = new CmdLineParser(cmdLine);

        try {
            parser.parseArgument(args);
        }
        catch (CmdLineException e) {
            System.err.println(e.getLocalizedMessage());
            usage(parser, System.err);
            System.exit(1);
        }

        // Help requested
        if (cmdLine.needHelp()) {
            usage(parser, System.out);
            System.exit(0);
        }

        // Configuration file does not exist.
        if (!new File(cmdLine.getConfigFilename()).isFile()) {
            System.err.printf("No such file: %s%n", cmdLine.getConfigFilename());
            System.exit(1);
        }

        File pidFile = new File(cmdLine.getPidFilename());

        // Daemonize?
        if (cmdLine.isDaemon()) {
            new Daemon().withMainArgs(args).withPidFile(pidFile).daemonize();
        }

        new NewtsService().run(new String[] { "server", cmdLine.getConfigFilename() });

    }
 
Example #19
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 #20
Source File: FlinkMiniClusterEntryPoint.java    From beam with Apache License 2.0 5 votes vote down vote up
private static void printUsage(CmdLineParser parser) {
  System.err.println(
      String.format(
          "Usage: java %s arguments...", FlinkMiniClusterEntryPoint.class.getSimpleName()));
  parser.printUsage(System.err);
  System.err.println();
}
 
Example #21
Source File: CommandLineOptionsTest.java    From snmpman with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #22
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 #23
Source File: FlinkPortableClientEntryPoint.java    From beam with Apache License 2.0 5 votes vote down vote up
private static EntryPointConfiguration parseArgs(String[] args) {
  EntryPointConfiguration configuration = new EntryPointConfiguration();
  CmdLineParser parser = new CmdLineParser(configuration);
  try {
    parser.parseArgument(args);
  } catch (CmdLineException e) {
    LOG.error("Unable to parse command line arguments.", e);
    parser.printUsage(System.err);
    throw new IllegalArgumentException("Unable to parse command line arguments.", e);
  }
  return configuration;
}
 
Example #24
Source File: FileConvert.java    From monsoon with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * 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);
}
 
Example #25
Source File: LaunchOptionsTest.java    From jbake with MIT License 5 votes vote down vote up
@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");
}
 
Example #26
Source File: StringSetOptionHandlerTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void testOptionSpecifiedMultipleTimes() throws CmdLineException {
  TestBean bean = new TestBean();
  CmdLineParser parser = new CmdLineParser(bean);
  parser.parseArgument(
      "--option1", "a", "b", "--option2", "c", "d", "--option1", "e", "f", "--option2", "g", "h");
  assertEquals(ImmutableSet.of("a", "b", "e", "f"), bean.getOption1());
  assertEquals(ImmutableSet.of("c", "d", "g", "h"), bean.getOption2());
}
 
Example #27
Source File: SparkPipelineRunner.java    From beam with Apache License 2.0 5 votes vote down vote up
private static SparkPipelineRunnerConfiguration parseArgs(String[] args) {
  SparkPipelineRunnerConfiguration configuration = new SparkPipelineRunnerConfiguration();
  CmdLineParser parser = new CmdLineParser(configuration);
  try {
    parser.parseArgument(args);
  } catch (CmdLineException e) {
    LOG.error("Unable to parse command line arguments.", e);
    parser.printUsage(System.err);
    throw new IllegalArgumentException("Unable to parse command line arguments.", e);
  }
  return configuration;
}
 
Example #28
Source File: RuntimeUtil.java    From indexr with Apache License 2.0 5 votes vote down vote up
public static CmdLineParser parseArgs(String[] args, Object t) {
    CmdLineParser parser = new CmdLineParser(t);
    try {
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        e.printStackTrace();
        System.err.println(e.getMessage());
        parser.printUsage(System.err);
        System.err.println();
        System.exit(1);
    }
    return parser;
}
 
Example #29
Source File: LaunchOptionsTest.java    From jbake with MIT License 5 votes vote down vote up
@Test
public void initWithTemplateAndSourceDirectory() throws Exception {
    String[] args = {"-i", "-t", "foo", "/tmp"};
    LaunchOptions res = new LaunchOptions();
    CmdLineParser parser = new CmdLineParser(res);
    parser.parseArgument(args);

    assertThat(res.isInit()).isTrue();
    assertThat(res.getTemplate()).isEqualTo("foo");
    assertThat(res.getSourceValue()).isEqualTo("/tmp");
}
 
Example #30
Source File: RestMain.java    From Ardulink-2 with Apache License 2.0 5 votes vote down vote up
static Optional<CommandLineArguments> tryParse(String... args) {
	CommandLineArguments cmdLineArgs = new CommandLineArguments();
	CmdLineParser cmdLineParser = new CmdLineParser(cmdLineArgs);
	try {
		cmdLineParser.parseArgument(args);
		return Optional.of(cmdLineArgs);
	} catch (CmdLineException e) {
		System.err.println(e.getMessage());
		cmdLineParser.printUsage(System.err);
		return Optional.empty();
	}
}