org.apache.commons.cli.BasicParser源码实例Demo

类org.apache.commons.cli.BasicParser源码实例Demo

下面列出了org.apache.commons.cli.BasicParser 类实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: datawave   文件: UpgradeCounterValues.java
private void parseConfig(String[] args) throws ParseException {
    CommandLine cl = new BasicParser().parse(options, args);
    instanceName = cl.getOptionValue(instanceNameOpt.getOpt());
    zookeepers = cl.getOptionValue(zookeeperOpt.getOpt());
    username = cl.getOptionValue(usernameOpt.getOpt());
    password = cl.getOptionValue(passwordOpt.getOpt());
    tableName = cl.getOptionValue(tableNameOpt.getOpt());
    ranges = new ArrayList<>();
    if (!cl.hasOption(rangesOpt.getOpt())) {
        System.out.println("NOTE: no ranges specified on the command line. Scanning the entire table.");
        ranges.add(new Range());
    } else {
        for (String rangeStr : cl.getOptionValues(rangesOpt.getOpt())) {
            String[] startEnd = rangeStr.split("\\s*,\\s*");
            ranges.add(new Range(startEnd[0], false, startEnd[1], false));
        }
        System.out.println("Using ranges: " + ranges);
    }
    
    if (cl.hasOption(bsThreadsOpt.getOpt()))
        bsThreads = Integer.parseInt(cl.getOptionValue(bsThreadsOpt.getOpt()));
    if (cl.hasOption(bwThreadsOpt.getOpt()))
        bwThreads = Integer.parseInt(cl.getOptionValue(bwThreadsOpt.getOpt()));
    if (cl.hasOption(bwMemoryOpt.getOpt()))
        bwMemory = Long.parseLong(cl.getOptionValue(bwMemoryOpt.getOpt()));
}
 
源代码2 项目: super-cloudops   文件: CommandUtils.java
/**
 * Build parsing required options.
 * 
 * @param args
 * @return
 * @throws ParseException
 */
public CommandLine build(String args[]) throws ParseException {
	CommandLine line = null;
	try {
		line = new BasicParser().parse(options, args);
		if (log.isInfoEnabled()) {
			// Print input argument list.
			List<String> printArgs = asList(line.getOptions()).stream()
					.map(o -> o.getOpt() + "|" + o.getLongOpt() + "=" + o.getValue()).collect(toList());
			log.info("Parsed commond line args: {}", printArgs);
		}
	} catch (Exception e) {
		new HelpFormatter().printHelp(120, "\n", "", options, "");
		throw new ParseException(e.getMessage());
	}
	return line;
}
 
源代码3 项目: yb-sample-apps   文件: CmdLineOpts.java
private static void parseHelpDetailed(String[] args, Options options) throws Exception {
  Options helpOptions = new Options();
  helpOptions.addOption("help", true, "Print help.");
  CommandLineParser helpParser = new BasicParser();
  CommandLine helpCommandLine = null;
  try {
    helpCommandLine = helpParser.parse(helpOptions, args);
  } catch (org.apache.commons.cli.MissingArgumentException e1) {
    // This is ok since there was no help argument passed.
    return;
  }  catch (ParseException e) {
    return;
  }
  if (helpCommandLine.hasOption("help")) {
    printUsageDetails(options, "Usage:", helpCommandLine.getOptionValue("help"));
    System.exit(0);
  }
}
 
public static void main(String[] args) throws Exception {
  Options opts = new Options();
  opts.addOption("usesample", false, "Use the sample tables if present.");
  CommandLineParser parser = new BasicParser();
  CommandLine cmd = parser.parse(opts, args);
  args = cmd.getArgs();

  if (args.length != 3) {
    System.err.println("Usage: NeedingHelpGoPackageFinder "
        + "<GCP project ID for billing> "
        + "<BigQuery dataset for output tables> "
        + "<GCS bucket used by BigQuery for temporary data>");
    System.exit(1);
  }

  String projectId = args[0];
  String bigQueryDataset = args[1];
  String gcsBucket = args[2];
  NeedingHelpGoPackageFinder finder = new NeedingHelpGoPackageFinder(projectId, bigQueryDataset,
      gcsBucket, cmd.hasOption("usesample"));
  finder.run();
}
 
