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

The following are top voted examples for showing how to use org.apache.commons.cli.CommandLine. 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: doctorkafka   File: URPChecker.java   Source Code and License 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 2
Project: 484_P7_1-Java   File: CommandLineApp.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) {
    CommandLineParser parser = new DefaultParser();
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(buildOptions(), args);

        if (line.hasOption('h')) {
            printHelp();
            System.exit(0);
        }

        if (line.hasOption('v')) {
            System.out.println(VERSION_STRING);
            System.exit(0);
        }

        new CommandLineApp(System.out, line).extractTables(line);
    } catch (ParseException exp) {
        System.err.println("Error: " + exp.getMessage());
        System.exit(1);
    }
    System.exit(0);
}
 
Example 3
Project: ditb   File: IntegrationTestLoadAndVerify.java   Source Code and License 6 votes vote down vote up
@Override
protected void processOptions(CommandLine cmd) {
  super.processOptions(cmd);

  String[] args = cmd.getArgs();
  if (args == null || args.length < 1) {
    usage();
    throw new RuntimeException("Incorrect Number of args.");
  }
  toRun = args[0];
  if (toRun.equalsIgnoreCase("search")) {
    if (args.length > 1) {
      keysDir = args[1];
    }
  }
}
 
Example 4
Project: https-github.com-apache-zookeeper   File: SyncCommand.java   Source Code and License 6 votes vote down vote up
@Override
public CliCommand parse(String[] cmdArgs) throws CliParseException {
    Parser parser = new PosixParser();
    CommandLine cl;
    try {
        cl = parser.parse(options, cmdArgs);
    } catch (ParseException ex) {
        throw new CliParseException(ex);
    }
    args = cl.getArgs();
    if (args.length < 2) {
        throw new CliParseException(getUsageStr());
    }

    return this;
}
 
Example 5
Project: rocketmq-rocketmq-all-4.1.0-incubating   File: UpdateTopicSubCommandTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testExecute() {
    UpdateTopicSubCommand cmd = new UpdateTopicSubCommand();
    Options options = ServerUtil.buildCommandlineOptions(new Options());
    String[] subargs = new String[] {
        "-b 127.0.0.1:10911",
        "-c default-cluster",
        "-t unit-test",
        "-r 8",
        "-w 8",
        "-p 6",
        "-o false",
        "-u false",
        "-s false"};
    final CommandLine commandLine =
        ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser());
    assertThat(commandLine.getOptionValue('b').trim()).isEqualTo("127.0.0.1:10911");
    assertThat(commandLine.getOptionValue('c').trim()).isEqualTo("default-cluster");
    assertThat(commandLine.getOptionValue('r').trim()).isEqualTo("8");
    assertThat(commandLine.getOptionValue('w').trim()).isEqualTo("8");
    assertThat(commandLine.getOptionValue('t').trim()).isEqualTo("unit-test");
    assertThat(commandLine.getOptionValue('p').trim()).isEqualTo("6");
    assertThat(commandLine.getOptionValue('o').trim()).isEqualTo("false");
    assertThat(commandLine.getOptionValue('u').trim()).isEqualTo("false");
    assertThat(commandLine.getOptionValue('s').trim()).isEqualTo("false");
}
 
Example 6
Project: java-cli-demos   File: MainWithBuilder.java   Source Code and License 6 votes vote down vote up
/**
 * Executable function to demonstrate Apache Commons CLI
 * parsing of command-line arguments.
 *
 * @param arguments Command-line arguments to be parsed.
 */
public static void main(final String[] arguments)
{
   final Options options = generateOptions();

   if (arguments.length < 1)
   {
      printUsage(options);
      printHelp(options);
      System.exit(-1);
   }

   final CommandLine commandLine = generateCommandLine(options, arguments);

   // "interrogation" stage of processing with Apache Commons CLI
   if (commandLine != null)
   {
      final boolean verbose =
         commandLine.hasOption(VERBOSE_OPTION);
      final String fileName =
         commandLine.getOptionValue(FILE_OPTION);
      out.println("The file '" + fileName + "' was provided and verbosity is set to '" + verbose + "'.");
   }
}
 
