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

The following are top voted examples for showing how to use org.apache.commons.cli.CommandLineParser. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: smaph   File: ServerMain.java   View source code 7 votes vote down vote up
/**
 * Main method.
 * 
 * @param args
 * @throws IOException
 * @throws ParseException
 */
public static void main(String[] args) throws Exception {
	java.util.logging.Logger l = java.util.logging.Logger.getLogger("org.glassfish.grizzly.http.server.HttpHandler");
	l.setLevel(java.util.logging.Level.FINE);
	l.setUseParentHandlers(false);
	java.util.logging.ConsoleHandler ch = new java.util.logging.ConsoleHandler();
	ch.setLevel(java.util.logging.Level.ALL);
	l.addHandler(ch);

	CommandLineParser parser = new GnuParser();
	Options options = new Options();
	options.addOption("h", "host", true, "Server hostname.");
	options.addOption("p", "port", true, "TCP port to listen.");
	options.addOption("s", "storage_path", true, "Storage path.");
	options.addOption("w", "wat_gcube_token", true, "WAT gcube authentication token");
	CommandLine line = parser.parse(options, args);

	String serverUri = String.format("http://%s:%d/smaph", line.getOptionValue("host", "localhost"),
	        Integer.parseInt(line.getOptionValue("port", "8080")));
	Path storage = Paths.get(line.getOptionValue("storage_path"));
	startServer(serverUri, storage, line.getOptionValue("wat_gcube_token"));
}
 
Example 2
Project: doctorkafka   File: URPChecker.java   View source code 7 votes vote down vote up
/**
 *  Usage:  URPChecker  \
 *             -brokerstatszk    datazk001:2181/data07    \
 *             -brokerstatstopic brokerstats              \
 *             -clusterzk  m10nzk001:2181,...,m10nzk007:2181/m10n07
 */
private static CommandLine parseCommandLine(String[] args) {
  Option zookeeper = new Option(ZOOKEEPER, true, "cluster zookeeper");
  options.addOption(zookeeper);

  if (args.length < 2) {
    printUsageAndExit();
  }

  CommandLineParser parser = new DefaultParser();
  CommandLine cmd = null;
  try {
    cmd = parser.parse(options, args);
  } catch (ParseException | NumberFormatException e) {
    printUsageAndExit();
  }
  return cmd;
}
 
Example 3
Project: kubernetes-HDFS   File: PodCIDRToNodeMapping.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws ParseException {
  Options options = new Options();
  Option nameOption = new Option("n", true, "Name to resolve");
  nameOption.setRequired(true);
  options.addOption(nameOption);
  CommandLineParser parser = new BasicParser();
  CommandLine cmd = parser.parse(options, args);

  BasicConfigurator.configure();
  Logger.getRootLogger().setLevel(Level.DEBUG);
  PodCIDRToNodeMapping plugin = new PodCIDRToNodeMapping();
  Configuration conf = new Configuration();
  plugin.setConf(conf);

  String nameToResolve = cmd.getOptionValue(nameOption.getOpt());
  List<String> networkPathDirs = plugin.resolve(Lists.newArrayList(nameToResolve));
  log.info("Resolved " + nameToResolve + " to " + networkPathDirs);
}
 
Example 4
Project: hadoop-oss   File: TestTFileSeqFileComparison.java   View source code 6 votes vote down vote up
public MyOptions(String[] args) {
  seed = System.nanoTime();

  try {
    Options opts = buildOptions();
    CommandLineParser parser = new GnuParser();
    CommandLine line = parser.parse(opts, args, true);
    processOptions(line, opts);
    validateOptions();
  }
  catch (ParseException e) {
    System.out.println(e.getMessage());
    System.out.println("Try \"--help\" option for details.");
    setStopProceed();
  }
}
 
Example 5
Project: pm-home-station   File: Start.java   View source code 6 votes vote down vote up
public static void main(String[] args) {
    CommandLineParser parser = new DefaultParser();
    try {
        Options options = getOptions();
        CommandLine line = parser.parse(options, args );
        if (line.hasOption("help")) {
            HelpFormatter formatter = new HelpFormatter();
            System.out.println(Constants.PROJECT_NAME + ", " + Constants.PROJECT_URL);
            formatter.printHelp(Constants.PROJECT_NAME, options, true);
        } else if (line.hasOption("version")) {
            System.out.println("version: " + Constants.VERSION);
        } else {
            logger.info("Starting pm-home-station ({} v.{})...", Constants.PROJECT_URL, Constants.VERSION);
            setLookAndFeel();
            PlanTowerSensor planTowerSensor = new PlanTowerSensor();
            Station station = new Station(planTowerSensor);
            SwingUtilities.invokeLater(() -> { station.showUI(); });
        }
    } catch (ParseException e) {
        logger.error("Ooops", e);
        return;
    }
}
 