源代码5 项目: distributedlog   文件: DistributedLogServerApp.java
private void run() {
    try {
        logger.info("Running distributedlog server : args = {}", Arrays.toString(args));
        BasicParser parser = new BasicParser();
        CommandLine cmdline = parser.parse(options, args);
        runCmd(cmdline);
    } catch (ParseException pe) {
        logger.error("Argument error : {}", pe.getMessage());
        printUsage();
        Runtime.getRuntime().exit(-1);
    } catch (IllegalArgumentException iae) {
        logger.error("Argument error : {}", iae.getMessage());
        printUsage();
        Runtime.getRuntime().exit(-1);
    } catch (ConfigurationException ce) {
        logger.error("Configuration error : {}", ce.getMessage());
        printUsage();
        Runtime.getRuntime().exit(-1);
    } catch (IOException ie) {
        logger.error("Failed to start distributedlog server : ", ie);
        Runtime.getRuntime().exit(-1);
    } catch (ClassNotFoundException cnf) {
      logger.error("Failed to start distributedlog server : ", cnf);
      Runtime.getRuntime().exit(-1);
    }
}
 
源代码6 项目: ade   文件: AdeAnalysisOutputCompare.java
/**
 * Parses the arguments passed into the program.
 * 
 * @param args
 *            an array of String that contains all values passed into the
 *            program
 * @throws ParseException
 *             if there is an error parsing arguments
 */
private void parseArgs(String[] args) throws ParseException {
	final Options options = getCmdLineOptions();
	final CommandLineParser parser = new BasicParser();
	CommandLine cmd = null;

	/*
	 * Parse the args according to the options definition. Will throw
	 * MissingOptionException when a required option is not specified or the
	 * more generic ParseException if there is any other error parsing the
	 * arguments.
	 */
	cmd = parser.parse(options, args);

	if (cmd.hasOption("b")) {
		setBaselinePath(cmd.getOptionValue("b"));
	}
}
 
源代码7 项目: distributedlog   文件: DistributedLogServerApp.java
private void run() {
    try {
        logger.info("Running distributedlog server : args = {}", Arrays.toString(args));
        BasicParser parser = new BasicParser();
        CommandLine cmdline = parser.parse(options, args);
        runCmd(cmdline);
    } catch (ParseException pe) {
        logger.error("Argument error : {}", pe.getMessage());
        printUsage();
        Runtime.getRuntime().exit(-1);
    } catch (IllegalArgumentException iae) {
        logger.error("Argument error : {}", iae.getMessage());
        printUsage();
        Runtime.getRuntime().exit(-1);
    } catch (ConfigurationException ce) {
        logger.error("Configuration error : {}", ce.getMessage());
        printUsage();
        Runtime.getRuntime().exit(-1);
    } catch (IOException ie) {
        logger.error("Failed to start distributedlog server : ", ie);
        Runtime.getRuntime().exit(-1);
    }
}
 
源代码8 项目: brooklin   文件: EmbeddedZookeeper.java
private static CommandLine parseArgs(String[] args) {
  Options options = new Options();

  options.addOption("p", "port", true, "Zookeeper port number to use");
  options.addOption("l", "logDir", true, "Zookeeper logDir");
  options.addOption("s", "snapshotDir", true, "Zookeeper snapshotDir");

  // Parse the command line options
  CommandLineParser parser = new BasicParser();
  CommandLine commandLine;
  try {
    commandLine = parser.parse(options, args);
  } catch (Exception e) {
    commandLine = null;
    LOG.error(e.getMessage());
  }
  return commandLine;
}
 