Example 7
Project: rmq4note   File: SendMsgStatusCommand.java   Source Code and License 6 votes vote down vote up
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) {
    final DefaultMQProducer producer = new DefaultMQProducer("PID_SMSC", rpcHook);
    producer.setInstanceName("PID_SMSC_" + System.currentTimeMillis());

    try {
        producer.start();
        String brokerName = commandLine.getOptionValue('b').trim();
        int messageSize = commandLine.hasOption('s') ? Integer.parseInt(commandLine.getOptionValue('s')) : 128;
        int count = commandLine.hasOption('c') ? Integer.parseInt(commandLine.getOptionValue('c')) : 50;

        producer.send(buildMessage(brokerName, 16));

        for (int i = 0; i < count; i++) {
            long begin = System.currentTimeMillis();
            SendResult result = producer.send(buildMessage(brokerName, messageSize));
            System.out.printf("rt:" + (System.currentTimeMillis() - begin) + "ms, SendResult=" + result);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        producer.shutdown();
    }
}
 
Example 8
Project: DemoUi   File: DemoUiCommandLineParser.java   Source Code and License 6 votes vote down vote up
static DemoUiState parse(CommandLine line) {

        // if we have `help`, then no need to evaluate configuration
        final DemoUiState state = new DemoUiState();

        state.showHelp(help(line));

        state.live(live(line));
        state.demoMode(demo(line));
        state.configuration(configuration(line));

        state.adb(adb(line));
        state.demoMode(demo(line));
        state.demoGlobalSettingEnabled(demoEnabled(line));
        state.loadConfiguration(loadConfiguration(line));
        state.saveConfiguration(saveConfiguration(line));

        state.debug(debug(line));
        state.screenshot(screenshot(line));

        return state;
    }
 
Example 9
Project: BNPMix.java   File: MixtureOptionPack.java   Source Code and License 6 votes vote down vote up
@Override
public MixtureOptionPack extract(CommandLine cmdline) throws AlreadySelectedException {
  NumEmptyClusters = Integer.parseInt(cmdline.getOptionValue("NumEmptyClusters", defaultNumEmptyClusters));
  if (cmdline.hasOption("Reuse")) {
    alg.setSelected(reuse);
  } else if (cmdline.hasOption("Neal8")) {
    alg.setSelected(neal8);
  } else if (cmdline.hasOption("Slice")) {
    alg.setSelected(slice);
  } else {
    throw new Error("mixture algorithm option not set");
  }
  if (cmdline.hasOption("Marginalized")) {
    marg.setSelected(marginalized);
  } else if (cmdline.hasOption("Sampled")) {
    marg.setSelected(sampled);
  }
  
  //MaxEmptyClusters = Integer.parseInt(cmdline.getOptionValue("MaxEmptyClusters", defaultMaxEmptyClusters));
  return this;
}
 
Example 10
Project: devops-cm-client   File: ReleaseTransport.java   Source Code and License 6 votes vote down vote up
public final static void main(String[] args) throws Exception {
    logger.debug(format("%s called with arguments: '%s'.", ReleaseTransport.class.getSimpleName(), Commands.Helpers.getArgsLogString(args)));
    Options options = new Options();
    Commands.Helpers.addStandardParameters(options);

    if(helpRequested(args)) {
        handleHelpOption(
            format("%s <changeId> <transportId>", getCommandName(ReleaseTransport.class)),
            "Releases the transport specified by <changeId>, <transportId>.", new Options()); return;
    }

    CommandLine commandLine = new DefaultParser().parse(options, args);

    new ReleaseTransport(getHost(commandLine),
            getUser(commandLine),
            getPassword(commandLine),
            getChangeId(commandLine),
            TransportRelated.getTransportId(commandLine)).execute();
}
 
Example 11
Project: ditb   File: ThriftServerRunner.java   Source Code and License 6 votes vote down vote up
static void setServerImpl(CommandLine cmd, Configuration conf) {
  ImplType chosenType = null;
  int numChosen = 0;
  for (ImplType t : values()) {
    if (cmd.hasOption(t.option)) {
      chosenType = t;
      ++numChosen;
    }
  }
  if (numChosen < 1) {
    LOG.info("Using default thrift server type");
    chosenType = DEFAULT;
  } else if (numChosen > 1) {
    throw new AssertionError("Exactly one option out of " +
      Arrays.toString(values()) + " has to be specified");
  }
  LOG.info("Using thrift server type " + chosenType.option);
  conf.set(SERVER_TYPE_CONF_KEY, chosenType.option);
}
 
Example 12
Project: hadoop-oss   File: HAAdmin.java   Source Code and License 6 votes vote down vote up
private int transitionToActive(final CommandLine cmd)
    throws IOException, ServiceFailedException {
  String[] argv = cmd.getArgs();
  if (argv.length != 1) {
    errOut.println("transitionToActive: incorrect number of arguments");
    printUsage(errOut, "-transitionToActive");
    return -1;
  }
  /*  returns true if other target node is active or some exception occurred 
      and forceActive was not set  */
  if(!cmd.hasOption(FORCEACTIVE)) {
    if(isOtherTargetNodeActive(argv[0], cmd.hasOption(FORCEACTIVE))) {
      return -1;
    }
  }
  HAServiceTarget target = resolveTarget(argv[0]);
  if (!checkManualStateManagementOK(target)) {
    return -1;
  }
  HAServiceProtocol proto = target.getProxy(
      getConf(), 0);
  HAServiceProtocolHelper.transitionToActive(proto, createReqInfo());
  return 0;
}
 
Example 13
Project: rocketmq-rocketmq-all-4.1.0-incubating   File: ServerUtil.java   Source Code and License 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 14
Project: twister2   File: MPIProcess.java   Source Code and License 6 votes vote down vote up
private static Config loadConfigurations(CommandLine cmd, int id) {
  String twister2Home = cmd.getOptionValue("twister2_home");
  String container = cmd.getOptionValue("container_class");
  String configDir = cmd.getOptionValue("config_dir");
  String clusterType = cmd.getOptionValue("cluster_type");

  LOG.log(Level.INFO, String.format("Initializing process with "
      + "twister_home: %s container_class: %s config_dir: %s cluster_type: %s",
      twister2Home, container, configDir, clusterType));

  Config config = ConfigLoader.loadConfig(twister2Home, configDir + "/" + clusterType);
  return Config.newBuilder().putAll(config).
      put(MPIContext.TWISTER2_HOME.getKey(), twister2Home).
      put(MPIContext.TWISTER2_JOB_BASIC_CONTAINER_CLASS, container).
      put(MPIContext.TWISTER2_CONTAINER_ID, id).
      put(MPIContext.TWISTER2_CLUSTER_TYPE, clusterType).build();
}
 
Example 15
Project: cyberduck   File: CommandLinePathParserTest.java   Source Code and License 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 16
Project: doctorkafka   File: ReplicaStatsRetriever.java   Source Code and License 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 17
Project: hadoop   File: HAAdmin.java   Source Code and License 6 votes vote down vote up
private int transitionToStandby(final CommandLine cmd)
    throws IOException, ServiceFailedException {
  String[] argv = cmd.getArgs();
  if (argv.length != 1) {
    errOut.println("transitionToStandby: incorrect number of arguments");
    printUsage(errOut, "-transitionToStandby");
    return -1;
  }
  
  HAServiceTarget target = resolveTarget(argv[0]);
  if (!checkManualStateManagementOK(target)) {
    return -1;
  }
  HAServiceProtocol proto = target.getProxy(
      getConf(), 0);
  HAServiceProtocolHelper.transitionToStandby(proto, createReqInfo());
  return 0;
}
 
Example 18
Project: LiquidFortressPacketAnalyzer   File: CommandLineValidator.java   Source Code and License 6 votes vote down vote up
private static boolean isModeValid(CommandLine commandLine, ValidatedArgs validatedArgs) {
    if (commandLine.hasOption(CommandLineOptions.MODE)) {
        int mode = Integer.valueOf(commandLine.getOptionValue(CommandLineOptions.MODE));
        switch (mode) {
            case 1:
                validatedArgs.mode = Mode.BASIC_ANALYSIS;
                break;
            case 2:
                validatedArgs.mode = Mode.DETAILED_ANALYSIS;
                break;
            case 3:
                validatedArgs.mode = Mode.POSSIBLE_ATTACKS_ANALYSIS;
                break;
            default:
                return false;
        }
        return true;
    }
    return false;
}
 
Example 19
Project: devops-cm-client   File: TransportRelated.java   Source Code and License 6 votes vote down vote up
protected static void main(Class<? extends TransportRelated> clazz, String[] args, String usage, String helpText) throws Exception {

        logger.debug(format("%s called with arguments: %s", clazz.getSimpleName(), Commands.Helpers.getArgsLogString(args)));

        Options options = new Options();
        Commands.Helpers.addStandardParameters(options);

        if(helpRequested(args)) {
            handleHelpOption(usage, helpText, new Options()); return;
        }

        CommandLine commandLine = new DefaultParser().parse(options, args);

        newInstance(clazz, getHost(commandLine),
                getUser(commandLine),
                getPassword(commandLine),
                getChangeId(commandLine),
                getTransportId(commandLine)).execute();
    }
 
Example 20
Project: pm-home-station   File: Start.java   Source Code and License 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 21
Project: rmq4note   File: UpdateKvConfigCommand.java   Source Code and License 6 votes vote down vote up
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) {
    DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
    defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
    try {
        // namespace
        String namespace = commandLine.getOptionValue('s').trim();
        // key name
        String key = commandLine.getOptionValue('k').trim();
        // key name
        String value = commandLine.getOptionValue('v').trim();

        defaultMQAdminExt.start();
        defaultMQAdminExt.createAndUpdateKvConfig(namespace, key, value);
        System.out.printf("create or update kv config to namespace success.%n");
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        defaultMQAdminExt.shutdown();
    }
}
 