Example 6
Project: doctorkafka   File: BrokerStatsFilter.java   View source code 6 votes vote down vote up
/**
 *  Usage:  BrokerStatsRetriever  \
 *             --brokerstatszk    datazk001:2181/data07    \
 *             --brokerstatstopic brokerstats              \
 *             --broker  kafkabroker001
 */
private static CommandLine parseCommandLine(String[] args) {
  Option config = new Option(CONFIG, true, "operator config");
  Option brokerStatsZookeeper =
      new Option(BROKERSTATS_ZOOKEEPER, true, "zookeeper for brokerstats topic");
  Option brokerStatsTopic = new Option(BROKERSTATS_TOPIC, true, "topic for brokerstats");
  Option broker = new Option(BROKERNAME, true, "broker name");
  options.addOption(config).addOption(brokerStatsZookeeper).addOption(brokerStatsTopic)
      .addOption(broker);

  if (args.length < 6) {
    printUsageAndExit();
  }

  CommandLineParser parser = new DefaultParser();
  CommandLine cmd = null;
  try {
    cmd = parser.parse(options, args);
  } catch (ParseException | NumberFormatException e) {
    printUsageAndExit();
  }
  return cmd;
}
 
Example 7
Project: kickoff   File: Cli.java   View source code 6 votes vote down vote up
public void parse() {
    CommandLineParser parser = new BasicParser();

    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args, true);

        if (cmd.hasOption("h")) {
            help();
        } else if (cmd.hasOption("o")) {
            open();
        } else if (!cmd.hasOption("g")) {
            log.log(Level.SEVERE, "Missing g option");
            help();
        }

    } catch (ParseException e) {
        help();
    }
}
 
Example 8
Project: doctorkafka   File: DoctorKafkaActionRetriever.java   View source code 6 votes vote down vote up
/**
 *  Usage:  OperatorActionRetriever                         \
 *             -zookeeper    datazk001:2181/data07          \
 *             -topic  operator_report  -num_messages 1000
 */
private static CommandLine parseCommandLine(String[] args) {
  Option zookeeper = new Option(ZOOKEEPER, true, "doctorkafka action zookeeper");
  Option topic = new Option(TOPIC, true, "doctorkafka action topic");
  Option num_messages = new Option(NUM_MESSAGES, true, "num of messages to retrieve");
  options.addOption(zookeeper).addOption(topic).addOption(num_messages);

  if (args.length < 2) {
    printUsageAndExit();
  }

  CommandLineParser parser = new DefaultParser();
  CommandLine cmd = null;
  try {
    cmd = parser.parse(options, args);
  } catch (ParseException | NumberFormatException e) {
    printUsageAndExit();
  }
  return cmd;
}
 
Example 9
Project: doctorkafka   File: MetricsFetcher.java   View source code 6 votes vote down vote up
private static CommandLine parseCommandLine(String[] args) {

    Option host = new Option(BROKER_NAME, true, "kafka broker");
    Option jmxPort = new Option(JMX_PORT, true, "kafka jmx port number");
    jmxPort.setArgName("kafka jmx port number");

    Option metric = new Option(METRICS_NAME, true, "jmx metric name");

    options.addOption(jmxPort).addOption(host).addOption(metric);

    if (args.length < 4) {
      printUsageAndExit();
    }
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;
    try {
      cmd = parser.parse(options, args);
    } catch (ParseException | NumberFormatException e) {
      printUsageAndExit();
    }
    return cmd;
  }
 
