io.airlift.airline.Cli Java Examples

The following examples show how to use io.airlift.airline.Cli. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CloudExplorerLiveTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
protected void call(InputStream instream, String... args) throws Exception {
    ByteArrayOutputStream stdoutStream = new ByteArrayOutputStream();
    ByteArrayOutputStream stderrStream = new ByteArrayOutputStream();
    
    Cli<BrooklynCommand> parser = new Main().cliBuilder().build();
    
    BrooklynCommand command = parser.parse(args);
    
    InputStream origIn = System.in;
    PrintStream origOut = System.out;
    PrintStream origErr = System.err;
    try {
        System.setIn(instream);
        System.setOut(new PrintStream(stdoutStream));
        System.setErr(new PrintStream(stderrStream));

        command.call();
    } finally {
        System.setIn(origIn);
        System.setOut(origOut);
        System.setOut(origErr);
        stdout = new String(stdoutStream.toByteArray());
        stderr = new String(stderrStream.toByteArray());
    }
}
 
Example #2
Source File: Launcher.java    From presto with Apache License 2.0 6 votes vote down vote up
protected void run(String[] args)
{
    CommandFactory<Runnable> commandFactory = new ExtensionsProvidingCommandFactory<>(getExtensions());
    Cli.CliBuilder<Runnable> cli = Cli.<Runnable>builder("launcher")
            .withCommandFactory(commandFactory) // TODO ignored
            .withDefaultCommand(Help.class)
            .withCommand(Help.class);

    cli
            .withGroup("env")
            .withDefaultCommand(Help.class) // TODO should be group aware https://github.com/airlift/airline/issues/72? Otherwise it's required until https://github.com/airlift/airline/pull/71
            .withCommand(EnvironmentUp.class)
            .withCommand(EnvironmentDown.class)
            .withCommand(EnvironmentList.class);

    cli
            .withGroup("test")
            .withDefaultCommand(Help.class) // TODO should be group aware https://github.com/airlift/airline/issues/72? Otherwise it's required until https://github.com/airlift/airline/pull/71
            .withCommand(TestRun.class);

    cli.build().parse(commandFactory, args).run();
}
 
Example #3
Source File: StageLibCli.java    From datacollector with Apache License 2.0 6 votes vote down vote up
boolean doMain(String[] args) {
  Cli.CliBuilder<Runnable> builder = Cli.<Runnable>builder("streamsets stagelib-cli vault-credentialstore")
      .withDescription("StreamSets Data Collector Vault Credential Store CLI")
      .withDefaultCommand(Help.class)
      .withCommands(Help.class, VaultShowIdCommand.class);

  try {
    builder.build().parse(args).run();
    return true;
  } catch (Exception ex) {
    if(Arrays.asList(args).contains("--stack")) {
      ex.printStackTrace(System.err);
    } else {
      System.err.println(ex.getMessage());
    }
    return false;
  }
}
 
Example #4
Source File: MetadataGeneratorMain.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static void main(String[] args) {
  System.setProperty("sdc.conf.dir", System.getProperty("user.dir"));
  Configuration.setFileRefsBaseDir(new File(System.getProperty("user.dir")));

  Cli.CliBuilder<Runnable> cliBuilder = Cli.
      <Runnable>builder("streamsets metadata-generator")
      .withDescription("Generates pipeline executor and stage libraries metadata for StreamSets Cloud")
      .withDefaultCommand(Help.class)
      .withCommands(
          Help.class,
          ExecutorMetadataCommand.class,
          StageLibMetadataCommand.class
      );

  Runnable runnable = cliBuilder.build().parse(args);
  runnable.run();
}
 