Example 22
Project: rocketmq-rocketmq-all-4.1.0-incubating   File: UpdateKvConfigCommand.java   Source Code and License 6 votes vote down vote up
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException {
    DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
    defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
    try {
        // namespace
        String namespace = commandLine.getOptionValue('s').trim();
        // key name
        String key = commandLine.getOptionValue('k').trim();
        // key name
        String value = commandLine.getOptionValue('v').trim();

        defaultMQAdminExt.start();
        defaultMQAdminExt.createAndUpdateKvConfig(namespace, key, value);
        System.out.printf("create or update kv config to namespace success.%n");
    } catch (Exception e) {
        throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e);
    } finally {
        defaultMQAdminExt.shutdown();
    }
}
 
Example 23
Project: iiif-producer   File: ArgParser.java   Source Code and License 5 votes vote down vote up
/**
 * This method parses the command-line args.
 *
 * @param cmd command line options
 * @return Config
 */
private Config parseConfigurationArgs(final CommandLine cmd) {
    final Config config = new Config();

    config.setViewId(cmd.getOptionValue('v'));
    config.setTitle(cmd.getOptionValue('t'));
    config.setInputFile(cmd.getOptionValue('i'));
    config.setOutputFile(cmd.getOptionValue('o'));
    return config;
}
 
