Java Code Examples for org.apache.commons.cli.CommandLine

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project android-rindirect, under directory /rindirect/src/main/java/de/akquinet/android/rindirect/.

Source file: Main.java

  23 
vote

/** 
 * Main method. This methods defines the arguments, parse them and launch the R indirection generation.
 * @param args the arguments.
 * @throws ParseException
 * @throws IOException
 */
public static void main(String[] args) throws ParseException, Exception {
  LOGGER.setLevel(Level.WARNING);
  Options options=new Options();
  options.addOption("P","package",true,"destination package (mandatory)").addOption("R","classname",true,"generated java file [R]").addOption("D","destination",true,"the root of the destination [src]").addOption("I","input",true,"R file [searched in the 'gen' folder]").addOption("V","verbose",false,"Enable verbose mode");
  CommandLineParser parser=new PosixParser();
  CommandLine cmd=parser.parse(options,args);
  RIndirect rindirect=configure(cmd);
  rindirect.generate();
}
 

Example 2

From project dcm4che, under directory /dcm4che-tool/dcm4che-tool-mkkos/src/main/java/org/dcm4che/tool/mkkos/.

Source file: MkKOS.java

  22 
vote

private static CommandLine parseComandLine(String[] args) throws ParseException {
  Options opts=new Options();
  CLIUtils.addCommonOptions(opts);
  addOptions(opts);
  CommandLine cl=CLIUtils.parseComandLine(args,opts,rb,MkKOS.class);
  if (cl.getArgList().isEmpty())   throw new ParseException(rb.getString("missing"));
  return cl;
}
 

Example 3

From project Flume-Hive, under directory /src/java/com/cloudera/flume/core/.

Source file: EventUtil.java

  22 
vote

public static CommandLine defaultSinkParser(String[] argv) throws ParseException {
  Options options=new Options();
  options.addOption("d",false,"Directly send to collector");
  options.addOption("c",false,"Directly output to console");
  CommandLineParser parser=new PosixParser();
  CommandLine cmd=parser.parse(options,argv);
  return cmd;
}
 

Example 4

From project flume_1, under directory /flume-core/src/main/java/com/cloudera/flume/core/.

Source file: EventUtil.java

  22 
vote

public static CommandLine defaultSinkParser(String[] argv) throws ParseException {
  Options options=new Options();
  options.addOption("d",false,"Directly send to collector");
  options.addOption("c",false,"Directly output to console");
  CommandLineParser parser=new PosixParser();
  CommandLine cmd=parser.parse(options,argv);
  return cmd;
}
 

Example 5

From project ISAvalidator-ISAconverter-BIImanager, under directory /import_layer/src/test/java/org/isatools/isatab/commandline/permission_manager/.

Source file: PermissionManagerTest.java

  22 
vote

@Test public void testCreateNewUserFromOptions() throws ParseException {
  PermissionManager permMgr=new PermissionManager(entityManager);
  String[] args=new String[]{"--name","Marco","--surename","Brandizi","-p","secret","--date","10/09/1973","-r","submitter"};
  CommandLineParser clparser=new GnuParser();
  CommandLine cmdl=clparser.parse(permMgr.createUserDefOptions(),args);
  Person user=permMgr.createNewUserFromOptions("zakmck",cmdl);
  out.println(user);
  assertEquals("Wrong created user!","zakmck",user.getUserName());
  assertEquals("Wrong created user!","Marco",user.getFirstName());
  assertEquals("Wrong created user!",StringEncryption.getInstance().encrypt("secret"),user.getPassword());
  assertEquals("Wrong created user!",UserRole.SUBMITTER,user.getRole());
  assertEquals("Wrong created user!",new GregorianCalendar(1973,Calendar.SEPTEMBER,10).getTime(),user.getJoinDate());
}
 

Example 6

From project Ivory, under directory /oozie/src/main/java/org/apache/ivory/workflow/.

Source file: IvoryPostProcessing.java

  22 
vote

@Override public int run(String[] args) throws Exception {
  CommandLine cmd=getCommand(args);
  invokeUserMessageProducer(cmd);
  invokeLogProducer(cmd);
  invokeIvoryMessageProducer(cmd);
  return 0;
}
 

Example 7

From project jmxsh, under directory /src/jmxsh/.

Source file: CloseCmd.java

  22 
vote

private CommandLine parseCommandLine(TclObject argv[]) throws ParseException {
  String[] args=new String[argv.length - 1];
  for (int i=0; i < argv.length - 1; i++)   args[i]=argv[i + 1].toString();
  CommandLine cl=(new PosixParser()).parse(this.opts,args);
  return cl;
}
 

