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

项目:gemfirexd-oss    文件:ToolsBase.java   
protected boolean handleCommonOption(final GfxdOption opt, final String cmd,
    final String cmdDescKey) throws ParseException {
  if (SYSTEM_PROPERTY.equals(opt.getOpt())) {
    String optValue = opt.getValue();
    int indexOfEquals = optValue.indexOf('=');
    if (indexOfEquals >= 0) {
      System.setProperty(optValue.substring(0, indexOfEquals),
          optValue.substring(indexOfEquals + 1));
    }
    else {
      throw new MissingArgumentException(opt);
    }
  }
  else if (HELP.equals(opt.getOpt())) {
    showUsage(null, cmd, cmdDescKey);
    throw new GemFireTerminateError(null, 0);
  }
  else {
    return false;
  }
  return true;
}
项目:rug-cli    文件:ParseExceptionProcessor.java   
@SuppressWarnings("unchecked")
public static String process(ParseException e) {
    if (e instanceof MissingOptionException) {
        StringBuilder sb = new StringBuilder();
        Iterator<String> options = ((MissingOptionException) e).getMissingOptions().iterator();
        while (options.hasNext()) {
            sb.append(options.next());
            if (options.hasNext()) {
                sb.append(", ");
            }
        }
        return String.format("Missing required option(s) %s.", sb.toString());
    }
    else if (e instanceof MissingArgumentException) {
        return String.format("%s is missing a required argument.",
                ((MissingArgumentException) e).getOption());
    }
    else if (e instanceof UnrecognizedOptionException) {
        return String.format("%s is not a valid option.",
                ((UnrecognizedOptionException) e).getOption());
    }
    else {
        return String.format("%s.", e.getMessage());
    }
}
项目:OSTMap    文件:ConnectionAnalysis.java   
public static void main(String[] args) throws Exception {
    GraphLoader gl = new GraphLoader();
    Graph<String, UserNodeValues, UserEdgeValues> graph;
    final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
    if(args.length == 0) {
        // read graph from accumulo
        graph = null; // TODO : adapt to gl.getUserGraph();
    } else if (args.length == 1) {
        graph = gl.getUserGraphFromFiles(args[0],env);
    } else {
        throw new MissingArgumentException("Either use no arguments for graph import from accumulo or the path " +
                "to file where the graph is stored.");
    }

    ConnectionAnalysis ca = new ConnectionAnalysis();
    ca.analyze(graph);
}
项目:gemfirexd-oss    文件:ToolsBase.java   
protected boolean handleCommonOption(final GfxdOption opt, final String cmd,
    final String cmdDescKey) throws ParseException {
  if (SYSTEM_PROPERTY.equals(opt.getOpt())) {
    String optValue = opt.getValue();
    int indexOfEquals = optValue.indexOf('=');
    if (indexOfEquals >= 0) {
      System.setProperty(optValue.substring(0, indexOfEquals),
          optValue.substring(indexOfEquals + 1));
    }
    else {
      throw new MissingArgumentException(opt);
    }
  }
  else if (HELP.equals(opt.getOpt())) {
    showUsage(null, cmd, cmdDescKey);
    throw new GemFireTerminateError(null, 0);
  }
  else {
    return false;
  }
  return true;
}
项目:hops    文件:RMAdminCLI.java   
private int handleReplaceLabelsOnNodes(String[] args, String cmd,
    boolean isHAEnabled) throws IOException, YarnException, ParseException {
  Options opts = new Options();
  opts.addOption("replaceLabelsOnNode", true,
      "Replace label on node.");
  opts.addOption("failOnUnknownNodes", false,
      "Fail on unknown nodes.");
  opts.addOption("directlyAccessNodeLabelStore", false,
      "Directly access node label store.");
  int exitCode = -1;
  CommandLine cliParser = null;
  try {
    cliParser = new GnuParser().parse(opts, args);
  } catch (MissingArgumentException ex) {
    System.err.println(NO_MAPPING_ERR_MSG);
    printUsage(args[0], isHAEnabled);
    return exitCode;
  }

  Map<NodeId, Set<String>> map = buildNodeLabelsMapFromStr(
      cliParser.getOptionValue("replaceLabelsOnNode"));
  return replaceLabelsOnNodes(map,
      cliParser.hasOption("failOnUnknownNodes"),
      cliParser.hasOption("directlyAccessNodeLabelStore"));
}
项目:Izou    文件:AddOnInformationManager.java   
/**
 * Registers an addOn with the AddOnInformationManager by extracting all relevant information from the addOn and
 * adding it the the sets.
 *
 * Once an addOn is registered, its public data can be viewed by any other addOn through the context.
 *
 * @param addOn The addOn to register with the AddOnInformationManager.
 */
