org.kohsuke.args4j.CmdLineException Java Examples

The following examples show how to use org.kohsuke.args4j.CmdLineException. 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: MqttMain.java    From Ardulink-1 with Apache License 2.0 6 votes vote down vote up
public void doMain(String... args) throws MqttSecurityException,
		MqttException, InterruptedException {
	CmdLineParser cmdLineParser = new CmdLineParser(this);
	try {
		cmdLineParser.parseArgument(args);
	} catch (CmdLineException e) {
		System.err.println(e.getMessage());
		cmdLineParser.printUsage(System.err);
		return;
	}

	connectToMqttBroker();
	try {
		wait4ever();
	} finally {
		close();
	}

}
 
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: MqttMain.java    From Ardulink-2 with Apache License 2.0 6 votes vote down vote up
public void doMain(String... args) throws Exception {
	CmdLineParser cmdLineParser = new CmdLineParser(this);
	try {
		cmdLineParser.parseArgument(args);
	} catch (CmdLineException e) {
		System.err.println(e.getMessage());
		cmdLineParser.printUsage(System.err);
		return;
	}

	connectToMqttBroker();
	try {
		wait4ever();
	} finally {
		close();
	}

}
 
Example #5
Source File: QueryMultiSetOptionHandler.java    From buck with Apache License 2.0 6 votes vote down vote up
/** Tries to parse {@code String[]} argument from {@link Parameters}. */
@Override
public int parseArguments(Parameters params) throws CmdLineException {
  int counter = 0;
  for (; counter < params.size(); counter++) {
    String param = params.getParameter(counter);

    // Special case the -- separator
    if (param.startsWith("-") && !param.equals(QueryNormalizer.SET_SEPARATOR)) {
      break;
    }

    setter.addValue(param);
  }

  return counter;
}
 
Example #6
Source File: CommandLineArgs.java    From FlowSpaceFirewall with Apache License 2.0 6 votes vote down vote up
public CommandLineArgs(String... args){
	CmdLineParser parser = new CmdLineParser(this);
	parser.setUsageWidth(80);
	try{
		parser.parseArgument(args);
		
		if(!getConfig().isFile()){
			throw new CmdLineException(parser, "--config is not a valid file.");
		}
		
		errorFree = true;
	} catch(CmdLineException e){
		System.err.println(e.getMessage());
		parser.printUsage(System.err);
	}
}
 
Example #7
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 #8
Source File: TestCommandTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void testLabelConjunctionsWithExclude() throws CmdLineException {
  TestCommand command = getCommand("--exclude", "windows+linux");

  TestRule rule1 =
      new FakeTestRule(
          ImmutableSet.of("windows", "linux"),
          BuildTargetFactory.newInstance("//:for"),
          ImmutableSortedSet.of());

  TestRule rule2 =
      new FakeTestRule(
          ImmutableSet.of("windows"),
          BuildTargetFactory.newInstance("//:lulz"),
          ImmutableSortedSet.of());

  List<TestRule> testRules = ImmutableList.of(rule1, rule2);

  Iterable<TestRule> result =
      command.filterTestRules(FakeBuckConfig.builder().build(), ImmutableSet.of(), testRules);
  assertEquals(ImmutableSet.of(rule2), result);
}
 
Example #9
Source File: TestCommandTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void testIfALabelIsIncludedItShouldNotBeExcludedEvenIfTheExcludeIsGlobal()
    throws CmdLineException {
  BuckConfig config =
      FakeBuckConfig.builder()
          .setSections(ImmutableMap.of("test", ImmutableMap.of("excluded_labels", "e2e")))
          .build();
  assertThat(
      config.getView(TestBuckConfig.class).getDefaultRawExcludedLabelSelectors(),
      contains("e2e"));
  TestCommand command = new TestCommand();

  CmdLineParserFactory.create(command).parseArgument("--include", "e2e");

  assertTrue(command.isMatchedByLabelOptions(config, ImmutableSet.of("e2e")));
}
 
Example #10
Source File: UIMan.java    From tuffylite with Apache License 2.0 6 votes vote down vote up
public static CommandOptions parseCommand(String[] args){
	CommandOptions opt = new CommandOptions();
	CmdLineParser parser = new CmdLineParser(opt);
	try{
		parser.parseArgument(args);
		if(opt.showHelp){
			UIMan.println("USAGE:");
            parser.printUsage(System.out);
            return null;
		}
	}catch(CmdLineException e){
		System.err.println(e.getMessage());
		UIMan.println("USAGE:");
           parser.printUsage(System.out);
           return null;
	}

	return processOptions(opt);
}
 