Example 8

From project jnrpe-lib, under directory /jnrpe-lib/src/main/java/it/jnrpe/plugins/.

Source file: PluginProxy.java

  22 
vote

/** 
 * Executes the proxied plugin passing the received arguments as parameters.
 * @param args The parameters to be passed to the plugin
 * @return The return value of the plugin.
 */
public ReturnValue execute(final String[] args){
  CommandLineParser clp=new PosixParser();
  try {
    CommandLine cl=clp.parse(m_Options,args);
    if (getListeners() != null && m_plugin instanceof IPluginInterfaceEx) {
      ((IPluginInterfaceEx)m_plugin).addListeners(getListeners());
    }
    return m_plugin.execute(new PluginCommandLine(cl));
  }
 catch (  ParseException e) {
    return new ReturnValue(Status.UNKNOWN,e.getMessage());
  }
}
 

Example 9

From project Metamorphosis, under directory /metamorphosis-server-wrapper/src/main/java/com/taobao/metamorphosis/.

Source file: ServerStartup.java

  22 
vote

public static void main(final String[] args){
  final CommandLine line=StartupHelp.parseCmdLine(args,new PosixParser());
  final Map<String,Properties> pluginsInfo=getPluginsInfo(line);
  final EnhancedBroker broker=new EnhancedBroker(getMetaConfig(line),pluginsInfo);
  broker.start();
}
 

Example 10

From project bagheera, under directory /src/main/java/com/mozilla/bagheera/consumer/.

Source file: KafkaHBaseConsumer.java

  21 
vote

public static void main(String[] args){
  OptionFactory optFactory=OptionFactory.getInstance();
  Options options=KafkaConsumer.getOptions();
  options.addOption(optFactory.create("tbl","table",true,"HBase table name.").required());
  options.addOption(optFactory.create("f","family",true,"Column family."));
  options.addOption(optFactory.create("q","qualifier",true,"Column qualifier."));
  options.addOption(optFactory.create("pd","prefixdate",false,"Prefix key with salted date."));
  CommandLineParser parser=new GnuParser();
  ShutdownHook sh=ShutdownHook.getInstance();
  try {
    CommandLine cmd=parser.parse(options,args);
    final KafkaConsumer consumer=KafkaConsumer.fromOptions(cmd);
    sh.addFirst(consumer);
    final KeyValueSink sink=new HBaseSink(cmd.getOptionValue("table"),cmd.getOptionValue("family","data"),cmd.getOptionValue("qualifier","json"),Boolean.parseBoolean(cmd.getOptionValue("prefixdate","true")));
    sh.addLast(sink);
    consumer.setSink(sink);
    MetricsManager.getInstance();
    consumer.poll();
  }
 catch (  ParseException e) {
    LOG.error("Error parsing command line options",e);
    HelpFormatter formatter=new HelpFormatter();
    formatter.printHelp(KafkaHBaseConsumer.class.getName(),options);
  }
}
 

Example 11

From project behemoth, under directory /core/src/main/java/com/digitalpebble/behemoth/util/.

Source file: ContentExtractor.java

  21 
vote

public int run(String[] args) throws Exception {
  Options options=new Options();
  HelpFormatter formatter=new HelpFormatter();
  CommandLineParser parser=new GnuParser();
  options.addOption("h","help",false,"print this message");
  options.addOption("i","input",true,"Behemoth corpus");
  options.addOption("o","output",true,"local corpus dir");
  options.addOption("b","binary",false,"dumps binary content, text otherwise");
  options.addOption("n","filenaming",true,"whether to name files based on URL, UUID (default) or NUM");
  try {
    CommandLine line=parser.parse(options,args);
    String input=line.getOptionValue("i");
    String output=line.getOptionValue("o");
    if (line.hasOption("help")) {
      formatter.printHelp("ContentExtractor",options);
      return 0;
    }
    if (input == null || output == null) {
      formatter.printHelp("ContentExtractor",options);
      return -1;
    }
    dumpBinary=line.hasOption("binary");
    if (line.hasOption("filenaming")) {
      String naming=line.getOptionValue("n");
      mode=FileNamingMode.toMode(naming);
    }
    return generateDocs(input,output);
  }
 catch (  ParseException e) {
    formatter.printHelp("ContentExtractor",options);
    return -1;
  }
}
 

Example 12

From project bonecp, under directory /bonecp-benchmark/src/main/java/com/jolbox/benchmark/.

Source file: BenchmarkMain.java

  21 
vote