Example 24
Project: BNPMix.java   File: SamplerOptionPack.java   Source Code and License 5 votes vote down vote up
@Override 
public SamplerOptionPack extract(CommandLine cmdline) {
  NumBurnin   = Integer.parseInt(cmdline.getOptionValue("NumBurnin"  , defaultNumBurnin  ));
  NumSample   = Integer.parseInt(cmdline.getOptionValue("NumSample"  , defaultNumSample  ));
  NumThinning = Integer.parseInt(cmdline.getOptionValue("NumThinning", defaultNumThinning));
  NumPrint    = Integer.parseInt(cmdline.getOptionValue("NumPrint"   , defaultNumPrint));
  return this;
}
 
Example 25
Project: 484_P7_1-Java   File: CommandLineApp.java   Source Code and License 5 votes vote down vote up
public CommandLineApp(Appendable defaultOutput, CommandLine line) throws ParseException {
    this.defaultOutput = defaultOutput;
    this.pageArea = CommandLineApp.whichArea(line);
    this.pages = CommandLineApp.whichPages(line);
    this.outputFormat = CommandLineApp.whichOutputFormat(line);
    this.tableExtractor = CommandLineApp.createExtractor(line);

    if (line.hasOption('s')) {
        this.password = line.getOptionValue('s');
    }
}
 
