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

The following examples show how to use com.beust.jcommander.JCommander#setProgramName() . 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: Player.java    From jsflight with Apache License 2.0 6 votes vote down vote up
private static IConfig getConfig(String[] args)
{
    LOG.info("Configs parsing");
    IConfig config;

    if (new File(System.getProperty("configFile")).exists())
    {
        config = new PropertiesConfig(System.getProperty("configFile"));
    }
    else
    {
        config = new CliConfig();
        JCommander jc = new JCommander(config, args);
        jc.setProgramName(Player.class.getSimpleName());
        if (((CliConfig)config).shouldShowUsage())
        {
            jc.usage();
            System.exit(0);
        }
    }
    return config;
}
 
Example 2
Source File: Example.java    From jpmml-model with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
static
public void execute(Class<? extends Example> clazz, String... args) throws Exception {
	Example example = clazz.newInstance();

	JCommander commander = new JCommander(example);
	commander.setProgramName(clazz.getName());

	try {
		commander.parse(args);
	} catch(ParameterException pe){
		commander.usage();

		System.exit(-1);
	}

	example.execute();
}
 
Example 3
Source File: TopicAdmin.java    From joyqueue with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args){
        String[] argV={"subscribe", "--topic", "test_topic_bh_6" ,
                "--app","test_app","--type","1","--host","http://localhost:50091","--delay","10000"};
//        String[] argV={"add", "-c", "test_topic_bh_6" ,"--host","http://localhost:50091", "-b" ,"1561112964"};
        final TopicArg topicArg=new TopicArg();
        final PublishArg publishArg=new PublishArg();
        final SubscribeArg consumeArg=new SubscribeArg();
        final PartitionGroupArg partitionGroupArg=new PartitionGroupArg();
        TopicAdmin topicAdmin=new TopicAdmin();
        Map<String,CommandArgs> argsMap=new HashMap(8);
        argsMap.put(Command.add.name(),topicArg);
        argsMap.put(Command.publish.name(),publishArg);
        argsMap.put(Command.subscribe.name(),consumeArg);
        JCommander jc =JCommander.newBuilder()
                .addObject(topicAdmin)
                .addCommand(Command.add.name(),topicArg)
                .addCommand(Command.delete.name(),topicAdmin)
                .addCommand(Command.publish.name(),publishArg)
                .addCommand(Command.unpublish.name(),publishArg)
                .addCommand(Command.subscribe.name(),consumeArg)
                .addCommand(Command.unsubscribe.name(),consumeArg)
                .addCommand(Command.partitiongroup.name(),partitionGroupArg)
                .build();
        jc.setProgramName("topic");
        topicAdmin.execute(jc,argV,argsMap);
    }
 
Example 4
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 5
Source File: CommandLineParameters.java    From render with GNU General Public License v2.0 6 votes vote down vote up
public void parse(final String[] args,
                  final Class programClass,
                  final boolean exitOnHelpOrFailure) throws IllegalArgumentException {

    jCommander = new JCommander(this);
    jCommander.setProgramName("java -cp <render-module>-standalone.jar " + programClass.getName());

    boolean parseFailed = true;
    try {
        jCommander.parse(args);
        parseFailed = false;
    } catch (final ParameterException pe) {
        JCommander.getConsole().println("\nERROR: failed to parse command line arguments\n\n" + pe.getMessage());
    } catch (final Throwable t) {
        LOG.error("failed to parse command line arguments", t);
    }

    if (help || parseFailed) {
        JCommander.getConsole().println("");
        jCommander.usage();
        if (exitOnHelpOrFailure) {
            System.exit(1);
        }
    }
}
 
Example 6
Source File: Main.java    From maven-artifacts-uploader with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    Injector injector = Guice.createInjector(new MavenModule(), new MavenCommandOptionsModule(), new XmlModule());
    OptionalArgs optionalArgs = injector.getInstance(OptionalArgs.class);
    JCommander jCommander = JCommander.newBuilder().addObject(optionalArgs).build();
    jCommander.setProgramName("mvnUploader");
    jCommander.parse(args);

    if (optionalArgs.isHelp()){
        jCommander.usage();
    } else {
        logger.info("Welcome To Maven Artifacts Uploader");
        Uploader uploader = injector.getInstance(Uploader.class);
        uploader.uploadToRepository(Paths.get(optionalArgs.getPathToArtifacts()));
        logger.info("Done uploading all the artifacts!");
    }
}
 