/** 
 * @param args
 * @throws ClassNotFoundException 
 * @throws PropertyVetoException 
 * @throws SQLException 
 * @throws NoSuchMethodException 
 * @throws InvocationTargetException 
 * @throws IllegalAccessException 
 * @throws InterruptedException 
 * @throws SecurityException 
 * @throws IllegalArgumentException 
 * @throws NamingException 
 * @throws ParseException 
 */
public static void main(String[] args) throws ClassNotFoundException, SQLException, PropertyVetoException, IllegalArgumentException, SecurityException, InterruptedException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, NamingException, ParseException {
  Options options=new Options();
  options.addOption("t","threads",true,"Max number of threads");
  options.addOption("s","stepping",true,"Stepping of threads");
  options.addOption("p","poolsize",true,"Pool size");
  options.addOption("h","help",false,"Help");
  CommandLineParser parser=new PosixParser();
  CommandLine cmd=parser.parse(options,args);
  if (cmd.hasOption("h")) {
    HelpFormatter formatter=new HelpFormatter();
    formatter.printHelp("benchmark.jar",options);
    System.exit(1);
  }
  Class.forName("com.jolbox.bonecp.MockJDBCDriver");
  new MockJDBCDriver();
  BenchmarkTests tests=new BenchmarkTests();
  BenchmarkTests.threads=200;
  BenchmarkTests.stepping=20;
  BenchmarkTests.pool_size=200;
  System.out.println("JIT warm up");
  tests.testMultiThreadedConstantDelay(0);
  BenchmarkTests.threads=200;
  BenchmarkTests.stepping=5;
  BenchmarkTests.pool_size=100;
  if (cmd.hasOption("t")) {
    BenchmarkTests.threads=Integer.parseInt(cmd.getOptionValue("t","400"));
  }
  if (cmd.hasOption("s")) {
    BenchmarkTests.stepping=Integer.parseInt(cmd.getOptionValue("s","20"));
  }
  if (cmd.hasOption("p")) {
    BenchmarkTests.pool_size=Integer.parseInt(cmd.getOptionValue("p","200"));
  }
  System.out.println("Starting benchmark tests with " + BenchmarkTests.threads + " threads (stepping "+ BenchmarkTests.stepping+ ") using pool size of "+ BenchmarkTests.pool_size+ " connections");
  System.out.println("Starting tests");
  plotLineGraph(tests.testMultiThreadedConstantDelay(0),0,false);
  plotBarGraph("Single Thread","bonecp-singlethread-poolsize-" + BenchmarkTests.pool_size + "-threads-"+ BenchmarkTests.threads+ ".png",tests.testSingleThread());
  plotBarGraph("Prepared Statement\nSingle Threaded","bonecp-preparedstatement-single-poolsize-" + BenchmarkTests.pool_size + "-threads-"+ BenchmarkTests.threads+ ".png",tests.testPreparedStatementSingleThread());
}
 

Example 13

From project bpelunit, under directory /net.bpelunit.framework.client.command/src/main/java/net/bpelunit/framework/ui/command/.

Source file: BPELUnitCommandLineRunner.java

  21 
vote

@SuppressWarnings("unchecked") private final void parseOptionsFromCommandLine(String[] args){
  saveCoverageDetails=false;
  CommandLineParser parser=new PosixParser();
  try {
    CommandLine cmd=parser.parse(options,args);
    verifyCommandLineArguments(cmd);
    verbose=cmd.hasOption(PARAMETER_VERBOSE);
    xmlFileName=trimEqualsSignFromStart(cmd.getOptionValue(PARAMETER_XMLFILE));
    logFileName=trimEqualsSignFromStart(cmd.getOptionValue(PARAMETER_LOGFILE));
    if (cmd.hasOption(PARAMETER_COVERAGEFILE)) {
      covFileName=trimEqualsSignFromStart(cmd.getOptionValue(PARAMETER_COVERAGEFILE));
    }
    if (cmd.hasOption(PARAMETER_DETAILEDCOVERAGEFILE)) {
      covFileName=trimEqualsSignFromStart(cmd.getOptionValue(PARAMETER_DETAILEDCOVERAGEFILE));
      saveCoverageDetails=true;
    }
    ArrayList<String> remainingOptions=new ArrayList<String>(cmd.getArgList());
    setAndValidateTestSuiteFileName(remainingOptions.remove(0));
    testCaseNames=remainingOptions;
  }
 catch (  ParseException e) {
    showHelpAndExit();
  }
}
 

Example 14

From project cidb, under directory /obo2solr/src/main/java/edu/toronto/cs/cidb/obo2solr/.

Source file: Main.java

  21 
vote