Example 26
Project: cyberduck   File: SingleTransferItemFinderTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testUploadDirectory() throws Exception {
    final CommandLineParser parser = new PosixParser();
    final CommandLine input = parser.parse(TerminalOptionsBuilder.options(), new String[]{"--upload", "ftps://test.cyberduck.ch/remote/", System.getProperty("java.io.tmpdir")});

    final Set<TransferItem> found = new SingleTransferItemFinder().find(input, TerminalAction.upload, new Path("/remote/", EnumSet.of(Path.Type.directory)));
    assertFalse(found.isEmpty());
    final Iterator<TransferItem> iter = found.iterator();
    final Local temp = LocalFactory.get(System.getProperty("java.io.tmpdir"));
    assertTrue(temp.getType().contains(Path.Type.directory));
    assertEquals(new TransferItem(new Path("/remote", EnumSet.of(Path.Type.directory)), temp), iter.next());
}
 
Example 27
Project: cyberduck   File: SingleTransferItemFinderTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testDeferUploadNameFromLocal() throws Exception {
    final CommandLineParser parser = new PosixParser();
    final String temp = System.getProperty("java.io.tmpdir");
    final CommandLine input = parser.parse(TerminalOptionsBuilder.options(), new String[]{"--upload", "ftps://test.cyberduck.ch/remote/", String.format("%s/f", temp)});

    final Set<TransferItem> found = new SingleTransferItemFinder().find(input, TerminalAction.upload, new Path("/remote/", EnumSet.of(Path.Type.directory)));
    assertFalse(found.isEmpty());
    assertEquals(new TransferItem(new Path("/remote/f", EnumSet.of(Path.Type.file)), LocalFactory.get(String.format("%s/f", temp))),
            found.iterator().next());
}
 
Example 28
Project: qpp-conversion-tool   File: ConversionEntryTest.java   Source Code and License 5 votes vote down vote up
@Test
void shouldAllowValidTemplateScopes() throws ParseException {
	//when
	CommandLine line = ConversionEntry.cli(new String[] {"file.txt", "-t", QrdaScope.ACI_SECTION.name()
			+ ","
			+ QrdaScope.IA_SECTION.name()});
	boolean result = ConversionEntry.shouldContinue(line);

	//then
	assertWithMessage("Both should be valid scopes")
			.that(result).isTrue();
}
 
Example 29
Project: qpp-conversion-tool   File: ConversionEntryTest.java   Source Code and License 5 votes vote down vote up
@Test
void testHandleSkipDefaults() throws ParseException {
	CommandLine line = ConversionEntry.cli(SKIP_DEFAULTS);
	assertWithMessage("Should have a skip default option")
			.that(line.hasOption(ConversionEntry.SKIP_DEFAULTS))
			.isTrue();
}
 
Example 30
Project: rmq4note   File: ProducerConnectionSubCommandTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testExecute() {
    ProducerConnectionSubCommand cmd = new ProducerConnectionSubCommand();
    Options options = ServerUtil.buildCommandlineOptions(new Options());
    String[] subargs = new String[] {"-g default-producer-group", "-t unit-test"};
    final CommandLine commandLine =
        ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser());
    cmd.execute(commandLine, options, null);
}
 
Example 31
Project: stl-decomp-4j   File: StlPerfTest.java   Source Code and License 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 32
Project: qpp-conversion-tool   File: ConversionEntryTest.java   Source Code and License 5 votes vote down vote up
@Test
void testHandleSkipValidationAbbreviated() throws ParseException {
	CommandLine line = ConversionEntry.cli("-v");
	assertWithMessage("Should have a skip validation option")
			.that(line.hasOption(ConversionEntry.SKIP_VALIDATION))
			.isTrue();
}
 