Example #5
Source File: JavaKeystoreCredentialStoreCli.java    From datacollector with Apache License 2.0 6 votes vote down vote up
boolean doMain(String[] args) {
  Cli.CliBuilder<Runnable> builder = Cli.<Runnable>builder("streamsets stagelib-cli jks-credentialstore")
      .withDescription("StreamSets Data Collector Java Keystore Credential Store CLI")
      .withDefaultCommand(Help.class)
      .withCommands(
          Help.class,
          ListCredentialsCommand.class,
          AddCredentialCommand.class,
          DeleteCredentialCommand.class
      );

  try {
    builder.build().parse(args).run();
    return true;
  } catch (Exception ex) {
    if(Arrays.asList(args).contains("--stack")) {
      ex.printStackTrace(System.err);
    } else {
      System.err.println(ex.getMessage());
    }
    return false;
  }
}
 
Example #6
Source File: GenerateTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("SameParameterValue")
private void setupAndRunTest(String specFlag, final String spec, String langFlag,
                             final String lang, String outputDirFlag, final String outputDir,
                             boolean configuratorFromFile, final String configFile, String... additionalParameters) {
    final String[] commonArgs =
            {"generate", langFlag, lang, outputDirFlag, outputDir, specFlag, spec};

    String[] argsToUse = ArrayUtils.addAll(commonArgs, additionalParameters);

    Cli.CliBuilder<Runnable> builder =
            Cli.<Runnable>builder("openapi-generator-cli")
                    .withCommands(Generate.class);

    Generate generate = (Generate) builder.build().parse(argsToUse);

    generate.configurator = configurator;
    generate.generator = generator;

    try {
        generate.run();
    } finally {
        verify(configurator).setInputSpec(spec);
        verify(configurator).setGeneratorName(lang);
        verify(configurator).setOutputDir(outputDir);
    }
}
 
Example #7
Source File: Runner.java    From grpc-proxy with Apache License 2.0 6 votes vote down vote up
private static Cli<Runnable> cli() {
  final CliBuilder<Runnable> builder = Cli.builder("grpc-proxy");

  builder
      .withDescription("A set of example services for testing a gRPC proxy service.")
      .withDefaultCommand(Help.class)
      .withCommand(Help.class)
      .withCommand(HelloWorldClient.Cmd.class);

  builder
      .withGroup("server")
      .withDescription("Run a server")
      .withDefaultCommand(Help.class)
      .withCommand(Help.class)
      .withCommand(ProxyRpcServer.Cmd.class)
      .withCommand(LegacyHttpServer.Cmd.class)
      .withCommand(HelloWorldServer.Cmd.class);

  return builder.build();
}
 
Example #8
Source File: CliTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testCliSystemPropertyDefines() {
    Cli<BrooklynCommand> cli = buildCli();
    BrooklynCommand command0 = cli.parse(
        "-Dorg.apache.brooklyn.cli.CliTest.sample1=foo",
        "-Dorg.apache.brooklyn.cli.CliTest.sample2=bar",
        "launch", 
        "-Dorg.apache.brooklyn.cli.CliTest.sample3=baz"
        );
    assertTrue(command0 instanceof LaunchCommand);
    LaunchCommand command = (LaunchCommand) command0;
    assertEquals(command.getDefines().size(), 3, 
        "Command is: "+command);
    assertTrue(command.getDefines().get(0).equals("org.apache.brooklyn.cli.CliTest.sample1=foo"),  
        "Command is: "+command);
    assertTrue(command.getDefines().get(2).equals("org.apache.brooklyn.cli.CliTest.sample3=baz"), 
        "Command is: "+command);
    assertEquals(command.getDefinesAsMap().get("org.apache.brooklyn.cli.CliTest.sample3"), "baz",
        "Command is: "+command);
}
 
Example #9
Source File: StreamsetsCredentialStoreCli.java    From datacollector with Apache License 2.0 6 votes vote down vote up
boolean doMain(String[] args) {
  Cli.CliBuilder<Runnable> builder = Cli.<Runnable>builder("streamsets stagelib-cli streamsets-credentialstore")
      .withDescription("StreamSets Data Collector Streamsets Credential Store CLI")
      .withDefaultCommand(Help.class)
      .withCommands(
          Help.class,
          DefaultSshKeyInfoCommand.class
      );

  try {
    builder.build().parse(args).run();
    return true;
  } catch (Exception ex) {
    if(Arrays.asList(args).contains("--stack")) {
      ex.printStackTrace(System.err);
    } else {
      System.err.println(ex.getMessage());
    }
    return false;
  }
}
 