public static void main(String args[]){
  Options options=generateOptions();
  try {
    CommandLineParser parser=new PosixParser();
    CommandLine cmd=parser.parse(options,args);
    if (!cmd.hasOption(OBO_DB_LOCATION_OPTION) || cmd.hasOption(HELP_OPTION)) {
      showUsage(options);
      System.exit(cmd.hasOption(HELP_OPTION) ? 0 : 1);
    }
    ParameterPreparer paramPrep=new ParameterPreparer();
    SolrUpdateGenerator generator=new SolrUpdateGenerator();
    File input=paramPrep.getInputFileHandler(cmd.getOptionValue(OBO_DB_LOCATION_OPTION));
    File output=paramPrep.getOutputFileHandler(cmd.getOptionValue(OUTPUT_XML_LOCATION_OPTION,DEFAULT_OUTPUT_XML_LOCATION));
    Map<String,Double> fieldSelection=paramPrep.getFieldSelection(cmd.getOptionValue(INDEX_FILEDS_OPTION,""));
    generator.transform(input,output,fieldSelection);
  }
 catch (  Exception ex) {
    ex.printStackTrace();
  }
}
 

Example 15

From project Cloud9, under directory /src/dist/edu/umd/cloud9/collection/.

Source file: DocnoMapping.java

  21 
vote

public static DefaultBuilderOptions parseDefaultOptions(String[] args){
  Options options=new Options();
  options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("(required) collection path").create(COLLECTION_OPTION));
  options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("(required) output DocnoMapping path").create(MAPPING_OPTION));
  options.addOption(OptionBuilder.withArgName("class").hasArg().withDescription("(optional) fully-qualified Hadoop InputFormat").create(FORMAT_OPTION));
  CommandLine cmdline;
  CommandLineParser parser=new GnuParser();
  try {
    cmdline=parser.parse(options,args);
  }
 catch (  ParseException exp) {
    System.err.println("Error parsing command line: " + exp.getMessage());
    return null;
  }
  if (!cmdline.hasOption(COLLECTION_OPTION) || !cmdline.hasOption(MAPPING_OPTION)) {
    HelpFormatter formatter=new HelpFormatter();
    formatter.printHelp(DefaultBuilderOptions.class.getName(),options);
    ToolRunner.printGenericCommandUsage(System.out);
    return null;
  }
  DefaultBuilderOptions parsedOptions=new DefaultBuilderOptions();
  parsedOptions.inputFormat=SequenceFileInputFormat.class;
  if (cmdline.hasOption(FORMAT_OPTION)) {
    try {
      parsedOptions.inputFormat=(Class<? extends InputFormat>)Class.forName(cmdline.getOptionValue(FORMAT_OPTION));
    }
 catch (    ClassNotFoundException e) {
      throw new RuntimeException(e);
    }
  }
  parsedOptions.collection=cmdline.getOptionValue(COLLECTION_OPTION);
  parsedOptions.docnoMapping=cmdline.getOptionValue(MAPPING_OPTION);
  return parsedOptions;
}
 

Example 16

From project cw-omnibus, under directory /Push/GCMCommand/src/com/commonsware/android/gcm/cmd/.

Source file: GCM.java

  21 
vote

@SuppressWarnings("static-access") public static void main(String[] args){
  Option helpOpt=new Option("h","help",false,"print this message");
  Option apiKeyOpt=OptionBuilder.withArgName("key").hasArg().isRequired().withDescription("GCM API key").withLongOpt("apiKey").create('a');
  Option deviceOpt=OptionBuilder.withArgName("regId").hasArg().isRequired().withDescription("device to send to").withLongOpt("device").create('d');
  Option dataOpt=OptionBuilder.withArgName("key=value").hasArgs(2).withDescription("datum to send").withValueSeparator().withLongOpt("data").create('D');
  Options options=new Options();
  options.addOption(apiKeyOpt);
  options.addOption(deviceOpt);
  options.addOption(dataOpt);
  options.addOption(helpOpt);
  CommandLineParser parser=new PosixParser();
  try {
    CommandLine line=parser.parse(options,args);
    if (line.hasOption('h') || !line.hasOption('a') || !line.hasOption('d')) {
      HelpFormatter formatter=new HelpFormatter();
      formatter.printHelp("gcm",options,true);
    }
 else {
      sendMessage(line.getOptionValue('a'),Arrays.asList(line.getOptionValues('d')),line.getOptionProperties("data"));
    }
  }
 catch (  org.apache.commons.cli.MissingOptionException moe) {
    System.err.println("Invalid command syntax");
    HelpFormatter formatter=new HelpFormatter();
    formatter.printHelp("gcm",options,true);
  }
catch (  Exception e) {
    e.printStackTrace();
  }
}
 