public void registerAddOn(AddOnModel addOn) {
    PluginDescriptor descriptor = addOn.getPlugin().getDescriptor();

    String name = descriptor.getTitle();
    String version = descriptor.getVersion().toString();
    String provider = descriptor.getProvider();
    String id = descriptor.getPluginId();
    String sdkVersion = descriptor.getSdkVersion().toString();
    String artifactID = descriptor.getArtifactID();
    Optional<Integer> serverID = descriptor.getServerID();

    try {
        AddOnInformation addOnInformation = new AddOnInformationImpl(name, provider, version, id, sdkVersion,
                serverID, artifactID);
        addOnInformations.add(addOnInformation);
        addOns.add(addOn);
    } catch (MissingArgumentException e) {
        error("Unable to register addOn: " + addOn.getID() + " with the AddOnInformationManager", e);
    }
}
项目:Izou    文件:AddOnInformationImpl.java   
/**
 * Creates a new instance of AddOnInformation, which holds all the public information of an addOn and is registered
 * in the {@link AddOnInformationManager} with the serverID.
 *
 * @param name The name of the AddOn.
 * @param version The version of the AddOn.
 * @param provider The author of the AddOn.
 * @param id The unique ID of the AddOn.
 * @param sdkVersion The version of the SDK that this addOn uses.
 * @param serverID The serverID of the addOn, if it has one (used to match the addOn with the server).
 * @param artifactID The artifactID of the addOn. This is the maven artifactID.
 *
 * @throws MissingArgumentException Thrown if the config file of an addon is not complete, in other words if
 * an argument is missing in the file
 */