源代码9 项目: postman-runner   文件: PostmanCollectionRunner.java
public static void main(String[] args) throws Exception {
	Options options = new Options();
	options.addOption(ARG_COLLECTION, true, "File name of the POSTMAN collection.");
	options.addOption(ARG_ENVIRONMENT, true, "File name of the POSTMAN environment variables.");
	options.addOption(ARG_FOLDER, true,
			"(Optional) POSTMAN collection folder (group) to execute i.e. \"My Use Cases\"");
	options.addOption(ARG_HALTONERROR, false, "(Optional) Stop on first error in POSTMAN folder.");

	CommandLineParser parser = new BasicParser();
	CommandLine cmd = parser.parse(options, args);
	String colFilename = cmd.getOptionValue(ARG_COLLECTION);
	String envFilename = cmd.getOptionValue(ARG_ENVIRONMENT);
	String folderName = cmd.getOptionValue(ARG_FOLDER);
	boolean haltOnError = cmd.hasOption(ARG_HALTONERROR);

	if (colFilename == null || colFilename.isEmpty() || envFilename == null || envFilename.isEmpty()) {
		// automatically generate the help statement
		HelpFormatter formatter = new HelpFormatter();
		formatter.printHelp("postman-runner", options);
		return;
	}

	PostmanCollectionRunner pcr = new PostmanCollectionRunner();
	pcr.runCollection(colFilename, envFilename, folderName, haltOnError, false, null);
}
 
@SuppressWarnings("static-access")
public static void main(String[] args) throws ParseException, AccumuloException, AccumuloSecurityException, TableNotFoundException, IOException {
    AccumuloCliOptions accumuloOptions = new AccumuloCliOptions();
    Options options = accumuloOptions.getOptions();
    options.addOption(OptionBuilder.isRequired(true).hasArg().withDescription("Config directory path").create(CONFIG_DIRECTORY_LOCATION_OVERRIDE));
    options.addOption(OptionBuilder.isRequired(false).hasArg().withDescription("Config file suffix").create(CONFIG_SUFFIEX_OVERRIDE));
    options.addOption(OptionBuilder.isRequired(false).hasArg().withDescription("Multiple numShards cache file path")
                    .create(MULTIPLE_NUMSHARD_CACHE_FILE_LOCATION_OVERRIDE));
    Configuration conf = accumuloOptions.getConf(args, true);
    CommandLine cl;
    String configDirectory = null;
    String configSuffix;
    try {
        cl = new BasicParser().parse(options, args);
        if (cl.hasOption(CONFIG_DIRECTORY_LOCATION_OVERRIDE)) {
            configDirectory = cl.getOptionValue(CONFIG_DIRECTORY_LOCATION_OVERRIDE);
        } else {
            HelpFormatter helpFormatter = new HelpFormatter();
            helpFormatter.printHelp("Generate Multiple NumShards Cache", options);
            System.exit(1);
        }
        if (cl.hasOption(MULTIPLE_NUMSHARD_CACHE_FILE_LOCATION_OVERRIDE)) {
            conf.set(NumShards.MULTIPLE_NUMSHARDS_CACHE_PATH, cl.getOptionValue(MULTIPLE_NUMSHARD_CACHE_FILE_LOCATION_OVERRIDE));
        }
        if (cl.hasOption(CONFIG_SUFFIEX_OVERRIDE)) {
            configSuffix = cl.getOptionValue(CONFIG_SUFFIEX_OVERRIDE);
        } else {
            configSuffix = "config.xml";
        }
        ConfigurationFileHelper.setConfigurationFromFiles(conf, configDirectory, configSuffix);
        NumShards numShards = new NumShards(conf);
        numShards.updateCache();
    } catch (ParseException ex) {
        log.error(GenerateMultipleNumShardsCacheFile.class.getName(), ex);
    }
}
 
