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

The following examples show how to use com.beust.jcommander.JCommander#addObject() . 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: Help.java    From accumulo-examples with Apache License 2.0 6 votes vote down vote up
public void parseArgs(String programName, String[] args, Object... others) {
  JCommander commander = new JCommander();
  commander.addObject(this);
  for (Object other : others)
    commander.addObject(other);
  commander.setProgramName(programName);
  try {
    commander.parse(args);
  } catch (ParameterException ex) {
    commander.usage();
    exitWithError(ex.getMessage(), 1);
  }
  if (help) {
    commander.usage();
    exit(0);
  }
}
 
Example 2
Source File: ConnectorDocGenerator.java    From pulsar with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    MainArgs mainArgs = new MainArgs();

    JCommander commander = new JCommander();
    try {
        commander.setProgramName("connector-doc-gen");
        commander.addObject(mainArgs);
        commander.parse(args);
        if (mainArgs.help) {
            commander.usage();
            Runtime.getRuntime().exit(0);
            return;
        }
    } catch (Exception e) {
        commander.usage();
        Runtime.getRuntime().exit(-1);
        return;
    }

    ConnectorDocGenerator docGen = new ConnectorDocGenerator();
    docGen.generatorConnectorYamls(mainArgs.outputDir);
}
 
Example 3
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 4
Source File: Cli.java    From apiman-cli with Apache License 2.0 5 votes vote down vote up
@Override
public void run(List<String> args, JCommander jc) {
    jc.setAcceptUnknownOptions(false);
    jc.setProgramName("apiman-cli");
    jc.addObject(this);
    build(jc);
    try {
        jc.parse(args.toArray(new String[]{}));
        super.run(args, jc);
    } catch (ParameterException | CommandException e) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(e.getMessage(), e);
        } else {
            if (e.getCause() == null) {
                LOGGER.error(e.getMessage());
            } else {
                LOGGER.error("{}: {}", e.getMessage(), e.getCause().getMessage());
            }
        }
        printUsage(jc, false);
    } catch (ExitWithCodeException ec) {
        // print the message and exit with the given code
        LogUtil.OUTPUT.error(ec.getMessage());
        if (ec.isPrintUsage()) {
            printUsage(jc, ec.getExitCode());
        } else {
            System.exit(ec.getExitCode());
        }
    }
}
 
Example 5
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 6
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 7
Source File: Configuration.java    From elasticsearch with Apache License 2.0 5 votes vote down vote up
public Configuration(String... args) {
    final JCommander jCommander = new JCommander();
    jCommander.addObject(zookeeperCLI);
    jCommander.addObject(elasticsearchCLI);
    jCommander.addObject(this);
    try {
        jCommander.parse(args); // Parse command line args into configuration class.
    } catch (com.beust.jcommander.ParameterException ex) {
        System.out.println(ex);
        jCommander.setProgramName("(Options preceded by an asterisk are required)");
        jCommander.usage();
        throw ex;
    }
}
 
Example 8
Source File: JCommanderPrefixTranslatorTest.java    From geowave with Apache License 2.0 5 votes vote down vote up
private JCommander prepareCommander(final JCommanderTranslationMap map) {
  final JCommander commander = new JCommander();
  map.createFacadeObjects();
  for (final Object obj : map.getObjects()) {
    commander.addObject(obj);
  }
  return commander;
}
 