Example 10
Project: cyberduck   File: CommandLineUriParserTest.java   View source code 6 votes vote down vote up
@Test
public void testParse() throws Exception {
    final CommandLineParser parser = new PosixParser();
    final CommandLine input = parser.parse(new Options(), new String[]{});

    final ProtocolFactory factory = new ProtocolFactory(new HashSet<>(Arrays.asList(new FTPTLSProtocol() {
        @Override
        public boolean isEnabled() {
            return true;
        }
    }, new S3Protocol() {
        @Override
        public boolean isEnabled() {
            return true;
        }
    })));
    assertTrue(new Host(new S3Protocol(), "s3.amazonaws.com", 443, "/cyberduck-test/key", new Credentials("AWS456", null))
            .compareTo(new CommandLineUriParser(input, factory).parse("s3://[email protected]/key")) == 0);
    assertTrue(new Host(new FTPTLSProtocol(), "cyberduck.io", 55, "/folder", new Credentials("anonymous", null))
            .compareTo(new CommandLineUriParser(input, factory).parse("ftps://cyberduck.io:55/folder")) == 0);
}
 
Example 11
Project: cyberduck   File: CommandLineUriParserTest.java   View source code 6 votes vote down vote up
@Test
public void testProfile() throws Exception {
    final CommandLineParser parser = new PosixParser();
    final CommandLine input = parser.parse(new Options(), new String[]{});
    final Set<Protocol> list = new HashSet<>(Arrays.asList(
            new SwiftProtocol(),
            new ProfilePlistReader(new ProtocolFactory(Collections.singleton(new SwiftProtocol() {
                @Override
                public boolean isEnabled() {
                    return true;
                }
            })))
                    .read(new Local("../profiles/default/Rackspace US.cyberduckprofile"))
    ));
    assertTrue(new Host(new ProtocolFactory(list).forName("rackspace"), "identity.api.rackspacecloud.com", 443, "/cdn.cyberduck.ch/", new Credentials("u", null))
            .compareTo(new CommandLineUriParser(input, new ProtocolFactory(list)).parse("rackspace://[email protected]/")) == 0);

}
 
Example 12
Project: cyberduck   File: TerminalTransferFactoryTest.java   View source code 6 votes vote down vote up
@Test
public void testFilter() throws Exception {
    final CommandLineParser parser = new PosixParser();

    final Transfer transfer = new TerminalTransferFactory().create(parser.parse(TerminalOptionsBuilder.options(), new String[]{"--download", "rackspace://cdn.cyberduck.ch/remote/*.css"}),
            new Host(new SwiftProtocol()), new Path("/remote/*.css", EnumSet.of(Path.Type.directory)), Collections.<TransferItem>emptyList());
    assertEquals(Transfer.Type.download, transfer.getType());
    final PathCache cache = new PathCache(1);
    transfer.withCache(cache);
    cache.clear();
    cache.put(new Path("/remote", EnumSet.of(Path.Type.directory)), new AttributedList<Path>(Collections.singletonList(new Path("/remote/file.css", EnumSet.of(Path.Type.file)))));
    assertFalse(transfer.list(null, null, new Path("/remote", EnumSet.of(Path.Type.directory)), new Local("/tmp"), new DisabledListProgressListener()).isEmpty());
    cache.clear();
    cache.put(new Path("/remote", EnumSet.of(Path.Type.directory)), new AttributedList<Path>(Collections.singletonList(new Path("/remote/file.png", EnumSet.of(Path.Type.file)))));
    assertTrue(transfer.list(null, null, new Path("/remote", EnumSet.of(Path.Type.directory)), new Local("/tmp"), new DisabledListProgressListener()).isEmpty());
}
 