public AddOnInformationImpl(String name, String provider, String version, String id, String sdkVersion,
                            Optional<Integer> serverID, String artifactID) throws MissingArgumentException {

    if (!checkField(name) || !checkField(provider) || !checkField(version) || !checkField(id)
            || !checkField(sdkVersion) || !checkField(artifactID)) {
        throw new MissingArgumentException("AddOnInformation is not complete - an argument is missing");
    }

    this.name = name;
    this.version = new Version(version);
    this.provider = provider;
    this.id = id;
    this.sdkVersion = new Version(sdkVersion);
    this.serverID = serverID;
    this.artifactID = artifactID;
}
项目:cfnassist    文件:CreateKeyPairAction.java   
@Override
public void invoke(FacadeFactory factory, ProjectAndEnv projectAndEnv, Collection<Parameter> cfnParams,
                   Collection<Parameter> artifacts, String... argument) throws IOException, InterruptedException,
        CfnAssistException, MissingArgumentException {
    AwsFacade facade = factory.createFacade();

    String filename;
    if (argument==null) {
        String home = System.getenv("HOME");
        String keypairName = format("%s_%s", projectAndEnv.getProject(), projectAndEnv.getEnv());
        filename = format("%s/.ssh/%s.pem", home, keypairName);
    } else {
        filename = argument[0];
    }

    KeyPair keyPair = facade.createKeyPair(projectAndEnv, factory.getSavesFile(), filename);
    System.out.println(format("Created key %s with fingerprint %s", keyPair.getKeyName(),
            keyPair.getKeyFingerprint()));
}
项目:vcloud-client    文件:Configuration.java   
public static CommandLine parseCli(ModeType mode, String[] args) {
    CommandLine cli = null;
    Options opt = ConfigModes.getMode(mode);
    try {
        cli = new IgnorePosixParser(true).parse(opt, args);
    } catch (MissingArgumentException me) {
        Formatter.usageError(me.getLocalizedMessage(), mode);
        System.exit(-1);
    } catch (MissingOptionException mo) {
        Formatter.usageError(mo.getLocalizedMessage(), mode);
        System.exit(-1);
    } catch (AlreadySelectedException ase) {
        Formatter.usageError(ase.getLocalizedMessage(), mode);
    } catch (UnrecognizedOptionException uoe) {
        Formatter.usageError(uoe.getLocalizedMessage(), mode);
    } catch (ParseException e) {
        Formatter.printStackTrace(e);
        System.exit(-1);
    }

    return cli;
}
项目:cfnassist    文件:DiagramsElement.java   
@Override
public void execute(FacadeFactory factory, ProjectAndEnv projectAndEnv,
        Collection<Parameter> cfnParams, Collection<Parameter> artifacts)
        throws IOException, InterruptedException,
        CfnAssistException, CommandLineException, MissingArgumentException {
    String path = target.getAbsolutePath();

    if (!target.isDirectory()) {
        throw new BuildException(
                String.format("Target %s was not a directory, please provide a directory for the diagrams to be saved into", path));
    }

    CreateDiagramAction action = new CreateDiagramAction();

    action.validate(projectAndEnv, cfnParams, artifacts, path);
    action.invoke(factory, projectAndEnv, cfnParams, artifacts, path);

}
项目:cfnassist    文件:TemplatesElement.java   
@Override
public void execute(FacadeFactory factory, ProjectAndEnv projectAndEnv, Collection<Parameter> cfnParams, Collection<Parameter> artifacts) 
        throws IOException, InterruptedException, CfnAssistException,
        CommandLineException, MissingArgumentException {
    String absolutePath = target.getAbsolutePath();
    CommandLineAction actionToInvoke = null;
    if (target.isDirectory()) {
        actionToInvoke = new DirAction();
    } else if (target.isFile()) {
        actionToInvoke = new FileAction();
    } 

    if (actionToInvoke==null) {
        throw new BuildException("Unable to action on path, expect file or folder, path was: " + absolutePath);
    } 
    actionToInvoke.validate(projectAndEnv, cfnParams, artifacts, absolutePath);
    actionToInvoke.invoke(factory, projectAndEnv, cfnParams, artifacts, absolutePath);      
}
项目:cfnassist    文件:SNSEventSource.java   
@Override
public void init() throws MissingArgumentException, FailedToCreateQueueException, InterruptedException {
    if (init) {
        logger.warn("SNSMonitor init called again");
        return;
    }
    logger.info("Init SNSMonitor");
    topicSnsArn = getOrCreateSNSARN();
    queueURL = getOrCreateQueue();

    Map<String, String> queueAttributes = getQueueAttributes(queueURL);
    queueArn = queueAttributes.get(QUEUE_ARN_KEY);
    checkOrCreateQueuePermissions(queueAttributes, topicSnsArn, queueArn, queueURL);

    createOrGetSQSSubscriptionToSNS();
    init = true;
}
项目:cfnassist    文件:FacadeFactory.java   
public AwsFacade createFacade() throws MissingArgumentException, CfnAssistException, InterruptedException {     
    if (awsFacade==null) {
        init();
        SNSEventSource eventSource = new SNSEventSource(snsClient, sqsClient);
        MonitorStackEvents monitor;
        if (snsMonitoring) {    
            monitor = new SNSMonitor(eventSource, cfnRepository);
        } else {
            monitor = new PollingStackMonitor(cfnRepository);
        }

        monitor.init();
           AwsRegionProvider regionProvider = new DefaultAwsRegionProviderChain();
           awsFacade = new AwsFacade(monitor, cfnRepository, vpcRepository, elbRepository,
                cloudRepository, notificationSender, identityProvider);
    }   
    return awsFacade;   
}
项目:cfnassist    文件:TestSNSEventSource.java   
@Test
public void shouldCreateSNSAndSQSPlusPolicyAsNeeded() throws MissingArgumentException, NotReadyException, FailedToCreateQueueException, InterruptedException {
    eventSource.init();
    String existingSNSARN = eventSource.getSNSArn();

    // reset the queue, sns and subscription (this forces policy recreation as well)
    String sub = eventSource.getARNofSQSSubscriptionToSNS();
    if (sub!=null) {
        snsClient.unsubscribe(sub);
    }
    snsClient.deleteTopic(existingSNSARN);
    sqsClient.deleteQueue(eventSource.getQueueURL());

    // now recreate the source and make sure we can send/receive
    SNSEventSource anotherEventSource = new SNSEventSource(snsClient, sqsClient);
    anotherEventSource.init();
    // should be able to send via sns and then receive from sqs if everything worked ok
    snsClient.publish(anotherEventSource.getSNSArn(), "aMessage");
    ReceiveMessageRequest request = new ReceiveMessageRequest().
            withQueueUrl(anotherEventSource.getQueueURL()).
            withWaitTimeSeconds(10);
    ReceiveMessageResult result = sqsClient.receiveMessage(request);
    assertTrue(result.getMessages().size()>0);
}
项目:cfnassist    文件:TestSNSStackMonitor.java   
@Test 
public void shouldThrowWhenExpectedStatusNotWithinTimeout() throws MissingArgumentException, InterruptedException, CfnAssistException {
    isStackFound= true;
    String inProgress = StackStatus.CREATE_IN_PROGRESS.toString();

    setExpectationsForInitAndReady();
    setExpectationsRepondInProgressUntilLimit(inProgress);

    replayAll();
    monitor.init();
    try {
        monitor.waitForRollbackComplete(stackNameAndId);
        fail("should have thrown");
    }
    catch(WrongStackStatus expectedException) {
        // noop
    }
    verifyAll();
}
项目:cfnassist    文件:TestSNSStackMonitor.java   
@Test
public void shouldMonitorMultiplePendingDeletes() throws InterruptedException, CfnAssistException, MissingArgumentException {
    isStackFound = true;
    String targetStatus = StackStatus.DELETE_COMPLETE.toString();

    DeletionsPending pending = createPendingDelete();

    eventSource.init();
    EasyMock.expectLastCall();
    EasyMock.expect(eventSource.isInit()).andReturn(true);
    setEventStreamExpectations(StackStatus.DELETE_IN_PROGRESS.toString(), targetStatus, "stackC", "id3");
    setEventStreamExpectations(StackStatus.DELETE_IN_PROGRESS.toString(), targetStatus, "stackB", "id2");
    setEventStreamExpectations(StackStatus.DELETE_IN_PROGRESS.toString(), targetStatus, "stackA", "id1");

    replayAll();
    monitor.init();
    monitor.waitForDeleteFinished(pending, this);
    assertEquals(0, deltaIndexResult);
    verifyAll();
}
项目:cfnassist    文件:TestSNSStackMonitor.java   
@Test
public void shouldMonitorMultiplePendingDeletesOutOfOrder() throws InterruptedException, CfnAssistException, MissingArgumentException {
    isStackFound = true;
    String targetStatus = StackStatus.DELETE_COMPLETE.toString();

    DeletionsPending pending = createPendingDelete();

    eventSource.init();
    EasyMock.expectLastCall();
    EasyMock.expect(eventSource.isInit()).andReturn(true);
    setEventStreamExpectations(StackStatus.DELETE_IN_PROGRESS.toString(), targetStatus, "stackB", "id2");
    setEventStreamExpectations(StackStatus.DELETE_IN_PROGRESS.toString(), targetStatus, "stackA", "id1");
    setEventStreamExpectations(StackStatus.DELETE_IN_PROGRESS.toString(), targetStatus, "stackC", "id3");

    replayAll();
    monitor.init();
    monitor.waitForDeleteFinished(pending, this);
    assertEquals(0, deltaIndexResult);
    verifyAll();
}
项目:cfnassist    文件:TestSNSStackMonitor.java   
@Test
public void shouldMonitorMultiplePendingDeletesNotAll() throws InterruptedException, CfnAssistException, MissingArgumentException {
    isStackFound = true;
    String targetStatus = StackStatus.DELETE_COMPLETE.toString();

    DeletionsPending pending = createPendingDelete();

    eventSource.init();
    EasyMock.expectLastCall();
    EasyMock.expect(eventSource.isInit()).andReturn(true);
    setEventStreamExpectations(StackStatus.DELETE_IN_PROGRESS.toString(), targetStatus, "stackB", "id2");
    setEventStreamExpectations(StackStatus.DELETE_IN_PROGRESS.toString(), targetStatus, "stackC", "id3");
    setExpectationsRepondInProgressUntilLimit(StackStatus.DELETE_IN_PROGRESS.toString());

    replayAll();
    monitor.init();
    monitor.waitForDeleteFinished(pending, this);
    assertEquals(1, deltaIndexResult);
    verifyAll();
}
项目:cfnassist    文件:TestSNSStackMonitor.java   
@Test
public void shouldMonitorMultiplePendingDeletesSomeMissing() throws InterruptedException, CfnAssistException, MissingArgumentException {
    isStackFound = true;
    String targetStatus = StackStatus.DELETE_COMPLETE.toString();

    DeletionsPending pending = createPendingDelete();

    eventSource.init();
    EasyMock.expectLastCall();
    EasyMock.expect(eventSource.isInit()).andReturn(true);
    setEventStreamExpectations(StackStatus.DELETE_IN_PROGRESS.toString(), targetStatus, "stackB", "id2");
    setExpectationsRepondInProgressUntilLimit(StackStatus.DELETE_IN_PROGRESS.toString());

    replayAll();
    monitor.init();
    monitor.waitForDeleteFinished(pending, this);
    assertEquals(1, deltaIndexResult);
    verifyAll();
}
项目:cfnassist    文件:TestCommandLineActions.java   
@Test
public void shouldListStacks() throws MissingArgumentException, CfnAssistException, InterruptedException, IOException {
    String stackName = "theStackName";
    String project = "theProject";
    String stackId = "theStackId";
    String env = "theEnv";

    setFactoryExpectations();

    List<StackEntry> stackEntries = new LinkedList<>();
    Stack stack = new Stack().withStackName(stackName).withStackId(stackId).withStackStatus(StackStatus.CREATE_COMPLETE);
    stackEntries.add(new StackEntry(project, new EnvironmentTag(env), stack));
    EasyMock.expect(facade.listStacks(projectAndEnv)).andReturn(stackEntries);

    String output = validate(CLIArgBuilder.listStacks());

    CLIArgBuilder.checkForExpectedLine(stackName, project, env, output);
}
项目:cfnassist    文件:TestCommandLineActions.java   
@Test
public void shouldUploadArtifacts() throws MissingArgumentException, CfnAssistException, InterruptedException {
    Integer buildNumber = 9987;
    Collection<Parameter> arts = new LinkedList<>();
    arts.add(new Parameter().withParameterKey("art1").withParameterValue(FilesForTesting.ACL));
    arts.add(new Parameter().withParameterKey("art2").withParameterValue(FilesForTesting.SUBNET_STACK));
    List<Parameter> uploaded = new LinkedList<>();

    factory.setProject(EnvironmentSetupForTests.PROJECT);

    projectAndEnv.addBuildNumber(buildNumber);
    EasyMock.expect(factory.createArtifactUploader(projectAndEnv)).andReturn(artifactUploader);
    EasyMock.expect(artifactUploader.uploadArtifacts(arts)).andReturn(uploaded);

    validate(CLIArgBuilder.uploadArtifacts(buildNumber));
}
项目:cfnassist    文件:TestCommandLineActions.java   
@Test
public void shouldDeleteArtifacts() throws MissingArgumentException, CfnAssistException, InterruptedException {
    Integer buildNumber = 9987;
    String filenameA = "fileA";
    String filenameB = "fileB";

    factory.setProject(EnvironmentSetupForTests.PROJECT);
       EasyMock.expectLastCall();

       projectAndEnv.addBuildNumber(buildNumber);
    EasyMock.expect(factory.createArtifactUploader(projectAndEnv)).andReturn(artifactUploader);
    artifactUploader.delete(filenameA);
       EasyMock.expectLastCall();
       artifactUploader.delete(filenameB);
       EasyMock.expectLastCall();

       validate(CLIArgBuilder.deleteArtifacts(buildNumber, filenameA, filenameB));
}
项目:qpp-conversion-tool    文件:ConversionEntryTest.java   
@Test
void shouldAllowEmptyTemplateScope() throws ParseException {
    //when
    Assertions.assertThrows(MissingArgumentException.class, () -> {
        CommandLine line = ConversionEntry.cli("-t");
        ConversionEntry.shouldContinue(line);
    });
}
项目:aliyun-maxcompute-data-collectors    文件:SqoopParser.java   
@Override
/**
 * Processes arguments to options but only strips matched quotes.
 */