源代码11 项目: datawave   文件: GenerateSplitsFile.java
@SuppressWarnings("static-access")
public static void main(String[] args) {
    AccumuloCliOptions accumuloOptions = new AccumuloCliOptions();
    Options options = accumuloOptions.getOptions();
    options.addOption(OptionBuilder.isRequired(true).hasArg().withDescription("Config directory path").create("cd"));
    options.addOption(OptionBuilder.isRequired(false).hasArg().withDescription("Config file suffix").create("cs"));
    options.addOption(OptionBuilder.isRequired(false).hasArg().withDescription("Splits file path").create("sp"));
    Configuration conf = accumuloOptions.getConf(args, true);
    CommandLine cl;
    String configDirectory = null;
    String configSuffix;
    try {
        cl = new BasicParser().parse(options, args);
        if (cl.hasOption("cd")) {
            configDirectory = cl.getOptionValue("cd");
            log.info("Set configDirectory to " + configDirectory);
        } else {
            HelpFormatter helpFormatter = new HelpFormatter();
            helpFormatter.printHelp("Generate Splits", options);
            System.exit(1);
        }
        if (cl.hasOption("sp")) {
            conf.set(MetadataTableSplits.SPLITS_CACHE_DIR, cl.getOptionValue("sp"));
            log.info("Set " + MetadataTableSplits.SPLITS_CACHE_DIR + " to " + cl.getOptionValue("sp"));
        }
        if (cl.hasOption("cs")) {
            configSuffix = cl.getOptionValue("cs");
        } else {
            configSuffix = "config.xml";
        }
        log.info("Set configSuffix to " + configSuffix);
        
        ConfigurationFileHelper.setConfigurationFromFiles(conf, configDirectory, configSuffix);
        MetadataTableSplits splitsFile = new MetadataTableSplits(conf);
        splitsFile.update();
    } catch (ParseException ex) {
        log.error(GenerateSplitsFile.class.getName(), ex);
    }
}
 
源代码12 项目: datawave   文件: AccumuloCliOptions.java
public boolean parseOptions(String[] args) {
    try {
        cl = new BasicParser().parse(options, args);
    } catch (ParseException ex) {
        log.error("Could not parse accumulo options", ex);
        return false;
    }
    return hasRequiredOptions(cl);
}
 
源代码13 项目: yb-sample-apps   文件: CmdLineOpts.java
private static void parseHelpOverview(String[] args, Options options) throws Exception {
  Options helpOptions = new Options();
  helpOptions.addOption("help", false, "Print help.");
  CommandLineParser helpParser = new BasicParser();
  CommandLine helpCommandLine = null;
  try {
    helpCommandLine = helpParser.parse(helpOptions, args);
  } catch (ParseException e) {
    return;
  }
  if (helpCommandLine.hasOption("help")) {
    printUsage(options, "Usage:");
    System.exit(0);
  }
}
 
源代码14 项目: ripme   文件: App.java
/**
 * Tries to parse commandline arguments.
 * @param args Array of commandline arguments.
 * @return CommandLine object containing arguments.
 */
private static CommandLine getArgs(String[] args) {
    BasicParser parser = new BasicParser();
    try {
        return parser.parse(getOptions(), args, false);
    } catch (ParseException e) {
        logger.error("[!] Error while parsing command-line arguments: " + Arrays.toString(args), e);
        System.exit(-1);
        return null;
    }
}
 
源代码15 项目: distributedlog   文件: MonitorServiceApp.java
private void run() {
    try {
        logger.info("Running monitor service.");
        BasicParser parser = new BasicParser();
        CommandLine cmdline = parser.parse(options, args);
        runCmd(cmdline);
    } catch (ParseException pe) {
        printUsage();
        Runtime.getRuntime().exit(-1);
    } catch (IOException ie) {
        logger.error("Failed to start monitor service : ", ie);
        Runtime.getRuntime().exit(-1);
    }
}
 
源代码16 项目: distributedlog   文件: Tool.java
@Override
public int runCmd(String[] args) throws Exception {
    try {
        BasicParser parser = new BasicParser();
        CommandLine cmdline = parser.parse(getOptions(), args);
        return runCmd(cmdline);
    } catch (ParseException e) {
        printUsage();
        return -1;
    }
}
 