Example #10
Source File: SchCli.java    From datacollector with Apache License 2.0 6 votes vote down vote up
boolean doMain(String[] args) {
  Cli.CliBuilder<Runnable> builder = Cli.<Runnable>builder("streamsets sch")
      .withDescription("StreamSets Data Collector CLI interface for Control Hub")
      .withDefaultCommand(Help.class)
      .withCommands(
        Help.class,
        RegisterCommand.class,
        UnregisterCommand.class
      );

  try {
    builder.build().parse(args).run();
    return true;
  } catch (Exception ex) {
    System.err.println(ex.getMessage());
    return false;
  }
}
 
Example #11
Source File: CliTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testLaunchWillStartAppWhenGivenImpl() throws Exception {
    Cli<BrooklynCommand> cli = buildCli();
    BrooklynCommand command = cli.parse("launch", "--noConsole", "--app", ExampleApp.class.getName(), "--location", "localhost");
    submitCommandAndAssertRunnableSucceeds(command, new Runnable() {
            @Override
            public void run() {
                assertTrue(exampleAppConstructed);
                assertTrue(exampleAppRunning);
            }
        });
}
 
Example #12
Source File: CliTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testLaunchWritesOutApacheBrooklyn() throws Exception {
    InputStream origIn = System.in;
    PrintStream origOut = System.out;
    try {
        InputStream stdin = new ByteArrayInputStream("".getBytes());
        System.setIn(stdin);

        final ByteArrayOutputStream stdoutBytes = new ByteArrayOutputStream();
        PrintStream stdout = new PrintStream(stdoutBytes);
        System.setOut(stdout);

        Cli<BrooklynCommand> cli = buildCli();
        BrooklynCommand command = cli.parse("launch", "--noConsole");
        submitCommandAndAssertRunnableSucceeds(command, new Runnable() {
                @Override
                public void run() {
                    String actualStdout = new String(stdoutBytes.toByteArray());
                    assertTrue(actualStdout.contains("Apache Brooklyn"), "stdout="+actualStdout);
                }
            });
    
    } finally {
        System.setIn(origIn);
        System.setOut(origOut);
    }
}
 
Example #13
Source File: PrestoVerifier.java    From presto with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args)
{
    Cli<Runnable> verifierParser = Cli.<Runnable>builder("verifier")
            .withDescription("Presto Verifier")
            .withDefaultCommand(Help.class)
            .withCommand(Help.class)
            .withCommand(VerifyCommand.class)
            .build();

    verifierParser.parse(args).run();
}
 
Example #14
Source File: CliTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testLaunchStartsYamlApp() throws Exception {
    Cli<BrooklynCommand> cli = buildCli();
    BrooklynCommand command = cli.parse("launch", "--noConsole", "--app", "example-app-no-location.yaml", "--location", "localhost");
    submitCommandAndAssertRunnableSucceeds(command, new Runnable() {
            @Override
            public void run() {
                assertTrue(exampleEntityRunning);
            }
        });
}
 
Example #15
Source File: CliTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testLaunchStartsYamlAppWithCommandLineLocation() throws Exception {
    Cli<BrooklynCommand> cli = buildCli();
    BrooklynCommand command = cli.parse("launch", "--noConsole", "--app", "example-app-no-location.yaml", "--location", "localhost:(name=testLocalhost)");
    submitCommandAndAssertRunnableSucceeds(command, new Runnable() {
            @Override
            public void run() {
                assertTrue(exampleEntityRunning);
                assertTrue(Iterables.getOnlyElement(exampleEntity.getApplication().getLocations()).getDisplayName().equals("testLocalhost"));
            }
        });
}
 