Example 17

From project flume, under directory /flume-ng-channels/flume-file-channel/src/main/java/org/apache/flume/channel/file/.

Source file: CheckpointRebuilder.java

  21 
vote

public static void main(String[] args) throws Exception {
  Options options=new Options();
  Option opt=new Option("c",true,"checkpoint directory");
  opt.setRequired(true);
  options.addOption(opt);
  opt=new Option("l",true,"comma-separated list of log directories");
  opt.setRequired(true);
  options.addOption(opt);
  options.addOption(opt);
  opt=new Option("t",true,"capacity of the channel");
  opt.setRequired(true);
  options.addOption(opt);
  CommandLineParser parser=new GnuParser();
  CommandLine cli=parser.parse(options,args);
  File checkpointDir=new File(cli.getOptionValue("c"));
  String[] logDirs=cli.getOptionValue("l").split(",");
  List<File> logFiles=Lists.newArrayList();
  for (  String logDir : logDirs) {
    File[] files=new File(logDir).listFiles();
    logFiles.addAll(Arrays.asList(files));
  }
  int capacity=Integer.parseInt(cli.getOptionValue("t"));
  File checkpointFile=new File(checkpointDir,"checkpoint");
  if (checkpointFile.exists()) {
    LOG.error("Cannot execute fast replay",new IllegalStateException("Checkpoint exists" + checkpointFile));
  }
 else {
    EventQueueBackingStore backingStore=EventQueueBackingStoreFactory.get(checkpointFile,capacity,"channel");
    FlumeEventQueue queue=new FlumeEventQueue(backingStore,new File(checkpointDir,"inflighttakes"),new File(checkpointDir,"inflightputs"));
    CheckpointRebuilder rebuilder=new CheckpointRebuilder(logFiles,queue);
    if (rebuilder.rebuild()) {
      rebuilder.writeCheckpoint();
    }
 else {
      LOG.error("Could not rebuild the checkpoint due to errors.");
    }
  }
}
 

Example 18

From project hank, under directory /src/java/com/rapleaf/hank/util/.

Source file: CliUtils.java

  21 
vote

public static CommandLine parseAndHelp(String appName,Options options,String[] args){
  options.addOption(HELP_OPTION);
  Parser parser=new GnuParser();
  CommandLine line=null;
  try {
    line=parser.parse(options,args);
  }
 catch (  MissingOptionException e) {
    new HelpFormatter().printHelp(appName,options,true);
    throw new IllegalArgumentException();
  }
catch (  MissingArgumentException e) {
    new HelpFormatter().printHelp(appName,options,true);
    throw new IllegalArgumentException();
  }
catch (  ParseException e) {
    System.err.println("Unexpected Exception: " + e);
    throw new IllegalArgumentException();
  }
  if (line.hasOption("help")) {
    new HelpFormatter().printHelp(appName,options,true);
    throw new IllegalArgumentException();
  }
  return line;
}
 

Example 19

From project heritrix3, under directory /commons/src/main/java/org/archive/io/.

Source file: Arc2Warc.java

  21 
vote

/** 
 * Command-line interface to Arc2Warc.
 * @param args Command-line arguments.
 * @throws ParseException Failed parse of the command line.
 * @throws IOException
 * @throws java.text.ParseException
 */
@SuppressWarnings("unchecked") public static void main(String[] args) throws ParseException, IOException, java.text.ParseException {
  Options options=new Options();
  options.addOption(new Option("h","help",false,"Prints this message and exits."));
  options.addOption(new Option("f","force",false,"Force overwrite of target file."));
  PosixParser parser=new PosixParser();
  CommandLine cmdline=parser.parse(options,args,false);
  List<String> cmdlineArgs=cmdline.getArgList();
  Option[] cmdlineOptions=cmdline.getOptions();
  HelpFormatter formatter=new HelpFormatter();
  if (cmdlineArgs.size() <= 0) {
    usage(formatter,options,0);
  }
  boolean force=false;
  for (int i=0; i < cmdlineOptions.length; i++) {
switch (cmdlineOptions[i].getId()) {
case 'h':
      usage(formatter,options,0);
    break;
case 'f':
  force=true;
break;
default :
throw new RuntimeException("Unexpected option: " + +cmdlineOptions[i].getId());
}
}
if (cmdlineArgs.size() != 2) {
usage(formatter,options,0);
}
(new Arc2Warc()).transform(new File(cmdlineArgs.get(0)),new File(cmdlineArgs.get(1)),force);
}
 

