Java 类org.apache.commons.cli.CommandLine 实例源码

项目:doctorkafka    文件:URPChecker.java   
/**
 *  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;
}
项目:484_P7_1-Java    文件:CommandLineApp.java   
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);
}
项目:ditb    文件:IntegrationTestLoadAndVerify.java   
@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];
    }
  }
}
项目:https-github.com-apache-zookeeper    文件:SyncCommand.java   
@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;
}
项目:rocketmq-rocketmq-all-4.1.0-incubating    文件:UpdateTopicSubCommandTest.java   
@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");
}
项目:java-cli-demos    文件:MainWithBuilder.java   
/**
 * 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 + "'.");
   }
}
项目:rmq4note    文件:SendMsgStatusCommand.java   
@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();
    }
}
项目:DemoUi    文件:DemoUiCommandLineParser.java   
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;
    }
项目:BNPMix.java    文件:MixtureOptionPack.java   
@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;
}
项目:devops-cm-client    文件:ReleaseTransport.java   
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();
}
项目:ditb    文件:ThriftServerRunner.java   
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);
}
项目:hadoop-oss    文件:HAAdmin.java   
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;
}
项目:rocketmq-rocketmq-all-4.1.0-incubating    文件:ServerUtil.java   
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;
}
项目:twister2    文件:MPIProcess.java   
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();
}
项目:doctorkafka    文件:ReplicaStatsRetriever.java   
/**
 *  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;
}
项目:hadoop    文件:HAAdmin.java   
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;
}
项目:LiquidFortressPacketAnalyzer    文件:CommandLineValidator.java   
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;
}
项目:devops-cm-client    文件:TransportRelated.java   
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();
    }
项目:pm-home-station    文件:Start.java   
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;
    }
}
项目:rmq4note    文件:UpdateKvConfigCommand.java   
@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();
    }
}
项目:rocketmq-rocketmq-all-4.1.0-incubating    文件:UpdateKvConfigCommand.java   
@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();
    }
}
项目:iiif-producer    文件:ArgParser.java   
/**
 * 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;
}
项目:BNPMix.java    文件:SamplerOptionPack.java   
@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;
}
项目:484_P7_1-Java    文件:CommandLineApp.java   
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');
    }
}
项目:cyberduck    文件:SingleTransferItemFinderTest.java   
@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());
}
项目:cyberduck    文件:SingleTransferItemFinderTest.java   
@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());
}
项目:qpp-conversion-tool    文件:ConversionEntryTest.java   
@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();
}
项目:qpp-conversion-tool    文件:ConversionEntryTest.java   
@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();
}
项目:rmq4note    文件:ProducerConnectionSubCommandTest.java   
@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);
}
项目:stl-decomp-4j    文件:StlPerfTest.java   
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);

}
项目:qpp-conversion-tool    文件:ConversionEntryTest.java   
@Test
void testHandleSkipValidationAbbreviated() throws ParseException {
    CommandLine line = ConversionEntry.cli("-v");
    assertWithMessage("Should have a skip validation option")
            .that(line.hasOption(ConversionEntry.SKIP_VALIDATION))
            .isTrue();
}
项目:qpp-conversion-tool    文件:ConversionEntryTest.java   
@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");
}
项目:rmq4note    文件:CloneGroupOffsetCommand.java   
@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();
    }
}
项目:TensorFlowOnYARN    文件:ProcessRunner.java   
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);
}
项目:doctorkafka    文件:BrokerStatsFilter.java   
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());
  }
}
项目:hadoop    文件:HAAdmin.java   
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;
}
项目:ditb    文件:IntegrationTestReplication.java   
@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");
  }
}
项目:cyberduck    文件:CommandLineUriParserTest.java   
@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);
}
项目:aliyun-maxcompute-data-collectors    文件:EvalSqlTool.java   
@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));
  }
}