Java Code Examples for com.beust.jcommander.JCommander#addCommand()

The following examples show how to use com.beust.jcommander.JCommander#addCommand() . 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: Git.java    From mdw with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    JCommander cmd = new JCommander();
    Git git = new Git();
    cmd.addCommand("git", git);
    String[] gitArgs = new String[args.length + 1];
    gitArgs[0] = "git";
    gitArgs[1] = "args";
    boolean showProgress = true;
    for (int i = 1; i < args.length; i++) {
        gitArgs[i + 1] = args[i];
        if ("--no-progress".equals(args[i]))
            showProgress = false;
    }
    cmd.parse(gitArgs);
    git.run(Main.getMonitor(showProgress));
}
 
Example 2
Source File: ShellCommandTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
private void performJCommanderCompletorTest(
    String line,
    int expectedBackMotion,
    String... expectedCompletions) {
  JCommander jcommander = new JCommander();
  jcommander.setProgramName("test");
  jcommander.addCommand("help", new HelpCommand(jcommander));
  jcommander.addCommand("testCommand", new TestCommand());
  jcommander.addCommand("testAnotherCommand", new TestAnotherCommand());
  List<String> completions = new ArrayList<>();
  assertThat(
          line.length()
              - new JCommanderCompletor(jcommander)
                  .completeInternal(line, line.length(), completions))
      .isEqualTo(expectedBackMotion);
  assertThat(completions).containsExactlyElementsIn(expectedCompletions);
}
 
Example 3
Source File: UsersSample.java    From director-sdk with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
  Map<String, Command> commands = new HashMap<String, Command>();
  commands.put("list", new ListCommand());
  commands.put("add", new AddCommand());
  commands.put("delete", new DeleteCommand());

  CommonParameters common = new CommonParameters();
  JCommander jc = new JCommander(common);
  jc.setProgramName("UsersSample");

  for (Map.Entry<String, Command> current : commands.entrySet()) {
    jc.addCommand(current.getKey(), current.getValue());
  }

  jc.parse(args);

  if (commands.containsKey(jc.getParsedCommand())) {
    commands.get(jc.getParsedCommand()).run(common);

  } else {
    jc.usage();
    System.exit(1);
  }
}
 
Example 4
Source File: Tool.java    From openjavacard-tools with GNU Lesser General Public License v3.0 5 votes vote down vote up
void run(String[] arguments) {
    // build commander
    JCommander jc = makeCommander();
    // add tool object
    jc.addObject(this);
    // core commands
    jc.addCommand(new Help(jc));
    jc.addCommand(new Script(this));
    // parse the command
    jc.parse(arguments);
    // execute the command
    runMainCommand(jc);
}
 
Example 5
Source File: Tool.java    From openjavacard-tools with GNU Lesser General Public License v3.0 5 votes vote down vote up
JCommander makeCommander() {
    JCommander jc = new JCommander();
    jc.addConverterFactory(new ConverterFactory());

    jc.addCommand(new GenericAPDU(mContext));
    jc.addCommand(new GenericReaders(mContext));

    jc.addCommand(new AIDInfo());
    jc.addCommand(new AIDNow());

    jc.addCommand(new CapInfo());
    jc.addCommand(new CapSize());
    jc.addCommand(new CapDump());

    jc.addCommand(new GPInfo(mContext));
    jc.addCommand(new GPList(mContext));
    jc.addCommand(new GPLoad(mContext));
    jc.addCommand(new GPInstall(mContext));
    jc.addCommand(new GPDelete(mContext));
    jc.addCommand(new GPExtradite(mContext));
    jc.addCommand(new GPState(mContext));
    jc.addCommand(new GPIdentity(mContext));
    jc.addCommand(new GPKeyReplace(mContext));

    jc.addCommand(new PkgAvailable(mContext));
    jc.addCommand(new PkgInfo(mContext));
    jc.addCommand(new PkgInit(mContext));
    jc.addCommand(new PkgInstall(mContext));
    jc.addCommand(new PkgList(mContext));
    jc.addCommand(new PkgSearch(mContext));

    jc.addCommand(new ScanName(mContext));
    jc.addCommand(new ScanFID(mContext));

    return jc;
}
 
Example 6
Source File: Main.java    From walle with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) throws Exception {
    final Map<String, IWalleCommand> subCommandList = new HashMap<String, IWalleCommand>();
    subCommandList.put("show", new ShowCommand());
    subCommandList.put("rm", new RemoveCommand());
    subCommandList.put("put", new PutCommand());
    subCommandList.put("batch", new BatchCommand());
    subCommandList.put("batch2", new Batch2Command());

    final WalleCommandLine walleCommandLine = new WalleCommandLine();
    final JCommander commander = new JCommander(walleCommandLine);

    for (Map.Entry<String, IWalleCommand> commandEntry : subCommandList.entrySet()) {
        commander.addCommand(commandEntry.getKey(), commandEntry.getValue());
    }
    try {
        commander.parse(args);
    } catch (ParameterException e) {
        System.out.println(e.getMessage());
        commander.usage();
        System.exit(1);
        return;
    }

    walleCommandLine.parse(commander);

    final String parseCommand = commander.getParsedCommand();
    if (parseCommand != null) {
        subCommandList.get(parseCommand).parse();
    }
}
 