Example #11
Source File: CLI.java    From audiveris with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Parse the CLI arguments and return the populated parameters structure.
 *
 * @param args the CLI arguments
 * @return the parsed parameters, or null if failed
 * @throws org.kohsuke.args4j.CmdLineException if error found in arguments
 */
public Parameters parseParameters (final String... args)
        throws CmdLineException
{
    logger.info("CLI args: {}", Arrays.toString(args));

    // Bug fix if an arg is made of spaces
    trimmedArgs = new String[args.length];

    for (int i = 0; i < args.length; i++) {
        trimmedArgs[i] = args[i].trim();
    }

    parser.parseArgument(trimmedArgs);

    if (logger.isDebugEnabled()) {
        new Dumping().dump(params);
    }

    checkParams();

    return params;
}
 
Example #12
Source File: ApiBin.java    From monsoon with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public ApiBin(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 */
    }
}
 
Example #13
Source File: CliOptionsTest.java    From plugin-installation-manager-tool with MIT License 6 votes vote down vote up
@Test
public void setupUpdateCenterEnvVarTest() throws CmdLineException {
    String ucEnvVar = "https://updates.jenkins.io/env";
    String experimentalUcEnvVar = "https://updates.jenkins.io/experimental/env";
    String incrementalsEnvVar = "https://repo.jenkins-ci.org/incrementals/env";
    String pluginInfoEnvVar = "https://updates.jenkins.io/current/plugin-versions/env";

    mockStatic(System.class);
    when(System.getenv("JENKINS_UC")).thenReturn(ucEnvVar);
    when(System.getenv("JENKINS_UC_EXPERIMENTAL")).thenReturn(experimentalUcEnvVar);
    when(System.getenv("JENKINS_INCREMENTALS_REPO_MIRROR")).thenReturn(incrementalsEnvVar);
    when(System.getenv("JENKINS_PLUGIN_INFO")).thenReturn(pluginInfoEnvVar);

    Config cfg = options.setup();
    assertEquals(ucEnvVar, cfg.getJenkinsUc().toString());
    assertEquals(experimentalUcEnvVar, cfg.getJenkinsUcExperimental().toString());
    assertEquals(incrementalsEnvVar, cfg.getJenkinsIncrementalsRepoMirror().toString());
    assertEquals(pluginInfoEnvVar, cfg.getJenkinsPluginInfo().toString());
}
 
Example #14
Source File: TargetDeviceCommandLineOptionsTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void serialFlagOverridesEnvironment() {
  TargetDeviceCommandLineOptions options = new TargetDeviceCommandLineOptions("1234");

  TargetDevice device = options.getTargetDeviceOptional().get();

  assertEquals("1234", device.getIdentifier().get());

  try {
    new CmdLineParser(options).parseArgument("-s", "5678");
  } catch (CmdLineException e) {
    fail("Unable to parse arguments");
  }

  device = options.getTargetDeviceOptional().get();

  assertEquals("5678", device.getIdentifier().get());
}
 
Example #15
Source File: EnumArrayOptionHandler.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
/**
 * Tries to parse {@code String[]} argument from {@link Parameters}.
 */
@Override
public int parseArguments(Parameters params)
    throws CmdLineException {
  int counter = 0;
  for (; counter < params.size(); counter++) {
    String param = params.getParameter(counter);

    if (param.startsWith("-")) {
      break;
    }

    for (String p : param.split(" ")) {
      Class<T> t = (Class<T>) setter.getType();
      setter.addValue(Enum.valueOf(t, p));
    }
  }

  return counter;
}
 
Example #16
Source File: InstallCommandOptionsTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void testInstallCommandOptionsActivity() throws CmdLineException {
  InstallCommand command =
      getCommand("katana", InstallCommand.ACTIVITY_SHORT_ARG, ".LoginActivity");
  assertTrue(command.shouldStartActivity());
  assertEquals(".LoginActivity", command.getActivityToStart());
}
 
