Java Code Examples for org.apache.commons.cli.CommandLine#hasOption()
The following examples show how to use
org.apache.commons.cli.CommandLine#hasOption() .
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: BaseSqoopTool.java From aliyun-maxcompute-data-collectors with Apache License 2.0 | 6 votes |
protected void applyHBaseOptions(CommandLine in, SqoopOptions out) { if (in.hasOption(HBASE_TABLE_ARG)) { out.setHBaseTable(in.getOptionValue(HBASE_TABLE_ARG)); } if (in.hasOption(HBASE_COL_FAM_ARG)) { out.setHBaseColFamily(in.getOptionValue(HBASE_COL_FAM_ARG)); } if (in.hasOption(HBASE_ROW_KEY_ARG)) { out.setHBaseRowKeyColumn(in.getOptionValue(HBASE_ROW_KEY_ARG)); } out.setHBaseBulkLoadEnabled(in.hasOption(HBASE_BULK_LOAD_ENABLED_ARG)); if (in.hasOption(HBASE_CREATE_TABLE_ARG)) { out.setCreateHBaseTable(true); } }
Example 2
Source File: CoOccurenceCalcs.java From hmftools with GNU General Public License v3.0 | 6 votes |
public static void main(@NotNull final String[] args) throws ParseException { final Options options = createBasicOptions(); final CommandLine cmd = createCommandLine(args, options); if (cmd.hasOption(LOG_DEBUG)) { Configurator.setRootLevel(Level.DEBUG); } String outputDir = cmd.getOptionValue(DATA_OUTPUT_DIR); CoOccurenceCalcs statsRoutines = new CoOccurenceCalcs(); statsRoutines.loadConfig(cmd, outputDir); statsRoutines.runStatistics(); LOGGER.info("run complete"); }
Example 3
Source File: DFSUtil.java From big-c with Apache License 2.0 | 6 votes |
/** * Parse the arguments for commands * * @param args the argument to be parsed * @param helpDescription help information to be printed out * @param out Printer * @param printGenericCommandUsage whether to print the * generic command usage defined in ToolRunner * @return true when the argument matches help option, false if not */ public static boolean parseHelpArgument(String[] args, String helpDescription, PrintStream out, boolean printGenericCommandUsage) { if (args.length == 1) { try { CommandLineParser parser = new PosixParser(); CommandLine cmdLine = parser.parse(helpOptions, args); if (cmdLine.hasOption(helpOpt.getOpt()) || cmdLine.hasOption(helpOpt.getLongOpt())) { // should print out the help information out.println(helpDescription + "\n"); if (printGenericCommandUsage) { ToolRunner.printGenericCommandUsage(out); } return true; } } catch (ParseException pe) { return false; } } return false; }
Example 4
Source File: UnitTopologyMain.java From eagle with Apache License 2.0 | 6 votes |
public static void main(String[] args) throws Exception { // command line parse Options options = new Options(); options.addOption("c", true, "config URL (valid file name) - defaults application.conf according to typesafe config default behavior."); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("c")) { String fileName = cmd.getOptionValue("c", "application.conf"); System.setProperty("config.resource", fileName.startsWith("/") ? fileName : "/" + fileName); ConfigFactory.invalidateCaches(); } Config config = ConfigFactory.load(); // load config and start String topologyId = getTopologyName(config); ZKMetadataChangeNotifyService changeNotifyService = createZKNotifyService(config, topologyId); new UnitTopologyRunner(changeNotifyService).run(topologyId, config); }
Example 5
Source File: RMNodeStarter.java From scheduling with GNU Affero General Public License v3.0 | 6 votes |
@VisibleForTesting void setNodeAvailabilityReportTimeoutDelay(CommandLine cl) { String property = System.getProperty(NODE_AVAILABILITY_REPORT_TIMEOUT_DELAY_PROP_NAME); if (property != null) { try { nodeAvailabilityReportTimeoutDelay = Integer.parseInt(property); } catch (NumberFormatException e) { nodeAvailabilityReportTimeoutDelay = DEFAULT_NODE_AVAILABILITY_REPORT_TIMEOUT_DELAY; } } if (cl.hasOption(OPTION_AVAILABILITY_REPORT_TIMEOUT)) { nodeAvailabilityReportTimeoutDelay = Integer.valueOf(cl.getOptionValue(OPTION_AVAILABILITY_REPORT_TIMEOUT)); } if (logger.isTraceEnabled()) { logger.trace("Node availability report timeout delay set to " + nodeAvailabilityReportTimeoutDelay + " ms."); } }
Example 6
Source File: QueryMsgByUniqueKeySubCommand.java From rocketmq-all-4.1.0-incubating with Apache License 2.0 | 6 votes |
@Override public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException { DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook); defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis())); try { defaultMQAdminExt.start(); final String msgId = commandLine.getOptionValue('i').trim(); final String topic = commandLine.getOptionValue('t').trim(); if (commandLine.hasOption('g') && commandLine.hasOption('d')) { final String consumerGroup = commandLine.getOptionValue('g').trim(); final String clientId = commandLine.getOptionValue('d').trim(); ConsumeMessageDirectlyResult result = defaultMQAdminExt.consumeMessageDirectly(consumerGroup, clientId, topic, msgId); System.out.printf("%s", result); } else { queryById(defaultMQAdminExt, topic, msgId); } } catch (Exception e) { throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e); } finally { defaultMQAdminExt.shutdown(); } }
Example 7
Source File: SendMsgStatusCommand.java From rocketmq with Apache License 2.0 | 6 votes |
@Override public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) { final DefaultMQProducer producer = new DefaultMQProducer("PID_SMSC", rpcHook); producer.setInstanceName("PID_SMSC_" + System.currentTimeMillis()); try { producer.start(); String brokerName = commandLine.getOptionValue('b').trim(); int messageSize = commandLine.hasOption('s') ? Integer.parseInt(commandLine.getOptionValue('s')) : 128; int count = commandLine.hasOption('c') ? Integer.parseInt(commandLine.getOptionValue('c')) : 50; producer.send(buildMessage(brokerName, 16)); for (int i = 0; i < count; i++) { long begin = System.currentTimeMillis(); SendResult result = producer.send(buildMessage(brokerName, messageSize)); System.out.printf("rt:" + (System.currentTimeMillis() - begin) + "ms, SendResult=" + result); } } catch (Exception e) { e.printStackTrace(); } finally { producer.shutdown(); } }
Example 8
Source File: HistoDbClearDbTool.java From ipst with Mozilla Public License 2.0 | 6 votes |
@Override public void run(CommandLine line, ToolRunningContext context) throws Exception { OfflineConfig config = OfflineConfig.load(); String dbName = null; if (line.hasOption("db-name")) { dbName = line.getOptionValue("db-name"); } context.getOutputStream().println("clear " + dbName + "..."); try (HistoDbClient histoDbClient = config.getHistoDbClientFactoryClass().newInstance().create(false)) { if (dbName == null) { histoDbClient.clearDb(); } else { histoDbClient.clearDb(dbName); } } }
Example 9
Source File: OptionManager.java From openapi-style-validator with Apache License 2.0 | 6 votes |
ValidatorParameters getOptionalValidatorParametersOrDefault(CommandLine commandLine) { ValidatorParameters parameters = new ValidatorParameters(); if (commandLine.hasOption(OPTIONS_OPT_SHORT)) { try { String content = Utils.readFile(commandLine.getOptionValue(OPTIONS_OPT_SHORT), Charset.defaultCharset()); JsonParser parser = new JsonParser(); JsonElement jsonElement = parser.parse(content); fixConventionRenaming(jsonElement, "path"); fixConventionRenaming(jsonElement, "parameter"); fixConventionRenaming(jsonElement, "property"); Gson gson = new GsonBuilder().create(); parameters = gson.fromJson(jsonElement, ValidatorParameters.class); } catch (Exception ignored) { System.out.println("Invalid path to option files, using default."); } } return parameters; }
Example 10
Source File: Main.java From contribution with GNU Lesser General Public License v2.1 | 6 votes |
/** * Forms POJO containing input paths. * * @param commandLine * parsed CLI. * @return POJO instance. * @throws IllegalArgumentException * on failure to find necessary arguments. */ private static CliPaths parseCliToPojo(CommandLine commandLine) throws IllegalArgumentException { final CompareMode compareMode = getCompareMode(OPTION_COMPARE_MODE, commandLine, CompareMode.XML); final Path xmlBasePath = getPath(OPTION_BASE_REPORT_PATH, commandLine, null); final Path xmlPatchPath = getPath(OPTION_PATCH_REPORT_PATH, commandLine, null); final Path refFilesPath = getPath(OPTION_REFFILES_PATH, commandLine, null); final Path defaultResultPath = Paths.get(System.getProperty("user.home")) .resolve("XMLDiffGen_report_" + new SimpleDateFormat("yyyy.MM.dd_HH_mm_ss") .format(Calendar.getInstance().getTime())); final Path outputPath = getPath(OPTION_OUTPUT_PATH, commandLine, defaultResultPath); final Path configBasePath = getPath(OPTION_BASE_CONFIG_PATH, commandLine, null); final Path configPatchPath = getPath(OPTION_PATCH_CONFIG_PATH, commandLine, null); final boolean shortFilePaths = commandLine.hasOption(OPTION_SHORT_PATHS); return new CliPaths(compareMode, xmlBasePath, xmlPatchPath, refFilesPath, outputPath, configBasePath, configPatchPath, shortFilePaths); }
Example 11
Source File: RegistryCli.java From hadoop with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") public int rm(String[] args) { Option recursive = OptionBuilder.withArgName("recursive") .withDescription("delete recursively") .create("r"); Options rmOption = new Options(); rmOption.addOption(recursive); boolean recursiveOpt = false; CommandLineParser parser = new GnuParser(); try { CommandLine line = parser.parse(rmOption, args); List<String> argsList = line.getArgList(); if (argsList.size() != 2) { return usageError("RM requires exactly one path argument", RM_USAGE); } if (!validatePath(argsList.get(1))) { return -1; } try { if (line.hasOption("r")) { recursiveOpt = true; } registry.delete(argsList.get(1), recursiveOpt); return 0; } catch (Exception e) { syserr.println(analyzeException("rm", e, argsList)); } return -1; } catch (ParseException exp) { return usageError("Invalid syntax " + exp.toString(), RM_USAGE); } }
Example 12
Source File: BddStepPrinter.java From vividus with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws ParseException, IOException { CommandLineParser parser = new DefaultParser(); Option helpOption = new Option("h", "help", false, "Print this message"); Option fileOption = new Option("f", "file", true, "Name of file to save BDD steps"); Options options = new Options(); options.addOption(helpOption); options.addOption(fileOption); CommandLine commandLine = parser.parse(options, args); if (commandLine.hasOption(helpOption.getOpt())) { new HelpFormatter().printHelp("BddStepPrinter", options); return; } Vividus.init(); Set<Step> steps = getSteps(); int maxLocationLength = steps.stream().map(Step::getLocation).mapToInt(String::length).max().orElse(0); List<String> stepsLines = steps.stream().map(s -> String .format("%-" + (maxLocationLength + 1) + "s%-24s%s %s", s.getLocation(), s.deprecated ? DEPRECATED : (s.compositeInStepsFile ? COMPOSITE : EMPTY), s.startingWord, s.pattern)) .collect(Collectors.toList()); String file = commandLine.getOptionValue(fileOption.getOpt()); if (file == null) { stepsLines.forEach(System.out::println); } else { Path path = Paths.get(file); FileUtils.writeLines(path.toFile(), stepsLines); System.out.println("File with BDD steps: " + path.toAbsolutePath()); } }
Example 13
Source File: GetClusterSpec.java From TensorFlowOnYARN with Apache License 2.0 | 5 votes |
public GetClusterSpec(YarnClient yarnClient, CommandLine cliParser) { this.yarnClient = yarnClient; if (!cliParser.hasOption(Constants.OPT_APPLICATION_ID)) { throw new IllegalArgumentException("Application ID is not specified"); } this.appId = cliParser.getOptionValue(Constants.OPT_APPLICATION_ID); }
Example 14
Source File: AgentServerGroupGetCommand.java From titus-control-plane with Apache License 2.0 | 5 votes |
@Override public void execute(CommandContext context) throws Exception { CommandLine cli = context.getCLI(); if (!cli.hasOption('i')) { getServerGroups(context); } else { getServerGroup(context, cli.getOptionValue('i')); } }
Example 15
Source File: ClusterLoadBalancer.java From doctorkafka with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws Exception { CommandLine commandLine = parseCommandLine(args); String configFilePath = commandLine.getOptionValue(CONFIG); String brokerStatsZk = commandLine.getOptionValue(BROKERSTATS_ZOOKEEPER); String brokerStatsTopic = commandLine.getOptionValue(BROKERSTATS_TOPIC); String clusterZk = commandLine.getOptionValue(CLUSTER_ZOOKEEPER); long seconds = Long.parseLong(commandLine.getOptionValue(SECONDS)); boolean onlyOne = commandLine.hasOption(ONLY_ONE); ReplicaStatsManager replicaStatsManager = new ReplicaStatsManager(new DoctorKafkaConfig(configFilePath)); replicaStatsManager.readPastReplicaStats(brokerStatsZk, SecurityProtocol.PLAINTEXT, brokerStatsTopic, seconds); Set<String> zkUrls = replicaStatsManager.getClusterZkUrls(); if (!zkUrls.contains(clusterZk)) { LOG.error("Failed to find zkurl {} in configuration", clusterZk); return; } DoctorKafkaClusterConfig clusterConf = replicaStatsManager.getConfig().getClusterConfigByZkUrl(clusterZk); KafkaCluster kafkaCluster = replicaStatsManager.getClusters().get(clusterZk); KafkaClusterManager clusterManager = new KafkaClusterManager( clusterZk, kafkaCluster, clusterConf, replicaStatsManager.getConfig(), null, null, replicaStatsManager); List<KafkaBroker> highTrafficBrokers = clusterManager.getHighTrafficBroker(); if (onlyOne && highTrafficBrokers.size() > 0) { KafkaBroker broker = highTrafficBrokers.get(0); highTrafficBrokers.clear(); highTrafficBrokers.add(broker); } String assignPlan = clusterManager.getWorkloadBalancingPlanInJson(highTrafficBrokers); LOG.info("Reassignment Plan : {}", assignPlan); }
Example 16
Source File: GobblinAWSTaskRunner.java From incubator-gobblin with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws Exception { final Options options = buildOptions(); try { final CommandLine cmd = new DefaultParser().parse(options, args); if (!cmd.hasOption(GobblinClusterConfigurationKeys.APPLICATION_NAME_OPTION_NAME) || !cmd.hasOption(GobblinClusterConfigurationKeys.HELIX_INSTANCE_NAME_OPTION_NAME) || !cmd.hasOption(GobblinAWSConfigurationKeys.APP_WORK_DIR)) { printUsage(options); System.exit(1); } if (System.getProperty("log4j.configuration") == null) { Log4jConfigHelper.updateLog4jConfiguration(GobblinTaskRunner.class, GobblinAWSConfigurationKeys.GOBBLIN_AWS_LOG4J_CONFIGURATION_FILE); } LOGGER.info(JvmUtils.getJvmInputArguments()); final String applicationName = cmd.getOptionValue(GobblinClusterConfigurationKeys.APPLICATION_NAME_OPTION_NAME); final String helixInstanceName = cmd.getOptionValue(GobblinClusterConfigurationKeys.HELIX_INSTANCE_NAME_OPTION_NAME); final String appWorkDir = cmd.getOptionValue(GobblinAWSConfigurationKeys.APP_WORK_DIR); final GobblinTaskRunner gobblinTaskRunner = new GobblinAWSTaskRunner(applicationName, helixInstanceName, ConfigFactory.load(), Optional.of(new Path(appWorkDir))); gobblinTaskRunner.start(); } catch (ParseException pe) { printUsage(options); System.exit(1); } }
Example 17
Source File: NadiaProcessor.java From nadia with Apache License 2.0 | 4 votes |
/** * @param args */ @SuppressWarnings("static-access") public static void main(String[] args) { Class<? extends UserInterface> ui_class=ConsoleInterface.class; //default UI String dialog_file=default_dialog; //default dialogue //process command line args Options cli_options = new Options(); cli_options.addOption("h", "help", false, "print this message"); cli_options.addOption(OptionBuilder.withLongOpt( "interface" ) .withDescription( "select user interface" ) .hasArg(true) .withArgName("console, rest") .create("i")); cli_options.addOption("f", "file", true, "specify dialogue path and file, e.g. -f /res/dialogue1.xml"); cli_options.addOption("r", "resource", true, "load dialogue (by name) from resources, e.g. -r dialogue1"); cli_options.addOption("s", "store", true, "load dialogue (by name) from internal store, e.g. -s dialogue1"); CommandLineParser parser = new org.apache.commons.cli.BasicParser(); try { CommandLine cmd = parser.parse(cli_options, args); //Help if(cmd.hasOption("h")){ HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("nadia", cli_options, true); return; } //UI if(cmd.hasOption("i")){ String interf=cmd.getOptionValue("i"); if(interf.equals("console")) ui_class=ConsoleInterface.class; else if (interf.equals("rest")) ui_class=RESTInterface.class; } //load dialogue from path file if(cmd.hasOption("f")){ dialog_file="file:///"+cmd.getOptionValue("f"); } //load dialogue from resources if(cmd.hasOption("r")){ dialog_file=config.getProperty(NadiaProcessorConfig.DIALOGUEDIR)+"/"+cmd.getOptionValue("r")+".xml"; } //load dialogue from internal store if(cmd.hasOption("s")){ Dialog store_dialog=DialogStore.getInstance().getDialogFromStore((cmd.getOptionValue("s"))); store_dialog.save(); dialog_file=config.getProperty(NadiaProcessorConfig.DIALOGUEDIR)+"/"+cmd.getOptionValue("s")+".xml"; } } catch (ParseException e1) { logger.severe("NADIA: loading by main-method failed. "+e1.getMessage()); e1.printStackTrace(); } //start Nadia with selected UI default_dialog=dialog_file; NadiaProcessor nadia = new NadiaProcessor(); try { ui = ui_class.newInstance(); ui.register(nadia); ui.start(); } catch (Exception e) { e.printStackTrace(); } }
Example 18
Source File: PMPDB.java From PicasaDBReader with MIT License | 4 votes |
@SuppressWarnings("static-access") public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption("h","help", false, "prints the help content"); options.addOption(OptionBuilder.withArgName("srcFolder").hasArg().withDescription("Picasa DB folder. Default is " + EnvironmentVariables.DEFAULT_PICASA_DB_PATH).create(PARAM_PICASA_DB_FOLDER)); options.addOption(OptionBuilder.withArgName("outputFolder").hasArg().isRequired().withDescription("output folder").create(PARAM_OUTPUT_FOLDER)); CommandLineParser parser = new GnuParser(); String folder=null; String output=null; try { // parse the command line arguments CommandLine line = parser.parse( options, args ); if(line.hasOption("h")){ showHelp(options); System.exit(1); } folder = EnvironmentVariables.getPicasaDBFolder(line, PARAM_PICASA_DB_FOLDER); if(line.hasOption(PARAM_OUTPUT_FOLDER)){ output = EnvironmentVariables.expandEnvVars(line.getOptionValue(PARAM_OUTPUT_FOLDER)); if(!output.endsWith(File.separator)){ output += File.separator; } if(! new File(output).exists()){ throw new Exception("output folder does not exist:"+output); } } } catch( ParseException exp ) { // oops, something went wrong System.err.println( "Parsing failed. Reason: " + exp.getMessage() ); showHelp(options); System.exit(1); } PMPDB db = new PMPDB(folder); db.populate(); db.writeCSVs(output); }
Example 19
Source File: NodeCLI.java From big-c with Apache License 2.0 | 4 votes |
@Override public int run(String[] args) throws Exception { Options opts = new Options(); opts.addOption(HELP_CMD, false, "Displays help for all commands."); opts.addOption(STATUS_CMD, true, "Prints the status report of the node."); opts.addOption(LIST_CMD, false, "List all running nodes. " + "Supports optional use of -states to filter nodes " + "based on node state, all -all to list all nodes."); Option nodeStateOpt = new Option(NODE_STATE_CMD, true, "Works with -list to filter nodes based on input comma-separated list of node states."); nodeStateOpt.setValueSeparator(','); nodeStateOpt.setArgs(Option.UNLIMITED_VALUES); nodeStateOpt.setArgName("States"); opts.addOption(nodeStateOpt); Option allOpt = new Option(NODE_ALL, false, "Works with -list to list all nodes."); opts.addOption(allOpt); opts.getOption(STATUS_CMD).setArgName("NodeId"); int exitCode = -1; CommandLine cliParser = null; try { cliParser = new GnuParser().parse(opts, args); } catch (MissingArgumentException ex) { sysout.println("Missing argument for options"); printUsage(opts); return exitCode; } if (cliParser.hasOption("status")) { if (args.length != 2) { printUsage(opts); return exitCode; } printNodeStatus(cliParser.getOptionValue("status")); } else if (cliParser.hasOption("list")) { Set<NodeState> nodeStates = new HashSet<NodeState>(); if (cliParser.hasOption(NODE_ALL)) { for (NodeState state : NodeState.values()) { nodeStates.add(state); } } else if (cliParser.hasOption(NODE_STATE_CMD)) { String[] types = cliParser.getOptionValues(NODE_STATE_CMD); if (types != null) { for (String type : types) { if (!type.trim().isEmpty()) { nodeStates.add(NodeState.valueOf( org.apache.hadoop.util.StringUtils.toUpperCase(type.trim()))); } } } } else { nodeStates.add(NodeState.RUNNING); } listClusterNodes(nodeStates); } else if (cliParser.hasOption(HELP_CMD)) { printUsage(opts); return 0; } else { syserr.println("Invalid Command Usage : "); printUsage(opts); } return 0; }
Example 20
Source File: GridVmNodesStarter.java From ignite with Apache License 2.0 | 4 votes |
/** * Main entry point. * * @param args Command line arguments. * @throws IgniteCheckedException If failed. */ public static void main(String[] args) throws IgniteCheckedException { System.setProperty(IGNITE_UPDATE_NOTIFIER, "false"); Options options = createOptions(); // Create the command line parser. CommandLineParser parser = new PosixParser(); String cfgPath = null; Integer nodesCnt = null; try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption(OPTION_CFG)) cfgPath = cmd.getOptionValue(OPTION_CFG); if (cmd.hasOption(OPTION_N)) try { nodesCnt = Integer.parseInt(cmd.getOptionValue(OPTION_N)); } catch (NumberFormatException ignored) { // No-op. } if (nodesCnt == null) nodesCnt = DFLT_NODES_COUNT; } catch (ParseException e) { exit(e.getMessage(), options, -1); } System.out.println(); System.out.println(">>> VM Nodes Starter parameters:"); System.out.println(" Nodes Count: " + nodesCnt); System.out.println(" Config Path: " + cfgPath); System.out.println(); final IgniteConfiguration[] cfgs = new IgniteConfiguration[nodesCnt]; for (int i = 0; i < nodesCnt; i++) cfgs[i] = getConfigurations(cfgPath).iterator().next(); final AtomicInteger cfgIdx = new AtomicInteger(0); GridTestUtils.runMultiThreadedAsync(new Callable<Object>() { @Override public Object call() throws Exception { G.start(cfgs[cfgIdx.getAndIncrement()]); return null; } }, nodesCnt, "test-node-starter"); }