Example 13
Project: cyberduck   File: CommandLinePathParserTest.java   View source code 6 votes vote down vote up
@Test
public void testParseProfile() throws Exception {
    final ProtocolFactory factory = new ProtocolFactory(new HashSet<>(Collections.singleton(new SwiftProtocol() {
        @Override
        public boolean isEnabled() {
            return true;
        }
    })));
    final ProfilePlistReader reader = new ProfilePlistReader(factory, new DeserializerFactory(PlistDeserializer.class.getName()));
    final Profile profile = reader.read(
            new Local("../profiles/default/Rackspace US.cyberduckprofile")
    );
    assertNotNull(profile);

    final CommandLineParser parser = new PosixParser();
    final CommandLine input = parser.parse(new Options(), new String[]{});

    assertEquals(new Path("/cdn.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume)),
            new CommandLinePathParser(input, new ProtocolFactory(new HashSet<>(Arrays.asList(new SwiftProtocol(), profile)))).parse("rackspace://[email protected]/"));
    assertEquals(new Path("/", EnumSet.of(Path.Type.directory, Path.Type.volume)),
            new CommandLinePathParser(input, new ProtocolFactory(new HashSet<>(Arrays.asList(new SwiftProtocol(), profile)))).parse("rackspace:///"));
}
 
Example 14
Project: java-cli-demos   File: MainWithBuilder.java   View source code 6 votes vote down vote up
/**
 * "Parsing" stage of command-line processing demonstrated with
 * Apache Commons CLI.
 *
 * @param options Options from "definition" stage.
 * @param commandLineArguments Command-line arguments provided to application.
 * @return Instance of CommandLine as parsed from the provided Options and
 *    command line arguments; may be {@code null} if there is an exception
 *    encountered while attempting to parse the command line options.
 */
private static CommandLine generateCommandLine(
   final Options options, final String[] commandLineArguments)
{
   final CommandLineParser cmdLineParser = new DefaultParser();
   CommandLine commandLine = null;
   try
   {
      commandLine = cmdLineParser.parse(options, commandLineArguments);
   }
   catch (ParseException parseException)
   {
      out.println(
           "ERROR: Unable to parse command-line arguments "
         + Arrays.toString(commandLineArguments) + " due to: "
         + parseException);
   }
   return commandLine;
}
 
Example 15
Project: doctorkafka   File: DoctorKafkaActionWriter.java   View source code 6 votes vote down vote up
/**
 *  Usage:  KafkaWriter  \
 *             --zookeeper zookeeper001:2181/cluster1 --topic kafka_test    \
 *             --message "this is a test message"
 */
private static CommandLine parseCommandLine(String[] args) {
  Option zookeeper = new Option(ZOOKEEPER, true, "zookeeper connection string");
  Option topic = new Option(TOPIC, true, "action report topic name");
  Option message = new Option(MESSAGE, true, "messags that writes to kafka");
  options.addOption(zookeeper).addOption(topic).addOption(message);

  if (args.length < 6) {
    printUsageAndExit();
  }

  CommandLineParser parser = new DefaultParser();
  CommandLine cmd = null;
  try {
    cmd = parser.parse(options, args);
  } catch (ParseException | NumberFormatException e) {
    printUsageAndExit();
  }
  return cmd;
}
 
Example 16
Project: doctorkafka   File: DoctorKafkaMain.java   View source code 6 votes vote down vote up
/**
 *  Usage:  DoctorKafkaMain  --zookeeper datazk001:2181/data07 \
 *             --topic brokerstats kafkahost  \
 *             --tsdhost  localhost:18321  --ostrichport 2051
 *             --uptimeinseconds 43200
 */
private static CommandLine parseCommandLine(String[] args) {
  Option configPath = new Option(CONFIG_PATH, true, "config file path");
  Option zookeeper = new Option(ZOOKEEPER, true, "zk url for metrics topic");
  zookeeper.setRequired(false);
  Option topic = new Option(METRICS_TOPIC, true, "kafka topic for metric messages");
  topic.setRequired(false);
  Option tsdHostPort = new Option(TSD_HOSTPORT, true, "tsd host and port, e.g. localhost:18621");
  tsdHostPort.setRequired(false);
  Option ostrichPort = new Option(OSTRICH_PORT, true, "ostrich port");
  ostrichPort.setRequired(false);
  Option uptimeInSeconds = new Option(UPTIME_IN_SECONDS, true, "uptime in seconds");
  uptimeInSeconds.setRequired(false);

  options.addOption(configPath).addOption(zookeeper).addOption(topic)
      .addOption(tsdHostPort).addOption(ostrichPort).addOption(uptimeInSeconds);

  if (args.length < 1) {
    printUsageAndExit();
  }
  CommandLineParser parser = new DefaultParser();
  CommandLine cmd = null;
  try {
    cmd = parser.parse(options, args);
  } catch (ParseException | NumberFormatException e) {
    printUsageAndExit();
  }
  return cmd;
}
 
Example 17
Project: hadoop-logfile-inputformat   File: Sample.java   View source code 6 votes vote down vote up
private static boolean parseArguments(String[] args) {
    CommandLineParser parser = new BasicParser();
    try {
        CommandLine commandLine = parser.parse(OPTIONS, args);

        inputPath = commandLine.getOptionValue(INPUT_PATH.getOpt());
        outputPath = new Path(commandLine.getOptionValue(OUTPUT_PATH.getOpt()));
        pattern = Pattern.compile(commandLine.getOptionValue(PATTERN.getOpt()));
        if (commandLine.hasOption(SAMPLE_FRACTION.getOpt())) {
            sampleFraction = Double.valueOf(commandLine.getOptionValue(SAMPLE_FRACTION.getOpt()));
        }

        if (sampleFraction < 0 || sampleFraction > 1) {
            return false;
        }

        return true;
    } catch (ParseException | IllegalArgumentException e) {
        return false;
    }
}
 
Example 18
Project: rmq4note   File: ServerUtil.java   View source code 6 votes vote down vote up
public static CommandLine parseCmdLine(final String appName, String[] args, Options options,
    CommandLineParser parser) {
    HelpFormatter hf = new HelpFormatter();
    hf.setWidth(110);
    CommandLine commandLine = null;
    try {
        commandLine = parser.parse(options, args);
        if (commandLine.hasOption('h')) {
            hf.printHelp(appName, options, true);
            return null;
        }
    } catch (ParseException e) {
        hf.printHelp(appName, options, true);
    }

    return commandLine;
}
 
Example 19
Project: BiglyBT   File: OptionsConsoleCommand.java   View source code 6 votes vote down vote up
/**
	 * take the args and try and create a command line object
	 */
	@Override
	public void execute(String commandName, ConsoleInput console, List arguments) {
		CommandLineParser parser = getParser();

		try
		{
			String []args = new String[arguments.size()];
			int i = 0;
			for (Iterator iter = arguments.iterator(); iter.hasNext();) {
				String arg = (String) iter.next();
				args[i++] = arg;
			}
			CommandLine line = parser.parse(getOptions(), args);
			execute( commandName, console, line );
		} catch (ParseException e)
		{
			console.out.println(">> Invalid arguments: " + e.getMessage());
//			printHelp(commandName, console.out);
			printHelp(console.out, arguments);
		}
	}
 
Example 20
Project: doctorkafka   File: KafkaWriter.java   View source code 6 votes vote down vote up
/**
 *  Usage:  KafkaWriter  \
 *             --zookeeper datazk001:2181/testk10 --topic kafka_test    \
 *             --num_messages 100
 */
private static CommandLine parseCommandLine(String[] args) {
  Option zookeeper = new Option(ZOOKEEPER, true, "zookeeper connection string");
  Option topic = new Option(TOPIC, true, "topic that KafkaWriter writes to");
  Option num_messages = new Option(NUM_MESSAGES, true, "num of messags that writes to kafka");
  options.addOption(zookeeper).addOption(topic).addOption(num_messages);

  if (args.length < 6) {
    printUsageAndExit();
  }

  CommandLineParser parser = new DefaultParser();
  CommandLine cmd = null;
  try {
    cmd = parser.parse(options, args);
  } catch (ParseException | NumberFormatException e) {
    printUsageAndExit();
  }
  return cmd;
}
 
Example 21
Project: hadoop   File: DFSUtil.java   View source code 6 votes vote down vote up
/**
 * 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 22
Project: doctorkafka   File: ReplicaStatsRetriever.java   View source code 6 votes vote down vote up
/**
 *  Usage:  ReplicaStatsRetriever  \
 *             -brokerstatszk    datazk001:2181/data07    \
 *             -brokerstatstopic brokerstats              \
 *             -clusterzk  m10nzk001:2181,...,m10nzk007:2181/m10n07 \
 *             -seconds 43200
 */
private static CommandLine parseCommandLine(String[] args) {
  Option config = new Option(CONFIG, true, "operator config");
  Option brokerStatsZookeeper =
      new Option(BROKERSTATS_ZOOKEEPER, true, "zookeeper for brokerstats topic");
  Option brokerStatsTopic = new Option(BROKERSTATS_TOPIC, true, "topic for brokerstats");
  Option clusterZookeeper = new Option(CLUSTER_ZOOKEEPER, true, "cluster zookeeper");
  Option seconds = new Option(SECONDS, true, "examined time window in seconds");
  options.addOption(config).addOption(brokerStatsZookeeper).addOption(brokerStatsTopic)
      .addOption(clusterZookeeper).addOption(seconds);

  if (args.length < 6) {
    printUsageAndExit();
  }

  CommandLineParser parser = new DefaultParser();
  CommandLine cmd = null;
  try {
    cmd = parser.parse(options, args);
  } catch (ParseException | NumberFormatException e) {
    printUsageAndExit();
  }
  return cmd;
}
 
Example 23
Project: doctorkafka   File: BrokerStatsReader.java   View source code 6 votes vote down vote up
private static CommandLine parseCommandLine(String[] args) {
  if (args.length < 4) {
    printUsageAndExit();
  }

  Option zookeeper = new Option(ZOOKEEPER, true, "zookeeper connection string");
  Option statsTopic = new Option(STATS_TOPIC, true, "kafka topic for broker stats");
  options.addOption(zookeeper).addOption(statsTopic);

  CommandLineParser parser = new DefaultParser();
  CommandLine cmd = null;
  try {
    cmd = parser.parse(options, args);
  } catch (ParseException | NumberFormatException e) {
    printUsageAndExit();
  }
  return cmd;
}
 
Example 24
Project: hadoop   File: TestTFileSeqFileComparison.java   View source code 6 votes vote down vote up
public MyOptions(String[] args) {
  seed = System.nanoTime();

  try {
    Options opts = buildOptions();
    CommandLineParser parser = new GnuParser();
    CommandLine line = parser.parse(opts, args, true);
    processOptions(line, opts);
    validateOptions();
  }
  catch (ParseException e) {
    System.out.println(e.getMessage());
    System.out.println("Try \"--help\" option for details.");
    setStopProceed();
  }
}
 
Example 25
Project: ditb   File: HFileV1Detector.java   View source code 5 votes vote down vote up
private boolean parseOption(String[] args) throws ParseException, IOException {
  if (args.length == 0) {
    return true; // no args will process with default values.
  }
  CommandLineParser parser = new GnuParser();
  CommandLine cmd = parser.parse(options, args);
  if (cmd.hasOption("h")) {
    HelpFormatter formatter = new HelpFormatter();
    formatter.printHelp("HFileV1Detector", options, true);
    System.out
        .println("In case no option is provided, it processes hbase.rootdir using 10 threads.");
    System.out.println("Example:");
    System.out.println(" To detect any HFileV1 in a given hbase installation '/myhbase':");
    System.out.println(" $ $HBASE_HOME/bin/hbase " + this.getClass().getName() + " -p /myhbase");
    System.out.println();
    return false;
  }

  if (cmd.hasOption("p")) {
    this.targetDirPath = new Path(FSUtils.getRootDir(getConf()), cmd.getOptionValue("p"));
  }
  try {
    if (cmd.hasOption("n")) {
      int n = Integer.parseInt(cmd.getOptionValue("n"));
      if (n < 0 || n > 100) {
        LOG.warn("Please use a positive number <= 100 for number of threads."
            + " Continuing with default value " + DEFAULT_NUM_OF_THREADS);
        return true;
      }
      this.numOfThreads = n;
    }
  } catch (NumberFormatException nfe) {
    LOG.error("Please select a valid number for threads");
    return false;
  }
  return true;
}
 
Example 26
Project: ditb   File: ThriftServer.java   View source code 5 votes vote down vote up
private static CommandLine parseArguments(Configuration conf, Options options, String[] args)
    throws ParseException, IOException {
  GenericOptionsParser genParser = new GenericOptionsParser(conf, args);
  String[] remainingArgs = genParser.getRemainingArgs();
  CommandLineParser parser = new PosixParser();
  return parser.parse(options, remainingArgs);
}
 
Example 27
Project: hadoop-oss   File: GenericOptionsParser.java   View source code 5 votes vote down vote up
/**
 * Parse the user-specified options, get the generic options, and modify
 * configuration accordingly
 * @param opts Options to use for parsing args.
 * @param conf Configuration to be modified
 * @param args User-specified arguments
 */
private void parseGeneralOptions(Options opts, Configuration conf, 
    String[] args) throws IOException {
  opts = buildGeneralOptions(opts);
  CommandLineParser parser = new GnuParser();
  try {
    commandLine = parser.parse(opts, preProcessForWindows(args), true);
    processGeneralOptions(conf, commandLine);
  } catch(ParseException e) {
    LOG.warn("options parsing failed: "+e.getMessage());

    HelpFormatter formatter = new HelpFormatter();
    formatter.printHelp("general options are: ", opts);
  }
}
 
Example 28
Project: hadoop-oss   File: RPCCallBenchmark.java   View source code 5 votes vote down vote up
private MyOptions(String args[]) {
  try {
    Options opts = buildOptions();
    CommandLineParser parser = new GnuParser();
    CommandLine line = parser.parse(opts, args, true);
    processOptions(line, opts);
    validateOptions();
  } catch (ParseException e) {
    System.err.println(e.getMessage());
    System.err.println("Try \"--help\" option for details.");
    failed = true;
  }
}
 
Example 29
Project: TRADFRI2MQTT   File: Main.java   View source code 5 votes vote down vote up
/**
 * @param args Command line arguments
 * @throws InterruptedException
 */
public static void main(String[] args) throws InterruptedException {
	Options options = new Options();
	options.addOption("psk", true, "The Secret on the base of the gateway");
	options.addOption("ip", true, "The IP address of the gateway");
	options.addOption("broker", true, "MQTT URL");
	options.addOption("retained", "Topics are retained");
	options.addOption("help", "Shows this usage information");

	CommandLineParser parser = new DefaultParser();
	CommandLine cmd = null;
	try {
		cmd = parser.parse(options, args);
	} catch (ParseException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

	String psk = cmd.getOptionValue("psk");
	String ip = cmd.getOptionValue("ip");
	String broker = cmd.getOptionValue("broker");
	boolean retained = cmd.hasOption("retained");
	boolean help = cmd.hasOption("help");

	if (help || psk == null || ip == null || broker == null) {
		HelpFormatter formatter = new HelpFormatter();
		formatter.printHelp("TRADFRI2MQTT", options);
		System.exit(1);
	}

	Main m = new Main(psk, ip, broker, retained);
	m.discover();
}
 
Example 30
Project: spydra   File: CliHelper.java   View source code 5 votes vote down vote up
public static CommandLine tryParse(CommandLineParser parser, Options options,
    String[] args) {

  try {
    return parser.parse(options, args);
  } catch (MissingOptionException moe) {
    logger.error("Required options missing: " + Joiner.on(',').join(moe.getMissingOptions()));
    throw new CliParser.ParsingException(moe);
  } catch (ParseException e) {
    logger.error("Failed parsing options", e);
    throw new CliParser.ParsingException(e);
  }
}
 
Example 31
Project: ditb   File: UpgradeTo96.java   View source code 5 votes vote down vote up
private boolean parseOption(String[] args) throws ParseException {
  if (args.length == 0) return false; // no args shows help.

  CommandLineParser parser = new GnuParser();
  CommandLine cmd = parser.parse(options, args);
  if (cmd.hasOption("h")) {
    return false;
  }
  if (cmd.hasOption("execute")) upgrade = true;
  if (cmd.hasOption("check")) checkForHFileV1 = true;
  if (checkForHFileV1 && cmd.hasOption("dir")) {
    this.dirToCheckForHFileV1 = cmd.getOptionValue("dir");
  }
  return true;
}
 
Example 32
Project: scijava-jupyter-kernel   File: DefaultJupyterService.java   View source code 5 votes vote down vote up
private Map<String, Object> parseArgumentsRun(final String... args) {
    if (args.length > 0) {
        try {

            Options options = new Options();
            options.addOption("connectionFile", true, "Connection File Path");
            options.addOption("verbose", true, "Verbose Mode");

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

            Map<String, Object> parameters = new HashMap<>();

            parameters.put("connectionFile", cmd.getOptionValue("connectionFile"));
            parameters.put("logLevel", cmd.getOptionValue("verbose"));

            return parameters;

        } catch (ParseException ex) {
            log.error("Error parsing arguments : " + ex.toString());
        }
    } else {
        log.error("No parameters passed to the Scijava kernel.");
    }
    return null;
}
 
Example 33
Project: samza-sql-tools   File: EventHubConsoleConsumer.java   View source code 5 votes vote down vote up
public static void main(String[] args)
    throws ServiceBusException, 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);
}
 