Example #16
Source File: CliTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testLaunchStartsYamlAppWithYamlAppLocation() throws Exception {
    Cli<BrooklynCommand> cli = buildCli();
    BrooklynCommand command = cli.parse("launch", "--noConsole", "--app", "example-app-app-location.yaml");
    submitCommandAndAssertRunnableSucceeds(command, new Runnable() {
            @Override
            public void run() {
                assertTrue(exampleEntityRunning);
                assertTrue(Iterables.getOnlyElement(exampleEntity.getApplication().getLocations()).getDisplayName().equals("appLocalhost"));
            }
        });
}
 
Example #17
Source File: CliTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testLaunchStartsYamlAppWithYamlAndAppCliLocation() throws Exception {
    Cli<BrooklynCommand> cli = buildCli();
    BrooklynCommand command = cli.parse("launch", "--noConsole", "--app", "example-app-app-location.yaml", "--location", "localhost");
    submitCommandAndAssertRunnableSucceeds(command, new Runnable() {
            @Override
            public void run() {
                assertTrue(exampleEntityRunning);
                assertTrue(Iterables.getFirst(exampleEntity.getApplication().getLocations(), null).getDisplayName().equals("appLocalhost"));
            }
        });
}
 
Example #18
Source File: CliTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testGeneratePasswordCommandParsed() throws Exception {
    Cli<BrooklynCommand> cli = buildCli();
    BrooklynCommand command = cli.parse("generate-password", "--user", "myname");
    
    assertTrue(command instanceof GeneratePasswordCommand);
}
 
Example #19
Source File: Main.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** method intended for overriding when a different {@link Cli} is desired,
 * or when the subclass wishes to change any of the arguments */
@SuppressWarnings("unchecked")
@Override
protected CliBuilder<BrooklynCommand> cliBuilder() {
    CliBuilder<BrooklynCommand> builder = Cli.<BrooklynCommand>builder(cliScriptName())
            .withDescription("Brooklyn Management Service")
            .withDefaultCommand(cliDefaultInfoCommand())
            .withCommands(
                    HelpCommand.class,
                    cliInfoCommand(),
                    GeneratePasswordCommand.class,
                    CleanOrphanedStateCommand.class,
                    CopyStateCommand.class,
                    ListAllCommand.class,
                    cliLaunchCommand()
            );

    builder.withGroup("cloud-compute")
            .withDescription("Access compute details of a given cloud")
            .withDefaultCommand(HelpCommand.class)
            .withCommands(
                    ComputeListImagesCommand.class,
                    ComputeListHardwareProfilesCommand.class,
                    ComputeListInstancesCommand.class,
                    ComputeGetImageCommand.class,
                    ComputeDefaultTemplateCommand.class,
                    ComputeTerminateInstancesCommand.class);

    builder.withGroup("cloud-blobstore")
            .withDescription("Access blobstore details of a given cloud")
            .withDefaultCommand(HelpCommand.class)
            .withCommands(
                    BlobstoreListContainersCommand.class, 
                    BlobstoreListContainerCommand.class,
                    BlobstoreGetBlobCommand.class);

    return builder;
}
 
Example #20
Source File: Artemis.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public static Object execute(boolean inputEnabled, File artemisHome, File artemisInstance, ActionContext context, String... args) throws Exception {

      if (inputEnabled) {
         InputAbstract.enableInput();
      }
      try {
         return internalExecute(artemisHome, artemisInstance, args, context);
      } catch (ConfigurationException configException) {
         System.err.println(configException.getMessage());
         System.out.println();
         System.out.println("Configuration should be specified as 'scheme:location'. Default configuration is 'xml:${ARTEMIS_INSTANCE}/etc/bootstrap.xml'");
         return configException;
      } catch (CLIException cliException) {
         System.err.println(cliException.getMessage());
         return cliException;
      } catch (NullPointerException e) {
         // Yeah.. I really meant System.err..
         // this is the CLI and System.out and System.err are common places for interacting with the user
         // this is a programming error that must be visualized and corrected
         e.printStackTrace();
         return e;
      } catch (RuntimeException | InvalidOptionsError re) {
         System.err.println(re.getMessage());
         System.out.println();

         Cli<Action> parser = builder(null).build();

         parser.parse("help").execute(context);
         return re;
      }
   }
 