Example 20

From project httpcore, under directory /httpcore-ab/src/main/java/org/apache/http/benchmark/.

Source file: HttpBenchmark.java

  21 
vote

public static void main(String[] args) throws Exception {
  Options options=CommandLineUtils.getOptions();
  CommandLineParser parser=new PosixParser();
  CommandLine cmd=parser.parse(options,args);
  if (args.length == 0 || cmd.hasOption('h') || cmd.getArgs().length != 1) {
    CommandLineUtils.showUsage(options);
    System.exit(1);
  }
  Config config=new Config();
  CommandLineUtils.parseCommandLine(cmd,config);
  if (config.getUrl() == null) {
    CommandLineUtils.showUsage(options);
    System.exit(1);
  }
  HttpBenchmark httpBenchmark=new HttpBenchmark(config);
  httpBenchmark.execute();
}
 

Example 21

From project indextank-engine, under directory /src/main/java/com/flaptor/indextank/storage/.

Source file: IndexesLogServer.java

  21 
vote

public static void main(String[] args) throws IOException, InterruptedException {
  CommandLineParser parser=new PosixParser();
  int readerPort, managerPort;
  try {
    CommandLine line=parser.parse(getOptions(),args);
    if (line.hasOption("help")) {
      printHelp(getOptions(),null);
      System.exit(1);
      return;
    }
    String val=null;
    val=line.getOptionValue("reader_port",null);
    if (null != val) {
      readerPort=Integer.valueOf(val);
    }
 else {
      printHelp(getOptions(),"Must specify a server port");
      System.exit(1);
      return;
    }
    val=null;
    val=line.getOptionValue("manager_port",null);
    if (null != val) {
      managerPort=Integer.valueOf(val);
    }
 else {
      printHelp(getOptions(),"Must specify a server port");
      System.exit(1);
      return;
    }
  }
 catch (  ParseException exp) {
    printHelp(getOptions(),exp.getMessage());
    System.exit(1);
    return;
  }
  new IndexesLogServer(readerPort,managerPort).start();
}
 

Example 22

From project jackrabbit-oak, under directory /oak-mongomk-perf/src/main/java/org/apache/jackrabbit/mongomk/perf/.

Source file: MicroKernelPerf.java

  21 
vote

@SuppressWarnings("static-access") private static void evalCommandLineOptions(String[] args) throws Exception {
  Option log4jOption=OptionBuilder.withLongOpt("log4j-path").hasArg().withArgName("path").withDescription("path to a log4j config file").create("log4j");
  Option masterOption=OptionBuilder.withLongOpt("master-mode").withDescription("starts this in master mode").create("master");
  Option prepareOption=OptionBuilder.withLongOpt("prepare-environment").withDescription("resets the environment before executing").create("prep");
  Options options=new Options();
  options.addOption(log4jOption);
  options.addOption(masterOption);
  options.addOption(prepareOption);
  CommandLineParser parser=new GnuParser();
  CommandLine line=parser.parse(options,args);
  if (line.hasOption(log4jOption.getOpt())) {
    configLog4J(line.getOptionValue(log4jOption.getOpt()));
  }
  if (line.hasOption(masterOption.getOpt())) {
    masterMode=true;
  }
  if (line.hasOption(prepareOption.getOpt())) {
    prepareEnvironment=true;
  }
}
 

Example 23

From project jnrpe-server, under directory /jnrpe-server/src/main/java/it/jnrpe/server/.

Source file: JNRPEServer.java

  21 
vote

public static void main(String[] args) throws Exception {
  CommandLine cl=parseCommandLine(args);
  if (cl.hasOption("help") && cl.getOptionValue("help") == null)   printUsage(null);
  if (cl.hasOption("version"))   printVersion();
  JNRPEConfiguration conf=loadConfiguration(cl.getOptionValue("conf"));
  String sPluginPath=conf.getServerSection().getPluginPath();
  if (sPluginPath == null) {
    System.out.println("Plugin path has not been specified");
    System.exit(-1);
  }
  File fPluginPath=new File(sPluginPath);
  if (fPluginPath.exists()) {
    if (!fPluginPath.isDirectory()) {
      System.out.println("Specified plugin path ('" + sPluginPath + "') must be a directory");
      System.exit(-1);
    }
  }
 else {
    System.out.println("Specified plugin path ('" + sPluginPath + "') do not exist");
    System.exit(-1);
  }
  PluginRepository pr=loadPluginDefinitions(conf.getServerSection().getPluginPath());
  if (cl.hasOption("help") && cl.getOptionValue("help") != null)   printHelp(pr,cl.getOptionValue("help"));
  if (cl.hasOption("list"))   printPluginList(pr);
  JNRPE jnrpe=new JNRPE(pr,conf.createCommandRepository());
  jnrpe.addEventListener(new EventLoggerListener());
  for (  String sAcceptedAddress : conf.getServerSection().getAllowedAddresses())   jnrpe.addAcceptedHost(sAcceptedAddress);
  for (  BindAddress bindAddress : conf.getServerSection().getBindAddresses()) {
    int iPort=5666;
    String[] vsParts=bindAddress.getBindingAddress().split(":");
    String sIp=vsParts[0];
    if (vsParts.length > 1)     iPort=Integer.parseInt(vsParts[1]);
    jnrpe.listen(sIp,iPort,bindAddress.isSSL());
  }
}
 