Example 34
Project: stl-decomp-4j   File: StlPerfTest.java   View source code 5 votes vote down vote up
private static void parseCommandLine(String[] args) {
	Options options = new Options();

	Option input = new Option("n", "timed-iterations", true, "number of iterations of timing loop");
	input.setRequired(false);
	options.addOption(input);

	Option output = new Option("w", "warmup-iterations", true, "number of warm-up iterations before timing loop");
	output.setRequired(false);
	options.addOption(output);

	Option hourly = new Option("h", "hourly", false, "whether to use hourly data");
	hourly.setRequired(false);
	options.addOption(hourly);

	CommandLineParser parser = new DefaultParser();
	HelpFormatter formatter = new HelpFormatter();
	CommandLine cmd;

	try {
		cmd = parser.parse(options, args);
	} catch (ParseException e) {
		System.out.println(e.getMessage());
		formatter.printHelp("StlPerfTest", options);

		System.exit(1);
		return;
	}

	if (cmd.hasOption("hourly")) {
		System.out.println("Running hourly stress test");
		fRunCo2 = false;
		fTimedIterations = 200;
		fWarmupIterations = 30;
	} else {
		System.out.println("Running CO2 test");
		fTimedIterations = 2000;
		fWarmupIterations = 30;
	}

	String nStr = cmd.getOptionValue("number");
	if (nStr != null)
		fTimedIterations = Integer.parseInt(nStr);

	String wStr = cmd.getOptionValue("warmup-iterations");
	if (wStr != null)
		fWarmupIterations = Integer.parseInt(wStr);

}
 