Example #17
Source File: TestCommandTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoTransitiveTestsWhenLabelExcludeWins() throws CmdLineException {
  TestCommand command =
      getCommand(
          "--labels",
          "!linux",
          "--always-exclude",
          "--exclude-transitive-tests",
          "//:for",
          "//:lulz");

  FakeTestRule rule1 =
      new FakeTestRule(
          ImmutableSet.of("windows", "linux"),
          BuildTargetFactory.newInstance("//:for"),
          ImmutableSortedSet.of());

  FakeTestRule rule2 =
      new FakeTestRule(
          ImmutableSet.of("windows"),
          BuildTargetFactory.newInstance("//:lulz"),
          ImmutableSortedSet.of(rule1));

  List<TestRule> testRules = ImmutableList.of(rule1, rule2);
  Iterable<TestRule> filtered =
      command.filterTestRules(
          FakeBuckConfig.builder().build(),
          ImmutableSet.of(
              BuildTargetFactory.newInstance("//:for"),
              BuildTargetFactory.newInstance("//:lulz")),
          testRules);

  assertEquals(rule2, Iterables.getOnlyElement(filtered));
}
 
Example #18
Source File: RunCommandOptionsTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void testDoubleDash4() throws CmdLineException {
  String[] args =
      new String[] {"//some/target", "arg1", "--opt1", "something", "--", "--opt2", "something"};
  expectedException.expect(CmdLineException.class);
  expectedException.expectMessage("\"--opt1\" is not a valid option");
  testWithArgs(args);
}
 
Example #19
Source File: Repl.java    From es6draft with MIT License 5 votes vote down vote up
@Override
protected Integer parse(String argument) throws NumberFormatException, CmdLineException {
    int value = Integer.parseInt(argument);
    Range range = setter.asAnnotatedElement().getAnnotation(Range.class);
    if (range != null && value != Math.min(Math.max(value, range.min()), range.max())) {
        throw new NumberFormatException();
    }
    return value;
}
 
Example #20
Source File: SingleStringSetOptionHandlerTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void failsIfNoValueGiven() throws CmdLineException {
  expected.expect(CmdLineException.class);
  expected.expectMessage("Option \"--set\" takes an operand");
  TestBean bean = new TestBean();
  CmdLineParser parser = new CmdLineParser(bean);
  parser.parseArgument("--set");
}
 
Example #21
Source File: FlinkPipelineRunner.java    From beam with Apache License 2.0 5 votes vote down vote up
private static FlinkPipelineRunnerConfiguration parseArgs(String[] args) {
  FlinkPipelineRunnerConfiguration configuration = new FlinkPipelineRunnerConfiguration();
  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 #22
Source File: MetastoreTimeseriesDeleteCommand.java    From s3mper with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #23
Source File: CreateGlueGrammar.java    From joshua with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
 final CreateGlueGrammar glueCreator = new CreateGlueGrammar();
 final CmdLineParser parser = new CmdLineParser(glueCreator);

 try {
   parser.parseArgument(args);
   glueCreator.run();
 } catch (CmdLineException e) {
   LOG.error(e.getMessage(), e);
   parser.printUsage(System.err);
   System.exit(1);
 }
}
 
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: InetAddressOptionHandler.java    From monsoon with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public int parseArguments(Parameters prmtrs) throws CmdLineException {
    final HostnamePort hp = HostnamePort.valueOf(prmtrs.getParameter(0), defaultPort());

    setter.addValue(hp.getAddress());
    return 1;
}
 
Example #26
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 #27
Source File: Component.java    From clouditor with Apache License 2.0 5 votes vote down vote up
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;
  }
}
 
Example #28
Source File: M2DocLauncher.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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;

}
 
Example #29
Source File: TestLabelOptions.java    From buck with Apache License 2.0 5 votes vote down vote up
@Override
public int parseArguments(Parameters parameters) throws CmdLineException {
  int index;
  for (index = 0; index < parameters.size(); index++) {
    String parameter = parameters.getParameter(index);
    if (parameter.charAt(0) == '-') {
      break;
    }
    labels.put(ordinal.getAndIncrement(), LabelSelector.fromString(parameter));
  }
  return index;
}
 
Example #30
Source File: ConsumeAllOptionsHandler.java    From buck with Apache License 2.0 5 votes vote down vote up
@Override
public int parseArguments(Parameters params) throws CmdLineException {
  for (int idx = 0; idx < params.size(); idx += 1) {
    setter.addValue(params.getParameter(idx));
  }
  return params.size();
}