Example 24

From project Kairos, under directory /src/java/org/apache/nutch/indexer/field/.

Source file: AnchorFields.java

  21 
vote

/** 
 * Runs the AnchorFields job.
 */
public int run(String[] args) throws Exception {
  Options options=new Options();
  Option helpOpts=OptionBuilder.withArgName("help").withDescription("show this help message").create("help");
  Option outputOpts=OptionBuilder.withArgName("output").hasArg().withDescription("the output index directory").create("output");
  Option webGraphDbOpts=OptionBuilder.withArgName("webgraphdb").hasArg().withDescription("the webgraphdb to use").create("webgraphdb");
  Option basicFieldOpts=OptionBuilder.withArgName("basicfields").hasArgs().withDescription("the basicfields to use").create("basicfields");
  options.addOption(helpOpts);
  options.addOption(webGraphDbOpts);
  options.addOption(basicFieldOpts);
  options.addOption(outputOpts);
  CommandLineParser parser=new GnuParser();
  try {
    CommandLine line=parser.parse(options,args);
    if (line.hasOption("help") || !line.hasOption("webgraphdb") || !line.hasOption("output")|| !line.hasOption("basicfields")) {
      HelpFormatter formatter=new HelpFormatter();
      formatter.printHelp("AnchorFields",options);
      return -1;
    }
    String webGraphDb=line.getOptionValue("webgraphdb");
    String output=line.getOptionValue("output");
    String basicFields=line.getOptionValue("basicfields");
    createFields(new Path(webGraphDb),new Path(basicFields),new Path(output));
    return 0;
  }
 catch (  Exception e) {
    LOG.fatal("AnchorFields: " + StringUtils.stringifyException(e));
    return -2;
  }
}
 

Example 25

From project ManalithBot, under directory /ManalithBotConsole/src/main/java/org/manalith/ircbot/console/.

Source file: Launcher.java

  21 
vote

public static void main(String[] args) throws Exception {
  Options options=new Options();
  options.addOption("c",true,"config file");
  CommandLineParser parser=new PosixParser();
  CommandLine cmd=parser.parse(options,args);
  String configFile="config.xml";
  String configFileOptionArg=cmd.getOptionValue("c");
  if (StringUtils.isNotBlank(configFileOptionArg)) {
    configFile=configFileOptionArg;
  }
  ApplicationContext context=new FileSystemXmlApplicationContext(configFile);
  UsernamePasswordAuthenticationToken userToken=new UsernamePasswordAuthenticationToken("admin","admin");
  SecurityContextHolder.getContext().setAuthentication(userToken);
  Launcher launcher=context.getBean(Launcher.class);
  ConsoleReader reader=new ConsoleReader();
  String line;
  while (!StringUtils.equals((line=reader.readLine("prompt> ")),"exit")) {
    String[] strs=StringUtils.split(line," ");
    launcher.sendMessage(strs[0],strs[1]);
  }
}
 

Example 26

From project activemq-apollo, under directory /apollo-util/src/main/scala/org/apache/activemq/apollo/util/cli/.

Source file: CommonsCLISupport.java

  19 
vote

/** 
 */
static public String[] setOptions(Object target,CommandLine cli){
  Option[] options=cli.getOptions();
  for (  Option option : options) {
    String name=option.getLongOpt();
    if (name == null)     continue;
    String propName=convertOptionToPropertyName(name);
    String value=option.getValue();
    if (value != null) {
      Class<?> type=IntrospectionSupport.getPropertyType(target,propName);
      if (type.isArray()) {
        IntrospectionSupport.setProperty(target,propName,option.getValues());
      }
 else       if (type.isAssignableFrom(ArrayList.class)) {
        IntrospectionSupport.setProperty(target,propName,new ArrayList(option.getValuesList()));
      }
 else       if (type.isAssignableFrom(HashSet.class)) {
        IntrospectionSupport.setProperty(target,propName,new HashSet(option.getValuesList()));
      }
 else {
        IntrospectionSupport.setProperty(target,propName,value);
      }
    }
 else {
      IntrospectionSupport.setProperty(target,propName,true);
    }
  }
  return cli.getArgs();
}
 