Example 7
Source File: PMDCommandLineInterface.java    From diff-check with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static PMDParameters extractParameters(PMDParameters arguments, String[] args, String progName) {
    JCommander jcommander = new JCommander(arguments);
	jcommander.setProgramName(progName);

	try {
		jcommander.parse(args);
		if (arguments.isHelp()) {
			jcommander.usage();
			System.out.println(buildUsageText(jcommander));
			setStatusCodeOrExit(ERROR_STATUS);
		}
	} catch (ParameterException e) {
		jcommander.usage();
		System.out.println(buildUsageText(jcommander));
		System.err.println(e.getMessage());
		setStatusCodeOrExit(ERROR_STATUS);
	}
	return arguments;
}
 
Example 8
Source File: Main.java    From maven-artifacts-uploader with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    Injector injector = Guice.createInjector(new MavenModule(), new MavenCommandOptionsModule(), new XmlModule());
    OptionalArgs optionalArgs = injector.getInstance(OptionalArgs.class);
    JCommander jCommander = JCommander.newBuilder().addObject(optionalArgs).build();
    jCommander.setProgramName("mvnUploader");
    jCommander.parse(args);

    if (optionalArgs.isHelp()){
        jCommander.usage();
    } else {
        logger.info("Welcome To Maven Artifacts Uploader");
        Uploader uploader = injector.getInstance(Uploader.class);
        uploader.uploadToRepository(Paths.get(optionalArgs.getPathToArtifacts()));
        logger.info("Done uploading all the artifacts!");
    }
}
 
Example 9
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 10
Source File: AgentCLI.java    From gocd with Apache License 2.0 5 votes vote down vote up
private void printUsageAndExit(int exitCode) {
    StringBuilder out = new StringBuilder();
    JCommander jCommander = new JCommander(new AgentBootstrapperArgs());
    jCommander.setProgramName("java -jar agent-bootstrapper.jar");
    jCommander.getUsageFormatter().usage(out);
    stderr.print(out);
    exit(exitCode);
}
 
Example 11
Source File: MetadataGeneratorTool.java    From shibboleth-oidc with Apache License 2.0 5 votes vote down vote up
/**
 * Main void.
 *
 * @param args the args
 */
public static void main(final String[] args) {
    final MetadataGeneratorTool tool = new MetadataGeneratorTool();

    final JCommander jc = new JCommander(tool.args, args);
    if (tool.args.help) {
        jc.setProgramName("MetadataGeneratorCommandLine");
        jc.usage();
        return;
    }

    tool.generate();
}
 
Example 12
Source File: LoadSimulationController.java    From pulsar with Apache License 2.0 5 votes vote down vote up
/**
 * Start a controller with command line arguments.
 *
 * @param args
 *            Arguments to pass in.
 */
public static void main(String[] args) throws Exception {
    final MainArguments arguments = new MainArguments();
    final JCommander jc = new JCommander(arguments);
    jc.setProgramName("pulsar-perf simulation-controller");
    try {
        jc.parse(args);
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
        jc.usage();
        System.exit(-1);
    }
    (new LoadSimulationController(arguments)).run();
}
 
Example 13
Source File: RegistryTestServerMain.java    From nomulus with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Throwable {
  RegistryTestServerMain serverMain = new RegistryTestServerMain();
  JCommander jCommander = new JCommander(serverMain);
  jCommander.setProgramName("dr-run server");
  jCommander.parse(args);
  if (serverMain.help) {
    jCommander.usage();
    return;
  }
  serverMain.run();
}
 
Example 14
Source File: Main.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
private Main(String[] args) {
    final JCommander commander = new JCommander(this);
    commander.setProgramName(getClass().getName());
    commander.parse(args);

    if (help != null && help) {
        commander.usage();
    } else {
        procIdFile = new PidFile(firstNonNull(pidFile, DEFAULT_PID_FILE));
        state = State.INITIALIZED;
    }
}
 
Example 15
Source File: VRPRunner.java    From VehicleRoutingProblem with GNU General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    VRPRunner jct = new VRPRunner();
    JCommander jCommander = new JCommander(jct, args);
    jCommander.setProgramName(VRPRunner.class.getSimpleName());

    switch (jct.alg) {
        case "acs":
            VrpAcsSolver aco = new VrpAcsSolver(jct);

            ExecutionStats
                    .execute(aco, aco.getProblem())
                    .printStats();
            break;
        case "tabu": {
            new TabuSearchSolver(jct)
                    .solve()
                    .print();
            break;
        }
        default:
        case "greedy": {
            new GreedySolver(jct)
                    .solve()
                    .print();
            break;
        }
    }
}
 