源代码17 项目: api-compiler   文件: ServiceConfigGeneratorTool.java
public static void main(String[] args) throws ParseException, IOException {
  ConfigGeneratorDriver.ensureStaticsInitialized();
  ImmutableList<Option<?>> frameworkOptions =
      buildFrameworkOptions();
  Options apacheCliOptions = ToolOptions.convertToApacheCliOptions(frameworkOptions);
  CommandLine cmd = (new BasicParser()).parse(apacheCliOptions, args);
  if (ToolOptions.isHelpFlagSet(cmd)) {
    ToolOptions.printUsage("ServiceConfigGeneratorTool", apacheCliOptions);
    System.exit(0);
  }
  ToolOptions toolOptions = ToolOptions.getToolOptionsFromCommandLine(cmd, frameworkOptions);
  System.exit(new ConfigGeneratorDriver(toolOptions).run());
}
 
源代码18 项目: incubator-hivemall   文件: CommandLineUtils.java
@Nonnull
public static CommandLine parseOptions(final String[] args, final Options opts) {
    final BasicParser parser = new BasicParser();
    final CommandLine cl;
    try {
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        throw new IllegalArgumentException(e);
    }
    return cl;
}
 
源代码19 项目: distributedlog   文件: Tool.java
@Override
public int runCmd(String[] args) throws Exception {
    try {
        BasicParser parser = new BasicParser();
        CommandLine cmdline = parser.parse(getOptions(), args);
        return runCmd(cmdline);
    } catch (ParseException e) {
        printUsage();
        return -1;
    }
}
 
源代码20 项目: distributedlog   文件: MonitorServiceApp.java
private void run() {
    try {
        logger.info("Running monitor service.");
        BasicParser parser = new BasicParser();
        CommandLine cmdline = parser.parse(options, args);
        runCmd(cmdline);
    } catch (ParseException pe) {
        printUsage();
        Runtime.getRuntime().exit(-1);
    } catch (IOException ie) {
        logger.error("Failed to start monitor service : ", ie);
        Runtime.getRuntime().exit(-1);
    }
}
 
源代码21 项目: incubator-atlas   文件: HiveMetaStoreBridge.java
public static void main(String[] args) throws AtlasHookException {
    try {
    Configuration atlasConf = ApplicationProperties.get();
    String[] atlasEndpoint = atlasConf.getStringArray(ATLAS_ENDPOINT);
    if (atlasEndpoint == null || atlasEndpoint.length == 0){
        atlasEndpoint = new String[] { DEFAULT_DGI_URL };
    }
    AtlasClient atlasClient;

    if (!AuthenticationUtil.isKerberosAuthenticationEnabled()) {
        String[] basicAuthUsernamePassword = AuthenticationUtil.getBasicAuthenticationInput();
        atlasClient = new AtlasClient(atlasEndpoint, basicAuthUsernamePassword);
    } else {
        UserGroupInformation ugi = UserGroupInformation.getCurrentUser();
        atlasClient = new AtlasClient(ugi, ugi.getShortUserName(), atlasEndpoint);
    }

    Options options = new Options();
    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse( options, args);

    boolean failOnError = false;
    if (cmd.hasOption("failOnError")) {
        failOnError = true;
    }

    HiveMetaStoreBridge hiveMetaStoreBridge = new HiveMetaStoreBridge(atlasConf, new HiveConf(), atlasClient);
    hiveMetaStoreBridge.importHiveMetadata(failOnError);
    }
    catch(Exception e) {
        throw new AtlasHookException("HiveMetaStoreBridge.main() failed.", e);
    }
}
 