Example 9
Source File: PulsarTransactionCoordinatorMetadataSetup.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();
    try {
        jcommander.addObject(arguments);
        jcommander.parse(args);
        if (arguments.help) {
            jcommander.usage();
            return;
        }
    } catch (Exception e) {
        jcommander.usage();
        throw e;
    }

    if (arguments.configurationStore == null) {
        System.err.println("Configuration store address argument is required (--configuration-store)");
        jcommander.usage();
        System.exit(1);
    }

    if (arguments.numTransactionCoordinators <= 0) {
        System.err.println("Number of transaction coordinators must greater than 0");
        System.exit(1);
    }

    ZooKeeper configStoreZk = PulsarClusterMetadataSetup
            .initZk(arguments.configurationStore, arguments.zkSessionTimeoutMillis);

    // Create system tenant
    PulsarClusterMetadataSetup
            .createTenantIfAbsent(configStoreZk, NamespaceName.SYSTEM_NAMESPACE.getTenant(), arguments.cluster);

    // Create system namespace
    PulsarClusterMetadataSetup.createNamespaceIfAbsent(configStoreZk, NamespaceName.SYSTEM_NAMESPACE,
            arguments.cluster);

    // Create transaction coordinator assign partitioned topic
    PulsarClusterMetadataSetup.createPartitionedTopic(configStoreZk, TopicName.TRANSACTION_COORDINATOR_ASSIGN,
            arguments.numTransactionCoordinators);

    System.out.println("Transaction coordinator metadata setup success");
}
 
Example 10
Source File: PulsarAdminTool.java    From pulsar with Apache License 2.0 4 votes vote down vote up
PulsarAdminTool(Properties properties) throws Exception {
    // fallback to previous-version serviceUrl property to maintain backward-compatibility
    serviceUrl = StringUtils.isNotBlank(properties.getProperty("webServiceUrl"))
            ? properties.getProperty("webServiceUrl")
            : properties.getProperty("serviceUrl");
    authPluginClassName = properties.getProperty("authPlugin");
    authParams = properties.getProperty("authParams");
    boolean tlsAllowInsecureConnection = this.tlsAllowInsecureConnection != null ? this.tlsAllowInsecureConnection
            : Boolean.parseBoolean(properties.getProperty("tlsAllowInsecureConnection", "false"));

    boolean tlsEnableHostnameVerification = this.tlsEnableHostnameVerification != null
            ? this.tlsEnableHostnameVerification
            : Boolean.parseBoolean(properties.getProperty("tlsEnableHostnameVerification", "false"));
    final String tlsTrustCertsFilePath = StringUtils.isNotBlank(this.tlsTrustCertsFilePath)
            ? this.tlsTrustCertsFilePath
            : properties.getProperty("tlsTrustCertsFilePath");

    this.useKeyStoreTls = Boolean
            .parseBoolean(properties.getProperty("useKeyStoreTls", "false"));
    this.tlsTrustStoreType = properties.getProperty("tlsTrustStoreType", "JKS");
    this.tlsTrustStorePath = properties.getProperty("tlsTrustStorePath");
    this.tlsTrustStorePassword = properties.getProperty("tlsTrustStorePassword");

    adminBuilder = PulsarAdmin.builder().allowTlsInsecureConnection(tlsAllowInsecureConnection)
            .enableTlsHostnameVerification(tlsEnableHostnameVerification)
            .tlsTrustCertsFilePath(tlsTrustCertsFilePath)
            .useKeyStoreTls(useKeyStoreTls)
            .tlsTrustStoreType(tlsTrustStoreType)
            .tlsTrustStorePath(tlsTrustStorePath)
            .tlsTrustStorePassword(tlsTrustStorePassword);

    jcommander = new JCommander();
    jcommander.setProgramName("pulsar-admin");
    jcommander.addObject(this);

    commandMap = new HashMap<>();
    commandMap.put("clusters", CmdClusters.class);
    commandMap.put("ns-isolation-policy", CmdNamespaceIsolationPolicy.class);
    commandMap.put("brokers", CmdBrokers.class);
    commandMap.put("broker-stats", CmdBrokerStats.class);
    commandMap.put("tenants", CmdTenants.class);
    commandMap.put("properties", CmdTenants.CmdProperties.class); // deprecated, doesn't show in usage()
    commandMap.put("namespaces", CmdNamespaces.class);
    commandMap.put("topics", CmdTopics.class);
    commandMap.put("schemas", CmdSchemas.class);
    commandMap.put("bookies", CmdBookies.class);

    // Hidden deprecated "persistent" and "non-persistent" subcommands
    commandMap.put("persistent", CmdPersistentTopics.class);
    commandMap.put("non-persistent", CmdNonPersistentTopics.class);


    commandMap.put("resource-quotas", CmdResourceQuotas.class);
    // pulsar-proxy cli
    commandMap.put("proxy-stats", CmdProxyStats.class);

    commandMap.put("functions", CmdFunctions.class);
    commandMap.put("functions-worker", CmdFunctionWorker.class);
    commandMap.put("sources", CmdSources.class);
    commandMap.put("sinks", CmdSinks.class);

    // Automatically generate documents for pulsar-admin
    commandMap.put("documents", CmdGenerateDocument.class);

    // To remain backwards compatibility for "source" and "sink" commands
    // TODO eventually remove this
    commandMap.put("source", CmdSources.class);
    commandMap.put("sink", CmdSinks.class);
}
 