Example 7
Source File: OmidTableManager.java    From phoenix-omid with Apache License 2.0 5 votes vote down vote up
public OmidTableManager(String... args) {
    commandLine = new JCommander(mainConfig);
    commandLine.addCommand(COMMIT_TABLE_COMMAND_NAME, commitTableCommand);
    commandLine.addCommand(TIMESTAMP_TABLE_COMMAND_NAME, timestampTableCommand);
    try {
        commandLine.parse(args);
    } catch (ParameterException ex) {
        commandLine.usage();
        throw new IllegalArgumentException(ex.getMessage());
    }
}
 
Example 8
Source File: L10nJCommander.java    From mojito with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a {@link JCommander} instance for a single run (sub-sequent
 * parsing are not supported but required for testing).
 */
public void createJCommanderForRun() {
    logger.debug("Create JCommander instance");
    jCommander = new JCommander();

    jCommander.setAcceptUnknownOptions(true);

    logger.debug("Initialize the JCommander instance");
    jCommander.setProgramName(PROGRAM_NAME);

    logger.debug("Set the main command for version/help directly on the JCommander");
    jCommander.addObject(mainCommand);

    logger.debug("Register Commands retreived using Spring");
    for (Command command : applicationContext.getBeansOfType(Command.class).values()) {

        Map<String, JCommander> jCommands = jCommander.getCommands();

        for (String name : command.getNames()) {
            if (jCommands.keySet().contains(name)) {
                throw new RuntimeException("There must be only one module with name: " + name);
            }
        }

        commands.put(command.getName(), command);
        jCommander.addCommand(command);
    }
}
 
Example 9
Source File: CliMain.java    From keywhiz with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
  CliConfiguration config = new CliConfiguration();

  JCommander commander = new JCommander();
  Map<String, Object> commands = ImmutableMap.<String, Object>builder()
      .put("login", new LoginActionConfig())
      .put("list", new ListActionConfig())
      .put("describe", new DescribeActionConfig())
      .put("add", new AddActionConfig())
      .put("update", new UpdateActionConfig())
      .put("delete", new DeleteActionConfig())
      .put("assign", new AssignActionConfig())
      .put("unassign", new UnassignActionConfig())
      .put("versions", new ListVersionsActionConfig())
      .put("rollback", new RollbackActionConfig())
      .build();
  commander.setProgramName("KeyWhiz Configuration Utility");
  commander.addObject(config);

  for (Map.Entry<String, Object> entry : commands.entrySet()) {
    commander.addCommand(entry.getKey(), entry.getValue());
  }

  try {
    commander.parse(args);
  } catch (ParameterException e) {
    System.err.println("Invalid command: " + e.getMessage());
    commander.usage();
    System.exit(1);
  }

  String command = commander.getParsedCommand();
  JCommander specificCommander = commander.getCommands().get(command);
  Injector injector = Guice.createInjector(new CliModule(config, commander, specificCommander,
      command, commands));
  CommandExecutor executor = injector.getInstance(CommandExecutor.class);
  executor.executeCommand();
}
 
Example 10
Source File: OperationsTool.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
public static int innerMain(String[] args) {
  BaseOptions base = new BaseOptions();
  JCommander jc = new JCommander(base);
  jc.setProgramName("ehcache-ops");
  jc.addCommand(new ListCacheManagers(base));
  jc.addCommand(new CreateCacheManager(base));
  jc.addCommand(new UpdateCacheManager(base));
  jc.addCommand(new DestroyCacheManager(base));

  jc.setParameterDescriptionComparator(REQUIRED_FIRST);
  for (JCommander jcc : jc.getCommands().values()) {
    jcc.setParameterDescriptionComparator(REQUIRED_FIRST);
  }

  try {
    jc.parse(args);

    if (base.isHelp()) {
      return usage(jc, new StringBuilder());
    } else {
      int result = 0;
      for (Object o : jc.getCommands().get(jc.getParsedCommand()).getObjects()) {
        result |= ((Command) o).execute();
      }

      return result;
    }
  } catch (ParameterException e) {
    return usage(jc, new StringBuilder(e.getMessage()).append("\n"));
  }
}
 