源代码22 项目: samza   文件: AbstractSamzaBench.java
public AbstractSamzaBench(String scriptName, String[] args) throws ParseException {
  options = new Options();
  options.addOption(
      CommandLineHelper.createOption(OPT_SHORT_PROPERTIES_FILE, OPT_LONG_PROPERTIES_FILE, OPT_ARG_PROPERTIES_FILE,
          true, OPT_DESC_PROPERTIES_FILE));
  options.addOption(
      CommandLineHelper.createOption(OPT_SHORT_NUM_EVENTS, OPT_LONG_NUM_EVENTS, OPT_ARG_NUM_EVENTS, true,
          OPT_DESC_NUM_EVENTS));

  options.addOption(
      CommandLineHelper.createOption(OPT_SHORT_START_PARTITION, OPT_LONG_START_PARTITION, OPT_ARG_START_PARTITION,
          true, OPT_DESC_START_PARTITION));
  options.addOption(
      CommandLineHelper.createOption(OPT_SHORT_END_PARTITION, OPT_LONG_END_PARTITION, OPT_ARG_END_PARTITION, true,
          OPT_DESC_END_PARTITION));
  options.addOption(
      CommandLineHelper.createOption(OPT_SHORT_STREAM, OPT_LONG_STREAM, OPT_ARG_STREAM, true, OPT_DESC_STREAM));

  addOptions(options);

  CommandLineParser parser = new BasicParser();
  try {
    cmd = parser.parse(options, args);
  } catch (Exception e) {
    HelpFormatter formatter = new HelpFormatter();
    formatter.printHelp(String.format("Error: %s.sh", scriptName), options);
    throw e;
  }
}
 
源代码23 项目: samza   文件: EventHubConsoleConsumer.java
public static void main(String[] args)
    throws EventHubException, IOException, ExecutionException, InterruptedException {
  Options options = new Options();
  options.addOption(
      CommandLineHelper.createOption(OPT_SHORT_EVENTHUB_NAME, OPT_LONG_EVENTHUB_NAME, OPT_ARG_EVENTHUB_NAME, true,
          OPT_DESC_EVENTHUB_NAME));

  options.addOption(CommandLineHelper.createOption(OPT_SHORT_NAMESPACE, OPT_LONG_NAMESPACE, OPT_ARG_NAMESPACE, true,
      OPT_DESC_NAMESPACE));

  options.addOption(CommandLineHelper.createOption(OPT_SHORT_KEY_NAME, OPT_LONG_KEY_NAME, OPT_ARG_KEY_NAME, true,
      OPT_DESC_KEY_NAME));

  options.addOption(
      CommandLineHelper.createOption(OPT_SHORT_TOKEN, OPT_LONG_TOKEN, OPT_ARG_TOKEN, true, OPT_DESC_TOKEN));

  CommandLineParser parser = new BasicParser();
  CommandLine cmd;
  try {
    cmd = parser.parse(options, args);
  } catch (Exception e) {
    HelpFormatter formatter = new HelpFormatter();
    formatter.printHelp(String.format("Error: %s%neh-console-consumer.sh", e.getMessage()), options);
    return;
  }

  String ehName = cmd.getOptionValue(OPT_SHORT_EVENTHUB_NAME);
  String namespace = cmd.getOptionValue(OPT_SHORT_NAMESPACE);
  String keyName = cmd.getOptionValue(OPT_SHORT_KEY_NAME);
  String token = cmd.getOptionValue(OPT_SHORT_TOKEN);

  consumeEvents(ehName, namespace, keyName, token);
}
 