Example 16
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 17
Source File: RenderParameters.java    From render with GNU General Public License v2.0 4 votes vote down vote up
private void setCommander() {
    jCommander = new JCommander(this);
    jCommander.setProgramName("java -jar render.jar");
}
 
Example 18
Source File: Backup.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
  final DACConfig dacConfig = DACConfig.newConfig();
  final BackupManagerOptions options = new BackupManagerOptions();
  JCommander jc = JCommander.newBuilder().addObject(options).build();
  jc.setProgramName("dremio-admin backup");

  try {
    jc.parse(args);
  } catch (ParameterException p) {
    AdminLogger.log(p.getMessage());
    jc.usage();
    System.exit(1);
  }

  if(options.help) {
    jc.usage();
    System.exit(0);
  }

  if (options.localAttach && (options.userName != null || options.password != null)){
    AdminLogger.log("Do not pass username or password when running in local-attach mode");
    jc.usage();
    System.exit(1);
  }

  try {
    if (!dacConfig.isMaster) {
      throw new UnsupportedOperationException("Backup should be ran on master node. ");
    }

    // Make sure that unqualified paths are resolved locally first, and default filesystem
    // is pointing to file
    Path backupDir = Path.of(options.backupDir);
    final String scheme = backupDir.toURI().getScheme();
    if (scheme == null || "file".equals(scheme)) {
      backupDir = HadoopFileSystem.getLocal(new Configuration()).makeQualified(backupDir);
    }

    URI target = backupDir.toURI();

    if (options.localAttach) {
      String[] backupArgs = {"backup",options.backupDir, Boolean.toString(!options.json), Boolean.toString(options.profiles)};
      try {
        DremioAttach.main(backupArgs);
      } catch (NoClassDefFoundError error) {
        AdminLogger.log("A JDK is required to use local-attach mode. Please make sure JAVA_HOME is correctly configured");
      }
    } else {
      if (options.userName == null)  {
        options.userName = System.console().readLine("username: ");
      }
      if(options.password == null) {
        char[] pwd = System.console().readPassword("password: ");
        options.password = new String(pwd);
      }
      if (!validateOnlineOption(options)) {
        throw new ParameterException("User credential is required.");
      }
      BackupStats backupStats = createBackup(dacConfig, options.userName, options.password, !options.acceptAll, target, !options.json, options.profiles);
      AdminLogger.log("Backup created at {}, dremio tables {}, uploaded files {}",
        backupStats.getBackupPath(), backupStats.getTables(), backupStats.getFiles());
    }


  } catch (Exception e) {
    AdminLogger.log("Failed to create backup at {}:", options.backupDir, e);
    System.exit(1);
  }
}
 
Example 19
Source File: CompactorTool.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);
    jcommander.setProgramName("PulsarTopicCompactor");

    // parse args by JCommander
    jcommander.parse(args);
    if (arguments.help) {
        jcommander.usage();
        System.exit(-1);
    }

    // init broker config
    ServiceConfiguration brokerConfig;
    if (isBlank(arguments.brokerConfigFile)) {
        jcommander.usage();
        throw new IllegalArgumentException("Need to specify a configuration file for broker");
    } else {
        brokerConfig = PulsarConfigurationLoader.create(
                arguments.brokerConfigFile, ServiceConfiguration.class);
    }

    ClientBuilder clientBuilder = PulsarClient.builder();

    if (isNotBlank(brokerConfig.getBrokerClientAuthenticationPlugin())) {
        clientBuilder.authentication(brokerConfig.getBrokerClientAuthenticationPlugin(),
                brokerConfig.getBrokerClientAuthenticationParameters());
    }


    if (brokerConfig.getBrokerServicePortTls().isPresent()) {
        clientBuilder
                .serviceUrl(PulsarService.brokerUrlTls(PulsarService.advertisedAddress(brokerConfig),
                        brokerConfig.getBrokerServicePortTls().get()))
                .allowTlsInsecureConnection(brokerConfig.isTlsAllowInsecureConnection())
                .tlsTrustCertsFilePath(brokerConfig.getTlsCertificateFilePath());

    } else {
        clientBuilder.serviceUrl(PulsarService.brokerUrl(PulsarService.advertisedAddress(brokerConfig),
                brokerConfig.getBrokerServicePort().get()));
    }

    ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(
            new ThreadFactoryBuilder().setNameFormat("compaction-%d").setDaemon(true).build());

    OrderedScheduler executor = OrderedScheduler.newSchedulerBuilder().build();
    ZooKeeperClientFactory zkClientFactory = new ZookeeperBkClientFactoryImpl(executor);

    ZooKeeper zk = zkClientFactory.create(brokerConfig.getZookeeperServers(),
                                          ZooKeeperClientFactory.SessionType.ReadWrite,
                                          (int)brokerConfig.getZooKeeperSessionTimeoutMillis()).get();
    BookKeeperClientFactory bkClientFactory = new BookKeeperClientFactoryImpl();
    BookKeeper bk = bkClientFactory.create(brokerConfig, zk, Optional.empty(), null);
    try (PulsarClient pulsar = clientBuilder.build()) {
        Compactor compactor = new TwoPhaseCompactor(brokerConfig, pulsar, bk, scheduler);
        long ledgerId = compactor.compact(arguments.topic).get();
        log.info("Compaction of topic {} complete. Compacted to ledger {}", arguments.topic, ledgerId);
    } finally {
        bk.close();
        bkClientFactory.close();
        zk.close();
        scheduler.shutdownNow();
        executor.shutdown();
    }
}
 