Example 27

From project anarchyape, under directory /src/main/java/ape/.

Source file: Main.java

  19 
vote

/** 
 * This method would parse the array that store all arguments read from StdIn  and return a CommandLine object
 */
public static CommandLine getCommand(String[] args) throws ParseException {
  if (args == null || args.length < 1 || args[0] == null) {
    printHelp();
    return null;
  }
  CommandLineParser parser=new PosixParser();
  return parser.parse(opts,args);
}
 

Example 28

From project GraphWalker, under directory /src/main/java/org/graphwalker/.

Source file: CLI.java

  19 
vote

/** 
 * Run the manual command
 * @param cl
 * @throws StopConditionException
 * @throws GeneratorException
 * @throws InterruptedException
 */
private void RunCommandManual(CommandLine cl) throws StopConditionException, GeneratorException, InterruptedException {
  if (helpNeeded("manual",!cl.hasOption("f"),"Missing the input graphml file (folder), See -f (--input_graphml)") || helpNeeded("manual",!cl.hasOption("s"),"A stop condition must be supplied, See option -s") || helpNeeded("manual",!cl.hasOption("g"),"Missing the generator, See option -g"))   return;
  getMbt().setManualTestSequence(true);
  getMbt().readGraph(cl.getOptionValue("f"));
  getMbt().enableJsScriptEngine(cl.hasOption("j"));
  getMbt().enableExtended(cl.hasOption("x"));
  getMbt().setWeighted(cl.hasOption("w"));
  AlternativeCondition alternativeCondition=new AlternativeCondition();
  String[] stopConditions=cl.getOptionValue("s").split("\\|");
  for (  String stopCondition : stopConditions) {
    String[] sc=stopCondition.trim().split(":");
    alternativeCondition.add(Util.getCondition(null,Keywords.getStopCondition(sc[0].trim()),(sc.length == 1 ? "" : sc[1].trim())));
  }
  String[] generators=cl.getOptionValue("g").split("\\|");
  for (  String genrator : generators) {
    getMbt().setGenerator(Keywords.getGenerator(genrator.trim()));
  }
  getMbt().getGenerator().setStopCondition(alternativeCondition);
  Vector<String[]> testSequence=new Vector<String[]>();
  getMbt().writePath(testSequence);
  new PrintHTMLTestSequence(testSequence,System.out);
}
 

Example 29

From project legacy-maven-support, under directory /maven3-interceptor/src/main/java/org/apache/maven/cli/.

Source file: DefaultMavenExecutionRequestBuilder.java

  19 
vote

static void populateProperties(CommandLine commandLine,Properties systemProperties,Properties userProperties){
  EnvironmentUtils.addEnvVars(systemProperties);
  if (commandLine.hasOption(CLIManager.SET_SYSTEM_PROPERTY)) {
    String[] defStrs=commandLine.getOptionValues(CLIManager.SET_SYSTEM_PROPERTY);
    if (defStrs != null) {
      for (int i=0; i < defStrs.length; ++i) {
        setCliProperty(defStrs[i],userProperties);
      }
    }
  }
  systemProperties.putAll(System.getProperties());
}
 

Example 30

From project Lily, under directory /cr/indexer/admin-cli/src/main/java/org/lilyproject/indexer/admin/cli/.

Source file: GetIndexerConfCli.java

  19 
vote

@Override public int run(CommandLine cmd) throws Exception {
  int result=super.run(cmd);
  if (result != 0)   return result;
  IndexDefinition index=model.getIndex(indexName);
  byte[] conf=index.getConfiguration();
  OutputStream os=getOutput();
  IOUtils.write(conf,os);
  os.close();
  return 0;
}
 

Example 31

From project maven-doxia-tools, under directory /doxia-converter/src/main/java/org/apache/maven/doxia/cli/.

Source file: CLIManager.java

  19 
vote

/** 
 * @param args not null.
 * @return a not null command line.
 * @throws ParseException if any
 * @throws IllegalArgumentException is args is null
 */
CommandLine parse(String[] args) throws ParseException {
  if (args == null) {
    throw new IllegalArgumentException("args is required.");
  }
  String[] cleanArgs=cleanArgs(args);
  CommandLineParser parser=new GnuParser();
  return parser.parse(OPTIONS,cleanArgs);
}