源代码24 项目: samza   文件: GenerateKafkaEvents.java
public static void main(String[] args) throws UnsupportedEncodingException, InterruptedException {
  randValueGenerator = new RandomValueGenerator(System.currentTimeMillis());
  Options options = new Options();
  options.addOption(
      CommandLineHelper.createOption(OPT_SHORT_TOPIC_NAME, OPT_LONG_TOPIC_NAME, OPT_ARG_TOPIC_NAME, true, OPT_DESC_TOPIC_NAME));

  options.addOption(
      CommandLineHelper.createOption(OPT_SHORT_BROKER, OPT_LONG_BROKER, OPT_ARG_BROKER, false, OPT_DESC_BROKER));

  options.addOption(
      CommandLineHelper.createOption(OPT_SHORT_NUM_EVENTS, OPT_LONG_NUM_EVENTS, OPT_ARG_NUM_EVENTS, false, OPT_DESC_NUM_EVENTS));

  options.addOption(
      CommandLineHelper.createOption(OPT_SHORT_EVENT_TYPE, OPT_LONG_EVENT_TYPE, OPT_ARG_EVENT_TYPE, false, OPT_DESC_EVENT_TYPE));

  CommandLineParser parser = new BasicParser();
  CommandLine cmd;
  try {
    cmd = parser.parse(options, args);
  } catch (Exception e) {
    HelpFormatter formatter = new HelpFormatter();
    formatter.printHelp(String.format("Error: %s%ngenerate-events.sh", e.getMessage()), options);
    return;
  }

  String topicName = cmd.getOptionValue(OPT_SHORT_TOPIC_NAME);
  String broker = cmd.getOptionValue(OPT_SHORT_BROKER, DEFAULT_BROKER);
  long numEvents = Long.parseLong(cmd.getOptionValue(OPT_SHORT_NUM_EVENTS, String.valueOf(Long.MAX_VALUE)));
  String eventType = cmd.getOptionValue(OPT_SHORT_EVENT_TYPE);
  generateEvents(broker, topicName, eventType, numEvents);
}
 
源代码25 项目: samza   文件: SamzaSqlConsole.java
public static void main(String[] args) {
  Options options = new Options();
  options.addOption(
      CommandLineHelper.createOption(OPT_SHORT_SQL_FILE, OPT_LONG_SQL_FILE, OPT_ARG_SQL_FILE, false, OPT_DESC_SQL_FILE));
  options.addOption(
      CommandLineHelper.createOption(OPT_SHORT_SQL_STMT, OPT_LONG_SQL_STMT, OPT_ARG_SQL_STMT, false, OPT_DESC_SQL_STMT));

  CommandLineParser parser = new BasicParser();
  CommandLine cmd;
  try {
    cmd = parser.parse(options, args);
    if (!cmd.hasOption(OPT_SHORT_SQL_STMT) && !cmd.hasOption(OPT_SHORT_SQL_FILE)) {
      throw new Exception(
          String.format("One of the (%s or %s) options needs to be set", OPT_SHORT_SQL_FILE, OPT_SHORT_SQL_STMT));
    }
  } catch (Exception e) {
    HelpFormatter formatter = new HelpFormatter();
    formatter.printHelp(String.format("Error: %s%nsamza-sql-console.sh", e.getMessage()), options);
    return;
  }

  List<String> sqlStmts;

  if (cmd.hasOption(OPT_SHORT_SQL_FILE)) {
    String sqlFile = cmd.getOptionValue(OPT_SHORT_SQL_FILE);
    sqlStmts = SqlFileParser.parseSqlFile(sqlFile);
  } else {
    String sql = cmd.getOptionValue(OPT_SHORT_SQL_STMT);
    System.out.println("Executing sql " + sql);
    sqlStmts = Collections.singletonList(sql);
  }

  executeSql(sqlStmts);
}
 
源代码26 项目: kieker   文件: AbstractCommandLineTool.java
private CommandLine parseCommandLineArguments(final Options options, final String[] arguments) {
	final BasicParser parser = new BasicParser();

	try {
		return parser.parse(options, arguments);
	} catch (final ParseException ex) {
		// Note that we append ex.getMessage() to the log message on purpose to improve the
		// logging output on the console.
		LOGGER.error("An error occurred while parsing the command line arguments: {}", ex.getMessage(), ex);
		LOGGER.info("Use the option `--{}` for usage information", CMD_OPT_NAME_HELP_LONG);

		return null;
	}
}
 
源代码27 项目: rya   文件: MergeConfigurationCLI.java
/**
 *
 * @param args
 * @throws MergeConfigurationException
 */