Example 11
Source File: Main.java    From pomutils with Apache License 2.0 5 votes vote down vote up
protected static int mainInternal(String... args) {
	CommandMain mainCommand = new CommandMain();
	CommandPomMergeDriver mergeCommand = new CommandPomMergeDriver();
	CommandPomVersionReplacer versionReplacerCommand = new CommandPomVersionReplacer();

	JCommander jc = new JCommander(mainCommand);
	jc.addCommand("merge", mergeCommand);
	jc.addCommand("replace", versionReplacerCommand);

	try {
		jc.parse(args);
	} catch (ParameterException e) {
		System.err.println(e.getMessage());
		return 1;
	}

	String logLevel = mainCommand.isDebug() ? "debug" : "error";
	System.setProperty(SimpleLogger.DEFAULT_LOG_LEVEL_KEY, logLevel);

	logger = LoggerFactory.getLogger(Main.class);

	if (logger.isInfoEnabled()) {
		logger.info("PomUtils version {}", ManifestUtils.getImplementationVersion());
	}

	if ("merge".equals(jc.getParsedCommand())) {
		return executePomMergeDriver(mergeCommand);
	} else if ("replace".equals(jc.getParsedCommand())) {
		executePomVersionReplacer(versionReplacerCommand);
		return 0;
	}
	jc.usage();
	return 1;
}
 
Example 12
Source File: CramTools.java    From cramtools with Apache License 2.0 5 votes vote down vote up
private static void addProgram(JCommander jc, Class<?> klass) throws ClassNotFoundException,
		InstantiationException, IllegalAccessException {

	Class<?> paramsClass = findParamsClass(klass);
	Object instance = paramsClass.newInstance();

	Field commandField = findStaticField("COMMAND", klass);
	String command = commandField.get(null).toString();

	jc.addCommand(command, instance);
	classes.put(command, klass);
}
 
Example 13
Source File: AbstractCommand.java    From apiman-cli with Apache License 2.0 4 votes vote down vote up
private static JCommander addSubCommand(JCommander parentCommand,
                                        String commandName, Object commandObject) {
    parentCommand.addCommand(commandName, commandObject);
    return parentCommand.getCommands().get(commandName);
}
 
Example 14
Source File: TokensCliUtils.java    From pulsar with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    Arguments arguments = new Arguments();
    JCommander jcommander = new JCommander(arguments);

    CommandCreateSecretKey commandCreateSecretKey = new CommandCreateSecretKey();
    jcommander.addCommand("create-secret-key", commandCreateSecretKey);

    CommandCreateKeyPair commandCreateKeyPair = new CommandCreateKeyPair();
    jcommander.addCommand("create-key-pair", commandCreateKeyPair);

    CommandCreateToken commandCreateToken = new CommandCreateToken();
    jcommander.addCommand("create", commandCreateToken);

    CommandShowToken commandShowToken = new CommandShowToken();
    jcommander.addCommand("show", commandShowToken);

    CommandValidateToken commandValidateToken = new CommandValidateToken();
    jcommander.addCommand("validate", commandValidateToken);

    try {
        jcommander.parse(args);

        if (arguments.help || jcommander.getParsedCommand() == null) {
            jcommander.usage();
            System.exit(1);
        }
    } catch (Exception e) {
        System.err.println(e);
        String chosenCommand = jcommander.getParsedCommand();
        jcommander.usage(chosenCommand);
        System.exit(1);
    }

    String cmd = jcommander.getParsedCommand();

    if (cmd.equals("create-secret-key")) {
        commandCreateSecretKey.run();
    } else if (cmd.equals("create-key-pair")) {
        commandCreateKeyPair.run();
    } else if (cmd.equals("create")) {
        commandCreateToken.run();
    } else if (cmd.equals("show")) {
        commandShowToken.run();
    } else if (cmd.equals("validate")) {
        commandValidateToken.run();
    } else {
        System.err.println("Invalid command: " + cmd);
        System.exit(1);
    }
}
 
Example 15
Source File: Main.java    From ballerina-message-broker with Apache License 2.0 3 votes vote down vote up
/**
 * Add a subCommand to its parent commander.
 *
 * Adding a command to a JCommander instance will create a new JCommander instance for the new command, and it
 * will be added into the parents command map. This method will extract the child commander and keep it for
 * future reference (to add another layer of sub-commands) and the new command will also get added into the
 * commandMap to refer at traversing stage.
 *
 * @param parentCommander parent commander instance.
 * @param commandName     name of this command.
 * @param commandObject   annotated command instance.
 * @return jCommander instance created for the new command.
 */
private static JCommander addChildCommand(JCommander parentCommander, String commandName,
        MBClientCmd commandObject) {
    parentCommander.addCommand(commandName, commandObject);
    JCommander childCommander = parentCommander.getCommands().get(commandName);
    commandObject.setSelfJCommander(childCommander);
    return childCommander;
}