Example 20
Source File: Experiments.java    From tsml with GNU General Public License v3.0 4 votes vote down vote up
private void parseArguments(String[] args) throws Exception {
            Builder b = JCommander.newBuilder();
            b.addObject(this);
            JCommander jc = b.build();
            jc.setProgramName("Experiments.java");  //todo maybe add copyright etcetc
            try {
                jc.parse(args);
            } catch (Exception e) {
                if (!help) {
                    //we actually errored, instead of the program simply being called with the --help flag
                    System.err.println("Parsing of arguments failed, parameter information follows after the error. Parameters that require values should have the flag and value separated by '='.");
                    System.err.println("For example: java -jar TimeSeriesClassification.jar -dp=data/path/ -rp=results/path/ -cn=someClassifier -dn=someDataset -f=0");
                    System.err.println("Parameters prefixed by a * are REQUIRED. These are the first five parameters, which are needed to run a basic experiment.");
                    System.err.println("Error: \n\t"+e+"\n\n");
                }
                jc.usage();
//                Thread.sleep(1000); //usage can take a second to print for some reason?... no idea what it's actually doing
//                System.exit(1);
            }

            foldId -= 1; //go from one-indexed to zero-indexed
            Experiments.debug = this.debug;

            resultsWriteLocation = StrUtils.asDirPath(resultsWriteLocation);
            dataReadLocation = StrUtils.asDirPath(dataReadLocation);
            if (checkpointingStr != null) {
                //some kind of checkpointing is wanted

                // is it simply "true"?

                checkpointing = Boolean.parseBoolean(checkpointingStr.toLowerCase());
                if(!checkpointing){
                    //it's not. must be a timing string
                    checkpointing = true;
                    checkpointInterval = parseTiming(checkpointingStr);

                }
          }

            //populating the contract times if present
            if (contractTrainTimeString != null)
                contractTrainTimeNanos = parseTiming(contractTrainTimeString);
            if (contractTestTimeString != null)
                contractTestTimeNanos = parseTiming(contractTestTimeString);

            if(contractTrainTimeNanos > 0) {
                trainContracts.add(String.valueOf(contractTrainTimeNanos));
                trainContracts.add(TimeUnit.NANOSECONDS.toString());
            }

            // check the contracts are in ascending order // todo sort them
            for(int i = 1; i < trainContracts.size(); i += 2) {
                trainContracts.set(i, trainContracts.get(i).toUpperCase());
            }
            long prev = -1;
            for(int i = 0; i < trainContracts.size(); i += 2) {
                long nanos = TimeUnit.NANOSECONDS.convert(Long.parseLong(trainContracts.get(i)),
                        TimeUnit.valueOf(trainContracts.get(i + 1)));
                if(prev > nanos) {
                    throw new IllegalArgumentException("contracts not in asc order");
                }
                prev = nanos;
            }

            if(trainContracts.size() % 2 != 0) {
                throw new IllegalStateException("illegal number of args for time");
            }

            if(logLevelStr != null) {
                logLevel = Level.parse(logLevelStr);
            }
        }