public MergeConfigurationCLI(final String[] args) throws MergeConfigurationException {
    checkNotNull(args);

    final Options cliOptions = getOptions();
    final CommandLineParser parser = new BasicParser();
    try {
        cmd = parser.parse(cliOptions, args);
    } catch (final ParseException pe) {
        throw new MergeConfigurationException("Improperly formatted options.", pe);
    }
}
 
源代码28 项目: fnlp   文件: JointParerTester.java
public static void main(String[] args) throws Exception {

		Options opt = new Options();

		opt.addOption("h", false, "Print help for this application");

		BasicParser parser = new BasicParser();
		CommandLine cl;
		try {
			cl = parser.parse(opt, args);
		} catch (Exception e) {
			System.err.println("Parameters format error");
			return;
		}

		if (args.length == 0 || cl.hasOption('h')) {
			HelpFormatter f = new HelpFormatter();
			f.printHelp(
					"Tagger:\n"
							+ "ParserTester [option] model_file test_file result_file;\n",
					opt);
			return;
		}

		String[] args1 = cl.getArgs();
		String modelfile  = args1[0]; 
		String testfile = args1[1]; 
		String resultfile = args1[2];

		JointParerTester tester = new JointParerTester(modelfile);
		tester.test(testfile, resultfile, "UTF-8");
	}
 
源代码29 项目: fnlp   文件: JointParerTrainer.java
/**
 * 主文件
 * 
 * @param args
 *            : 训练文件;模型文件;循环次数
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
	//		args = new String[2];
	//		args[0] = "./tmp/malt.train";
	//		args[1] = "./tmp/Malt2Model.gz";
	Options opt = new Options();

	opt.addOption("h", false, "Print help for this application");
	opt.addOption("iter", true, "iterative num, default 50");
	opt.addOption("c", true, "parameters 1, default 1");

	BasicParser parser = new BasicParser();
	CommandLine cl;
	try {
		cl = parser.parse(opt, args);
	} catch (Exception e) {
		System.err.println("Parameters format error");
		return;
	}

	if (args.length == 0 || cl.hasOption('h')) {
		HelpFormatter f = new HelpFormatter();
		f.printHelp(
				"Tagger:\n"
						+ "ParserTrainer [option] train_file model_file;\n",
						opt);
		return;
	}
	args = cl.getArgs();
	String datafile = args[0];
	String modelfile = args[1];
	int maxite = Integer.parseInt(cl.getOptionValue("iter", "50"));
	float c = Float.parseFloat(cl.getOptionValue("c", "1"));

	JointParerTrainer trainer = new JointParerTrainer(modelfile);
	trainer.train(datafile, maxite, c);
}
 
源代码30 项目: fnlp   文件: ParserTrainer.java
/**
 * 主文件
 * 
 * @param args
 *            : 训练文件;模型文件;循环次数
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
	args = new String[2];
	args[0] = "./tmp/CoNLL2009-ST-Chinese-train.txt";
	args[1] = "./tmp/modelConll.gz";
	Options opt = new Options();

	opt.addOption("h", false, "Print help for this application");
	opt.addOption("iter", true, "iterative num, default 50");
	opt.addOption("c", true, "parameters 1, default 1");

	BasicParser parser = new BasicParser();
	CommandLine cl;
	try {
		cl = parser.parse(opt, args);
	} catch (Exception e) {
		System.err.println("Parameters format error");
		return;
	}
	
	if (args.length == 0 || cl.hasOption('h')) {
		HelpFormatter f = new HelpFormatter();
		f.printHelp(
				"Tagger:\n"
						+ "ParserTrainer [option] train_file model_file;\n",
				opt);
		return;
	}
	args = cl.getArgs();
	String datafile = args[0];
	String modelfile = args[1];
	int maxite = Integer.parseInt(cl.getOptionValue("iter", "50"));
	float c = Float.parseFloat(cl.getOptionValue("c", "1"));
	
	ParserTrainer trainer = new ParserTrainer(modelfile);
	trainer.train(datafile, maxite, c);
}