Example 11
Source File: ApplicationTest.java    From jfr-flame-graph with Apache License 2.0 4 votes vote down vote up
private void parseCommands(String[] args) {
    JCommander jc = new JCommander();
    jc.addObject(jfrToFlameGraphWriter);
    jc.addObject(parameters);
    jc.parse(args);
}
 
Example 12
Source File: HelpCommand.java    From geowave with Apache License 2.0 4 votes vote down vote up
@Override
public void execute(final OperationParams inputParams) {
  final CommandLineOperationParams params = (CommandLineOperationParams) inputParams;

  final List<String> nameArray = new ArrayList<>();
  final OperationRegistry registry = OperationRegistry.getInstance();

  StringBuilder builder = new StringBuilder();

  Operation lastOperation = null;
  for (final Map.Entry<String, Operation> entry : params.getOperationMap().entrySet()) {
    if (entry.getValue() == this) {
      continue;
    }
    nameArray.add(entry.getKey());
    lastOperation = entry.getValue();
  }

  if (lastOperation == null) {
    lastOperation = registry.getOperation(GeoWaveTopLevelSection.class).createInstance();
  }
  if (lastOperation != null) {
    final String usage = lastOperation.usage();
    if (usage != null) {
      System.out.println(usage);
    } else {
      // This is done because if we don't, then JCommander will
      // consider the given parameters as the Default parameters.
      // It's also done so that we can parse prefix annotations
      // and special delegate processing.
      final JCommanderPrefixTranslator translator = new JCommanderPrefixTranslator();

      translator.addObject(lastOperation);
      final JCommanderTranslationMap map = translator.translate();
      map.createFacadeObjects();

      // Copy default parameters over for help display.
      map.transformToFacade();

      // Execute a prepare

      // Add processed objects
      final JCommander jc = new JCommander();
      for (final Object obj : map.getObjects()) {
        jc.addObject(obj);
      }

      final String programName = StringUtils.join(nameArray, " ");
      jc.setProgramName(programName);
      jc.getUsageFormatter().usage(builder);

      // Trim excess newlines.
      final String operations = builder.toString().trim();
      builder = new StringBuilder();
      builder.append(operations);
      builder.append("\n\n");

      // Add sub-commands
      final OperationEntry lastEntry = registry.getOperation(lastOperation.getClass());
      // Cast to list so we can sort it based on operation name.
      final List<OperationEntry> children = new ArrayList<>(lastEntry.getChildren());
      Collections.sort(children, getOperationComparator());
      if (children.size() > 0) {
        builder.append("  Commands:\n");
        for (final OperationEntry childEntry : children) {

          // Get description annotation
          final Parameters p = childEntry.getOperationClass().getAnnotation(Parameters.class);

          // If not hidden, then output it.
          if ((p == null) || !p.hidden()) {
            builder.append(
                String.format(
                    "    %s%n",
                    StringUtils.join(childEntry.getOperationNames(), ", ")));
            if (p != null) {
              final String description = p.commandDescription();
              builder.append(String.format("      %s%n", description));
            } else {
              builder.append("      <no description>\n");
            }
            builder.append("\n");
          }
        }
      }

      // Trim excess newlines.
      final String output = builder.toString().trim();

      System.out.println(output);
    }
  }
}