Example 33
Project: qpp-conversion-tool   File: ConversionEntryTest.java   Source Code and License 5 votes vote down vote up
@Test
void testHandleCombo() throws ParseException {
	CommandLine line = ConversionEntry.cli("-dvt", "meep");
	assertWithMessage("Should have a skip validation option")
			.that(line.hasOption(ConversionEntry.SKIP_VALIDATION)).isTrue();
	assertWithMessage("Should have a skip default option")
			.that(line.hasOption(ConversionEntry.SKIP_DEFAULTS)).isTrue();
	assertThat(line.getOptionValue(ConversionEntry.TEMPLATE_SCOPE))
			.isEqualTo("meep");
}
 
Example 34
Project: rmq4note   File: CloneGroupOffsetCommand.java   Source Code and License 5 votes vote down vote up
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) {
    String srcGroup = commandLine.getOptionValue("s").trim();
    String destGroup = commandLine.getOptionValue("d").trim();
    String topic = commandLine.getOptionValue("t").trim();

    DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
    defaultMQAdminExt.setInstanceName("admin-" + Long.toString(System.currentTimeMillis()));

    try {
        defaultMQAdminExt.start();
        ConsumeStats consumeStats = defaultMQAdminExt.examineConsumeStats(srcGroup);
        Set<MessageQueue> mqs = consumeStats.getOffsetTable().keySet();
        if (!mqs.isEmpty()) {
            TopicRouteData topicRoute = defaultMQAdminExt.examineTopicRouteInfo(topic);
            for (MessageQueue mq : mqs) {
                String addr = null;
                for (BrokerData brokerData : topicRoute.getBrokerDatas()) {
                    if (brokerData.getBrokerName().equals(mq.getBrokerName())) {
                        addr = brokerData.selectBrokerAddr();
                        break;
                    }
                }
                long offset = consumeStats.getOffsetTable().get(mq).getBrokerOffset();
                if (offset >= 0) {
                    defaultMQAdminExt.updateConsumeOffset(addr, destGroup, mq, offset);
                }
            }
        }
        System.out.printf("clone group offset success. srcGroup[%s], destGroup=[%s], topic[%s]",
            srcGroup, destGroup, topic);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        defaultMQAdminExt.shutdown();
    }
}
 
Example 35
Project: TensorFlowOnYARN   File: ProcessRunner.java   Source Code and License 5 votes vote down vote up
private CommandLine parseArgs(Options opts, String[] args) throws ParseException {
  if (args.length == 0) {
    throw new IllegalArgumentException("No args specified for " + name + " to initialize");
  }

  return new GnuParser().parse(opts, args);
}
 
Example 36
Project: doctorkafka   File: BrokerStatsFilter.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
  CommandLine commandLine = parseCommandLine(args);
  String brokerStatsZk = commandLine.getOptionValue(BROKERSTATS_ZOOKEEPER);
  String brokerStatsTopic = commandLine.getOptionValue(BROKERSTATS_TOPIC);
  String brokerName = commandLine.getOptionValue(BROKERNAME);
  Set<String> brokerNames = new HashSet<>();
  brokerNames.add(brokerName);

  KafkaConsumer kafkaConsumer = KafkaUtils.getKafkaConsumer(brokerStatsZk,
      "org.apache.kafka.common.serialization.ByteArrayDeserializer",
      "org.apache.kafka.common.serialization.ByteArrayDeserializer", 1);

  long startTimestampInMillis = System.currentTimeMillis() - 86400 * 1000L;
  Map<TopicPartition, Long> offsets = ReplicaStatsManager.getProcessingStartOffsets(
      kafkaConsumer, brokerStatsTopic, startTimestampInMillis);
  kafkaConsumer.unsubscribe();
  kafkaConsumer.assign(offsets.keySet());
  Map<TopicPartition, Long> latestOffsets = kafkaConsumer.endOffsets(offsets.keySet());
  kafkaConsumer.close();

  Map<Long, BrokerStats> brokerStatsMap = new TreeMap<>();
  for (TopicPartition topicPartition : offsets.keySet()) {
    LOG.info("Start processing {}", topicPartition);
    long startOffset = offsets.get(topicPartition);
    long endOffset = latestOffsets.get(topicPartition);

    List<BrokerStats> statsList = processOnePartition(brokerStatsZk, topicPartition,
        startOffset, endOffset, brokerNames);
    for (BrokerStats brokerStats : statsList) {
      brokerStatsMap.put(brokerStats.getTimestamp(), brokerStats);
    }
    LOG.info("Finished processing {}, retrieved {} records", topicPartition, statsList.size());
  }

  for (Map.Entry<Long, BrokerStats> entry: brokerStatsMap.entrySet()) {
    System.out.println(entry.getKey() + " : " + entry.getValue());
  }
}
 