Example 35
Project: hbs_decipher   File: QNAPFileDecrypter.java   View source code 5 votes vote down vote up
/**
 * Apply Apache Commons CLI PosixParser to command-line arguments.
 * 
 * @param commandLineArguments
 *            Command-line arguments to be processed with Posix-style parser.
 */
private static CommandLine usePosixParser(final String[] commandLineArguments) {
	final CommandLineParser cmdLinePosixParser = new DefaultParser();
	final Options posixOptions = constructPosixOptions();
	try {
		return cmdLinePosixParser.parse(posixOptions, commandLineArguments);
	} catch (ParseException parseException) {
		System.err
				.println("Encountered exception while parsing using PosixParser:\n" + parseException.getMessage());
	}
	return null;
}
 
Example 36
Project: WebPLP   File: AssembleConsole.java   View source code 5 votes vote down vote up
private static void parseCLIArguments(String[] args)
{
	CommandLineParser parser = new DefaultParser();
	
	try
	{
		commandLine = parser.parse(options, args);
	}
	catch (ParseException e)
	{
		e.printStackTrace();
		System.exit(-1);
	}
}
 
Example 37
Project: kickoff   File: Cli.java   View source code 5 votes vote down vote up
public CommandLine getOptions() {
    CommandLineParser parser = new BasicParser();
    try {
        return parser.parse(options, args, true);
    } catch (ParseException e) {
        help();
        return null;
    }

}
 