Example #21
Source File: ToolkitMain.java    From servicecomb-toolkit with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static void main(String[] args) {

  initialProjectVersion();

  String scriptName = System.getProperty("script.name");
  Cli.CliBuilder<Runnable> builder = null;
  if (StringUtils.isNotEmpty(scriptName)) {
    builder = Cli.builder(scriptName);
  } else {
    builder = Cli.builder("java -jar cli-" + projectVersion + ".jar");
  }

  builder.withDescription("Microservice development toolkit(version " + projectVersion
      + "). ");
  builder.withDefaultCommand(Help.class);
  builder.withCommands(
      CodeGenerate.class, DocGenerate.class,
      CheckStyle.class, CheckStyleAbbr.class,
      CheckCompatibility.class, CheckCompatibilityAbbr.class,
      Help.class
  );
  try {
    Runnable cmd = builder.build().parse(args);

    cmd.run();
  } catch (ValidationFailedException ex) {
    ex.printStackTrace(System.err);
    System.exit(1);
  }
}
 
Example #22
Source File: SwaggerCodegen.java    From TypeScript-Microservices with MIT License 5 votes vote down vote up
public static void main(String[] args) {
    String version = Version.readVersionFromResources();
    @SuppressWarnings("unchecked")
    Cli.CliBuilder<Runnable> builder =
            Cli.<Runnable>builder("swagger-codegen-cli")
                    .withDescription(
                            String.format(
                                    "Swagger code generator CLI (version %s). More info on swagger.io",
                                    version))
                    .withDefaultCommand(Langs.class)
                    .withCommands(Generate.class, Meta.class, Langs.class, Help.class,
                            ConfigHelp.class, Validate.class, Version.class);

    builder.build().parse(args).run();
}
 
Example #23
Source File: AuthorTemplateTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test
public void smokeTestAuthorTemplateCommand(){
    Cli.CliBuilder<Runnable> builder = createBuilder();
    String[] arguments = new String[]{
            "author",
            "template",
            "-g",
            "java",
            "--library",
            "webclient",
            "--output",
            outputDirectory.toAbsolutePath().toString()
    };
    builder.build().parse(arguments).run();

    // spot check root files
    Assert.assertTrue(Files.exists(outputDirectory.resolve("ApiClient.mustache")));
    Assert.assertTrue(Files.exists(outputDirectory.resolve("api_doc.mustache")));
    Assert.assertTrue(Files.exists(outputDirectory.resolve("pom.mustache")));

    Assert.assertTrue(Files.exists(outputDirectory.resolve("auth/OAuth.mustache")));

    // check libraries files and subdirectories
    Assert.assertTrue(Files.exists(outputDirectory.resolve("libraries/webclient/ApiClient.mustache")));
    Assert.assertTrue(Files.exists(outputDirectory.resolve("libraries/webclient/pom.mustache")));
    Assert.assertTrue(Files.exists(outputDirectory.resolve("libraries/webclient/auth/OAuth.mustache")));

    // check non-existence of unselected libraries
    Assert.assertFalse(Files.exists(outputDirectory.resolve("libraries/feign/build.gradle.mustache")));
    Assert.assertFalse(Files.exists(outputDirectory.resolve("libraries/feign/auth/OAuth.mustache")));

    Assert.assertFalse(Files.exists(outputDirectory.resolve("libraries/jersey2/api_doc.mustache")));
    Assert.assertFalse(Files.exists(outputDirectory.resolve("libraries/jersey2/auth/HttpBasicAuth.mustache")));

    Assert.assertFalse(Files.exists(outputDirectory.resolve("libraries/okhttp-gson/api.mustache")));
    Assert.assertFalse(Files.exists(outputDirectory.resolve("libraries/okhttp-gson/auth/RetryingOAuth.mustache")));
}
 