public void processArgs(Option opt, ListIterator iter)
    throws ParseException {
  // Loop until an option is found.
  while (iter.hasNext()) {
    String str = (String) iter.next();

    if (getOptions().hasOption(str) && str.startsWith("-")) {
      // found an Option, not an argument.
      iter.previous();
      break;
    }

    // Otherwise, this is a value.
    try {
      // Note that we only strip matched quotes here.
      addValForProcessing.invoke(opt, stripMatchedQuotes(str));
    } catch (IllegalAccessException iae) {
      throw new RuntimeException(iae);
    } catch (java.lang.reflect.InvocationTargetException ite) {
      // Any runtime exception thrown within addValForProcessing()
      // will be wrapped in an InvocationTargetException.
      iter.previous();
      break;
    } catch (RuntimeException re) {
      iter.previous();
      break;
    }
  }

  if (opt.getValues() == null && !opt.hasOptionalArg()) {
    throw new MissingArgumentException(opt);
  }
}
项目:hadoop    文件:QueueCLI.java   
@Override
public int run(String[] args) throws Exception {
  Options opts = new Options();

  opts.addOption(STATUS_CMD, true,
      "List queue information about given queue.");
  opts.addOption(HELP_CMD, false, "Displays help for all commands.");
  opts.getOption(STATUS_CMD).setArgName("Queue Name");

  CommandLine cliParser = null;
  try {
    cliParser = new GnuParser().parse(opts, args);
  } catch (MissingArgumentException ex) {
    sysout.println("Missing argument for options");
    printUsage(opts);
    return -1;
  }

  if (cliParser.hasOption(STATUS_CMD)) {
    if (args.length != 2) {
      printUsage(opts);
      return -1;
    }
    return listQueue(cliParser.getOptionValue(STATUS_CMD));
  } else if (cliParser.hasOption(HELP_CMD)) {
    printUsage(opts);
    return 0;
  } else {
    syserr.println("Invalid Command Usage : ");
    printUsage(opts);
    return -1;
  }
}
项目:aliyun-oss-hadoop-fs    文件:QueueCLI.java   
@Override
public int run(String[] args) throws Exception {
  Options opts = new Options();

  opts.addOption(STATUS_CMD, true,
      "List queue information about given queue.");
  opts.addOption(HELP_CMD, false, "Displays help for all commands.");
  opts.getOption(STATUS_CMD).setArgName("Queue Name");

  CommandLine cliParser = null;
  try {
    cliParser = new GnuParser().parse(opts, args);
  } catch (MissingArgumentException ex) {
    sysout.println("Missing argument for options");
    printUsage(opts);
    return -1;
  }

  if (cliParser.hasOption(STATUS_CMD)) {
    if (args.length != 2) {
      printUsage(opts);
      return -1;
    }
    return listQueue(cliParser.getOptionValue(STATUS_CMD));
  } else if (cliParser.hasOption(HELP_CMD)) {
    printUsage(opts);
    return 0;
  } else {
    syserr.println("Invalid Command Usage : ");
    printUsage(opts);
    return -1;
  }
}
项目:big-c    文件:QueueCLI.java   
@Override
public int run(String[] args) throws Exception {
  Options opts = new Options();

  opts.addOption(STATUS_CMD, true,
      "List queue information about given queue.");
  opts.addOption(HELP_CMD, false, "Displays help for all commands.");
  opts.getOption(STATUS_CMD).setArgName("Queue Name");

  CommandLine cliParser = null;
  try {
    cliParser = new GnuParser().parse(opts, args);
  } catch (MissingArgumentException ex) {
    sysout.println("Missing argument for options");
    printUsage(opts);
    return -1;
  }

  if (cliParser.hasOption(STATUS_CMD)) {
    if (args.length != 2) {
      printUsage(opts);
      return -1;
    }
    return listQueue(cliParser.getOptionValue(STATUS_CMD));
  } else if (cliParser.hasOption(HELP_CMD)) {
    printUsage(opts);
    return 0;
  } else {
    syserr.println("Invalid Command Usage : ");
    printUsage(opts);
    return -1;
  }
}
项目:mesfavoris    文件:BugCLI71Test.java   
@Test
public void testLackOfError() throws Exception {
    String[] args = new String[] { "-k", "-a",  "Caesar" };
    try {
        parser.parse( options, args);
        fail("MissingArgumentException expected");
    } catch(MissingArgumentException e) {
        assertEquals("option missing an argument", "k", e.getOption().getOpt());
    }
}
项目:mesfavoris    文件:BugsTest.java   
@Test
public void test13425() throws Exception
{
    Options options = new Options();
    Option oldpass = OptionBuilder.withLongOpt( "old-password" )
        .withDescription( "Use this option to specify the old password" )
        .hasArg()
        .create( 'o' );
    Option newpass = OptionBuilder.withLongOpt( "new-password" )
        .withDescription( "Use this option to specify the new password" )
        .hasArg()
        .create( 'n' );

    String[] args = { 
        "-o", 
        "-n", 
        "newpassword" 
    };

    options.addOption( oldpass );
    options.addOption( newpass );

    Parser parser = new PosixParser();

    try {
        parser.parse( options, args );
        fail( "MissingArgumentException not caught." );
    } catch( MissingArgumentException expected ) {
    }
}
项目:mesfavoris    文件:BugCLI71Test.java   
@Test
public void testLackOfError() throws Exception {
    String[] args = new String[] { "-k", "-a",  "Caesar" };
    try {
        parser.parse( options, args);
        fail("MissingArgumentException expected");
    } catch(MissingArgumentException e) {
        assertEquals("option missing an argument", "k", e.getOption().getOpt());
    }
}
项目:mesfavoris    文件:BugsTest.java   
@Test
public void test13425() throws Exception
{
    Options options = new Options();
    Option oldpass = OptionBuilder.withLongOpt( "old-password" )
        .withDescription( "Use this option to specify the old password" )
        .hasArg()
        .create( 'o' );
    Option newpass = OptionBuilder.withLongOpt( "new-password" )
        .withDescription( "Use this option to specify the new password" )
        .hasArg()
        .create( 'n' );

    String[] args = { 
        "-o", 
        "-n", 
        "newpassword" 
    };

    options.addOption( oldpass );
    options.addOption( newpass );

    Parser parser = new PosixParser();

    try {
        parser.parse( options, args );
        fail( "MissingArgumentException not caught." );
    } catch( MissingArgumentException expected ) {
    }
}
项目:mesfavoris    文件:BugCLI71Test.java   
@Test
public void testLackOfError() throws Exception {
    String[] args = new String[] { "-k", "-a",  "Caesar" };
    try {
        parser.parse( options, args);
        fail("MissingArgumentException expected");
    } catch(MissingArgumentException e) {
        assertEquals("option missing an argument", "k", e.getOption().getOpt());
    }
}
项目:mesfavoris    文件:BugsTest.java   
@Test
public void test13425() throws Exception
{
    Options options = new Options();
    Option oldpass = OptionBuilder.withLongOpt( "old-password" )
        .withDescription( "Use this option to specify the old password" )
        .hasArg()
        .create( 'o' );
    Option newpass = OptionBuilder.withLongOpt( "new-password" )
        .withDescription( "Use this option to specify the new password" )
        .hasArg()
        .create( 'n' );

    String[] args = { 
        "-o", 
        "-n", 
        "newpassword" 
    };

    options.addOption( oldpass );
    options.addOption( newpass );

    Parser parser = new PosixParser();

    try {
        parser.parse( options, args );
        fail( "MissingArgumentException not caught." );
    } catch( MissingArgumentException expected ) {
    }
}
项目:mesfavoris    文件:BugCLI71Test.java   
@Test
public void testLackOfError() throws Exception {
    String[] args = new String[] { "-k", "-a",  "Caesar" };
    try {
        parser.parse( options, args);
        fail("MissingArgumentException expected");
    } catch(MissingArgumentException e) {
        assertEquals("option missing an argument", "k", e.getOption().getOpt());
    }
}
项目:mesfavoris    文件:BugsTest.java   
@Test
public void test13425() throws Exception
{
    Options options = new Options();
    Option oldpass = OptionBuilder.withLongOpt( "old-password" )
        .withDescription( "Use this option to specify the old password" )
        .hasArg()
        .create( 'o' );
    Option newpass = OptionBuilder.withLongOpt( "new-password" )
        .withDescription( "Use this option to specify the new password" )
        .hasArg()
        .create( 'n' );

    String[] args = { 
        "-o", 
        "-n", 
        "newpassword" 
    };

    options.addOption( oldpass );
    options.addOption( newpass );

    Parser parser = new PosixParser();

    try {
        parser.parse( options, args );
        fail( "MissingArgumentException not caught." );
    } catch( MissingArgumentException expected ) {
    }
}
项目:hadoop-2.6.0-cdh5.4.3    文件:QueueCLI.java   
@Override
public int run(String[] args) throws Exception {
  Options opts = new Options();

  opts.addOption(STATUS_CMD, true,
      "List queue information about given queue.");
  opts.addOption(HELP_CMD, false, "Displays help for all commands.");
  opts.getOption(STATUS_CMD).setArgName("Queue Name");

  CommandLine cliParser = null;
  try {
    cliParser = new GnuParser().parse(opts, args);
  } catch (MissingArgumentException ex) {
    sysout.println("Missing argument for options");
    printUsage(opts);
    return -1;
  }

  if (cliParser.hasOption(STATUS_CMD)) {
    if (args.length != 2) {
      printUsage(opts);
      return -1;
    }
    return listQueue(cliParser.getOptionValue(STATUS_CMD));
  } else if (cliParser.hasOption(HELP_CMD)) {
    printUsage(opts);
    return 0;
  } else {
    syserr.println("Invalid Command Usage : ");
    printUsage(opts);
    return -1;
  }
}
项目:herd    文件:ArgumentParserTest.java   
@Test(expected = MissingArgumentException.class)
public void testParseArgumentsMissingArgumentException() throws ParseException
{
    ArgumentParser argParser = new ArgumentParser("");
    argParser.addArgument("a", "some_optional_parameter", true, "Some optional parameter with an argument", false);
    argParser.parseArguments(new String[] {"-a"});
}
项目:mesos-kibana    文件:SchedulerConfigurationTest.java   
/**
 * Tests if not passing in a zookeeper url causes parseLaunchArguments to fail
 */