Example 37
Project: hadoop   File: HAAdmin.java   Source Code and License 5 votes vote down vote up
private int getServiceState(final CommandLine cmd)
    throws IOException, ServiceFailedException {
  String[] argv = cmd.getArgs();
  if (argv.length != 1) {
    errOut.println("getServiceState: incorrect number of arguments");
    printUsage(errOut, "-getServiceState");
    return -1;
  }

  HAServiceProtocol proto = resolveTarget(argv[0]).getProxy(
      getConf(), rpcTimeoutForChecks);
  out.println(proto.getServiceStatus().getState());
  return 0;
}
 
Example 38
Project: ditb   File: IntegrationTestReplication.java   Source Code and License 5 votes vote down vote up
@Override
protected void processOptions(CommandLine cmd) {
  processBaseOptions(cmd);

  sourceClusterIdString = cmd.getOptionValue(SOURCE_CLUSTER_OPT);
  sinkClusterIdString = cmd.getOptionValue(DEST_CLUSTER_OPT);
  outputDir = cmd.getOptionValue(OUTPUT_DIR_OPT);

  /** This uses parseInt from {@link org.apache.hadoop.hbase.util.AbstractHBaseTool} */
  numMappers = parseInt(cmd.getOptionValue(NUM_MAPPERS_OPT,
                                           Integer.toString(DEFAULT_NUM_MAPPERS)),
                        1, Integer.MAX_VALUE);
  numReducers = parseInt(cmd.getOptionValue(NUM_REDUCERS_OPT,
                                            Integer.toString(DEFAULT_NUM_REDUCERS)),
                         1, Integer.MAX_VALUE);
  numNodes = parseInt(cmd.getOptionValue(NUM_NODES_OPT, Integer.toString(DEFAULT_NUM_NODES)),
                      1, Integer.MAX_VALUE);
  generateVerifyGap = parseInt(cmd.getOptionValue(GENERATE_VERIFY_GAP_OPT,
                                                  Integer.toString(DEFAULT_GENERATE_VERIFY_GAP)),
                               1, Integer.MAX_VALUE);
  numIterations = parseInt(cmd.getOptionValue(ITERATIONS_OPT,
                                              Integer.toString(DEFAULT_NUM_ITERATIONS)),
                           1, Integer.MAX_VALUE);
  width = parseInt(cmd.getOptionValue(WIDTH_OPT, Integer.toString(DEFAULT_WIDTH)),
                                      1, Integer.MAX_VALUE);
  wrapMultiplier = parseInt(cmd.getOptionValue(WRAP_MULTIPLIER_OPT,
                                               Integer.toString(DEFAULT_WRAP_MULTIPLIER)),
                            1, Integer.MAX_VALUE);

  if (cmd.hasOption(NO_REPLICATION_SETUP_OPT)) {
    noReplicationSetup = true;
  }

  if (numNodes % (width * wrapMultiplier) != 0) {
    throw new RuntimeException("numNodes must be a multiple of width and wrap multiplier");
  }
}
 
Example 39
Project: cyberduck   File: CommandLineUriParserTest.java   Source Code and License 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: aliyun-maxcompute-data-collectors   File: EvalSqlTool.java   Source Code and License 5 votes vote down vote up
@Override
/** {@inheritDoc} */
public void applyOptions(CommandLine in, SqoopOptions out)
    throws InvalidOptionsException {

  applyCommonOptions(in, out);
  if (in.hasOption(SQL_QUERY_ARG)) {
    out.setSqlQuery(in.getOptionValue(SQL_QUERY_ARG));
  }
}