Example #24
Source File: CommandLineTool.java    From incubator-taverna-language with Apache License 2.0 5 votes vote down vote up
private static Cli<TvnLangTool> parser() {
	CliBuilder<TvnLangTool> build = Cli.<TvnLangTool> builder("tavlang")
			.withDescription("Convert, manage workflows")
			.withDefaultCommand(HelpCommand.class)
			.withCommand(CommandConvert.class) // Conversion
			.withCommand(HelpCommand.class) // Help
			.withCommand(CommandInspect.class) // Inspect
			.withCommand(CommandValidate.class) // Validate
			.withCommand(CommandVersion.class) // Version
			.withCommand(CommandStat.class); // Statistics

	return build.build();
}
 
Example #25
Source File: AlfrescoCLI.java    From alfresco-client-sdk with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args)
{
    Cli.CliBuilder<Runnable> builder = Cli.<Runnable> builder("alfclient")
            .withDescription("Sample Alfresco Command Line Client").withDefaultCommand(Help.class)
            .withCommands(Help.class, AlfrescoCommands.infoUser.class)
            .withCommands(Help.class, AlfrescoCommands.listRoot.class);

    Cli<Runnable> gitParser = builder.build();

    gitParser.parse(args).run();
}
 
Example #26
Source File: AuthorTemplateTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
private Cli.CliBuilder<Runnable> createBuilder(){
    Cli.CliBuilder<Runnable> builder = new Cli.CliBuilder<>("openapi-generator-cli");

    builder.withGroup("author")
            .withDescription("Utilities for authoring generators or customizing templates.")
            .withDefaultCommand(HelpCommand.class)
            .withCommands(AuthorTemplate.class);

    return builder;
}
 
Example #27
Source File: Denominator.java    From denominator with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
  CliBuilder<Runnable> builder = Cli.<Runnable>builder("denominator")
      .withDescription("Denominator: Portable control of DNS clouds")
      .withDefaultCommand(Help.class)
      .withCommand(Help.class)
      .withCommand(PrintVersion.class)
      .withCommand(ListProviders.class);

  builder.withGroup("zone")
      .withDescription("manage zones")
      .withDefaultCommand(ZoneList.class)
      .withCommand(ZoneList.class)
      .withCommand(ZoneAdd.class)
      .withCommand(ZoneUpdate.class)
      .withCommand(ZoneDelete.class);

  builder.withGroup("record")
      .withDescription("manage resource record sets in a zone")
      .withDefaultCommand(ResourceRecordSetList.class)
      .withCommand(ResourceRecordSetList.class)
      .withCommand(ResourceRecordSetGet.class)
      .withCommand(ResourceRecordSetAdd.class)
      .withCommand(ResourceRecordSetApplyTTL.class)
      .withCommand(ResourceRecordSetReplace.class)
      .withCommand(ResourceRecordSetRemove.class)
      .withCommand(ResourceRecordSetDelete.class);

  builder.withGroup("geo")
      .withDescription("manage geo resource record sets in a zone")
      .withDefaultCommand(GeoResourceRecordSetList.class)
      .withCommand(GeoTypeList.class)
      .withCommand(GeoRegionList.class)
      .withCommand(GeoResourceRecordSetList.class)
      .withCommand(GeoResourceRecordSetGet.class)
      .withCommand(GeoResourceRecordSetApplyTTL.class)
      .withCommand(GeoResourceRecordAddRegions.class);

  Cli<Runnable> denominatorParser = builder.build();
  try {
    denominatorParser.parse(args).run();
  } catch (RuntimeException e) {
    if (e instanceof NullPointerException) {
      e.printStackTrace();
    }
    System.err.println(";; error: " + e.getMessage());
    System.exit(1);
  }
  System.exit(0);
}
 