@Test(expected = MissingArgumentException.class)
public void handleArguments_zookeeperRequired() throws Exception {
    String apiPort = "9001";
    String elasticSearch = "myElasticSearch2:9200";
    String args = " -p " + apiPort + " -es " + elasticSearch;
    SchedulerConfiguration config = new SchedulerConfiguration();
    config.parseLaunchArguments(args.split(" "));
}
项目:hops    文件:RMAdminCLI.java   
private int handleAddToClusterNodeLabels(String[] args, String cmd,
    boolean isHAEnabled) throws IOException, YarnException, ParseException {
  Options opts = new Options();
  opts.addOption("addToClusterNodeLabels", true,
      "Add to cluster node labels.");
  opts.addOption("directlyAccessNodeLabelStore", false,
      "Directly access node label store.");
  int exitCode = -1;
  CommandLine cliParser = null;
  try {
    cliParser = new GnuParser().parse(opts, args);
  } catch (MissingArgumentException ex) {
    System.err.println(NO_LABEL_ERR_MSG);
    printUsage(args[0], isHAEnabled);
    return exitCode;
  }

  List<NodeLabel> labels = buildNodeLabelsFromStr(
      cliParser.getOptionValue("addToClusterNodeLabels"));
  if (cliParser.hasOption("directlyAccessNodeLabelStore")) {
    getNodeLabelManagerInstance(getConf()).addToCluserNodeLabels(labels);
  } else {
    ResourceManagerAdministrationProtocol adminProtocol =
        createAdminProtocol();
    AddToClusterNodeLabelsRequest request =
        AddToClusterNodeLabelsRequest.newInstance(labels);
    adminProtocol.addToClusterNodeLabels(request);
  }
  return 0;
}
项目:hops    文件:RMAdminCLI.java   
private int handleRemoveFromClusterNodeLabels(String[] args, String cmd,
    boolean isHAEnabled) throws IOException, YarnException, ParseException {
  Options opts = new Options();
  opts.addOption("removeFromClusterNodeLabels", true,
      "Remove From cluster node labels.");
  opts.addOption("directlyAccessNodeLabelStore", false,
      "Directly access node label store.");
  int exitCode = -1;
  CommandLine cliParser = null;
  try {
    cliParser = new GnuParser().parse(opts, args);
  } catch (MissingArgumentException ex) {
    System.err.println(NO_LABEL_ERR_MSG);
    printUsage(args[0], isHAEnabled);
    return exitCode;
  }

  Set<String> labels = buildNodeLabelNamesFromStr(
      cliParser.getOptionValue("removeFromClusterNodeLabels"));
  if (cliParser.hasOption("directlyAccessNodeLabelStore")) {
    getNodeLabelManagerInstance(getConf()).removeFromClusterNodeLabels(
        labels);
  } else {
    ResourceManagerAdministrationProtocol adminProtocol =
        createAdminProtocol();
    RemoveFromClusterNodeLabelsRequest request =
        RemoveFromClusterNodeLabelsRequest.newInstance(labels);
    adminProtocol.removeFromClusterNodeLabels(request);
  }

  return 0;
}