Example 38
Project: cyberduck   File: DeletePathFinderTest.java   View source code 5 votes vote down vote up
@Test
public void testFindFile() throws Exception {
    final CommandLineParser parser = new PosixParser();
    final CommandLine input = parser.parse(TerminalOptionsBuilder.options(), new String[]{"--delete", "rackspace://cdn.cyberduck.ch/remote"});

    assertTrue(new DeletePathFinder().find(input, TerminalAction.delete, new Path("/remote", EnumSet.of(Path.Type.file))).contains(
            new TransferItem(new Path("/remote", EnumSet.of(Path.Type.file)))
    ));
}
 
Example 39
Project: cyberduck   File: CommandLineUriParserTest.java   View source code 5 votes vote down vote up
@Test
public void testScheme() throws Exception {
    final CommandLineParser parser = new PosixParser();
    final CommandLine input = parser.parse(new Options(), new String[]{});

    final ProtocolFactory factory = new ProtocolFactory(new HashSet<>(Arrays.asList(
            new AzureProtocol(),
            new DAVSSLProtocol()
    )));
    factory.register(new ProfilePlistReader(factory).read(LocalFactory.get("../profiles/default/Azure.cyberduckprofile")));
    factory.register(new ProfilePlistReader(factory).read(LocalFactory.get("../profiles/default/DAVS.cyberduckprofile")));
    assertTrue(new Host(new DAVSSLProtocol(), "ftp.gnu.org", 443, "/gnu/wget/wget-1.19.1.tar.gz", new Credentials("anonymous", null))
            .compareTo(new CommandLineUriParser(input, factory).parse("https://ftp.gnu.org/gnu/wget/wget-1.19.1.tar.gz")) == 0);
}
 
Example 40
Project: cyberduck   File: TerminalTransferFactoryTest.java   View source code 5 votes vote down vote up
@Test
public void testCreate() throws Exception {
    final CommandLineParser parser = new PosixParser();

    final Transfer transfer = new TerminalTransferFactory().create(parser.parse(TerminalOptionsBuilder.options(), new String[]{"--download", "rackspace://cdn.cyberduck.ch/remote"}),
            new Host(new SwiftProtocol()), new Path("/remote", EnumSet.of(Path.Type.directory)), Collections.<TransferItem>emptyList());
    assertEquals(Transfer.Type.download, transfer.getType());
}