Example #28
Source File: CliTest.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
protected List<String> runCommand(Cli<BrooklynCommand> cli, Iterable<String> args, String input) throws Exception {
    final BrooklynCommand command = cli.parse(args);
    
    final AtomicReference<Exception> exception = new AtomicReference<Exception>();
    Thread t= new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                command.call();
            } catch (Exception e) {
                exception.set(e);
                throw Exceptions.propagate(e);
            }
        }});
    
    InputStream origIn = System.in;
    PrintStream origOut = System.out;
    try {
        InputStream stdin = new ByteArrayInputStream(input.getBytes());
        System.setIn(stdin);

        ByteArrayOutputStream stdoutBytes = new ByteArrayOutputStream();
        PrintStream stdout = new PrintStream(stdoutBytes);
        System.setOut(stdout);

        t.start();

        t.join(10*1000);
        assertFalse(t.isAlive());
        
        if (exception.get() != null) {
            throw new ExecutionException(exception.get());
        }
        
        return ImmutableList.copyOf(Splitter.on(Pattern.compile("\r?\n")).split(new String(stdoutBytes.toByteArray())));
    } finally {
        System.setIn(origIn);
        System.setOut(origOut);
        t.interrupt();
    }
}
 
Example #29
Source File: CliTest.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
protected List<String> runCommand(Iterable<String> args, String input) throws Exception {
    Cli<BrooklynCommand> cli = buildCli();
    return runCommand(cli, args, input);
}
 
Example #30
Source File: StrongboxCLI.java    From strongbox with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
    CliBuilder<Runnable> builder = Cli.<Runnable>builder("strongbox")
            .withDescription("Strongbox")
            .withDefaultCommand(Help.class)
            .withCommands(Help.class);

    builder.withCommand(Global.CustomHelp.class);
    builder.withCommand(Global.Version.class);
    builder.withCommand(Global.VersionOption.class);

    builder.withGroup("group")
            .withDescription("Manage Secret Groups")
            .withDefaultCommand(Group.GroupHelp.class)
            .withCommands(Group.Create.class, Group.List.class, Group.Info.class, Group.Delete.class, Group.AttachAdmin.class, Group.DetachAdmin.class, Group.AttachReadOnly.class, Group.DetachReadOnly.class, Group.BackupCommand.class, Group.RestoreCommand.class, Group.MigrateCommand.class);

    builder.withGroup("secret")
            .withDescription("Manage Secrets for a Secret Group")
            .withDefaultCommand(Secret.SecretHelp.class)
            .withCommands(Secret.Create.class, Secret.AddVersion.class, Secret.Get.class, Secret.GetLatest.class, Secret.Delete.class, Secret.ListNames.class, Secret.ListVersions.class, Secret.Update.class);

    builder.withCommand(Gui.OpenGui.class);

    Cli<Runnable> parser = builder.build();
    globalMetadata = parser.getMetadata();

    try {
        parser.parse(args).run();
    } catch (ParseArgumentsUnexpectedException exception) {
        Optional<String> globalOptions = exception.getUnparsedInput().stream()
                .filter(Global.Option::contains)
                .findAny();

        System.err.println(exception.getMessage());
        if (globalOptions.isPresent()) {
            System.err.println(String.format(
                    "Please note: global options like '%s' must be placed before the command,\n" +
                    "  e.g. 'strongbox --global-option [global-option-value] <command> [<args>]'\n" +
                    "  see 'strongbox help <command>' for more information about ordering.",
                    globalOptions.get()));
        } else {
            System.err.println("See 'strongbox help'.");
        }

        System.exit(1);
    } catch (Exception e) {
        boolean stacktrace = stacktraceIsSet(parser.getMetadata(), args);

        if (!stacktrace) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
        throw e;
    }
}