@SuppressWarnings("deprecation") private void verifyReturnValueForBuiltInHandlers(CommandLineFactory factory, Object expected, String[] args) { IParseResultHandler[] handlers = new IParseResultHandler[] { new RunFirst(), new RunLast(), new RunAll() }; PrintStream out = new PrintStream(new ByteArrayOutputStream()); for (IParseResultHandler handler : handlers) { String descr = handler.getClass().getSimpleName(); Object actual = factory.create().parseWithHandler(handler, out, args); assertEquals(descr + ": return value", expected, actual); } }
private void verifyReturnValueForBuiltInHandlers2(CommandLineFactory factory, Object expected, String[] args) { IParseResultHandler2<?>[] handlers = new IParseResultHandler2[] { new RunFirst(), new RunLast(), new RunAll() }; PrintStream out = new PrintStream(new ByteArrayOutputStream()); for (IParseResultHandler2<?> handler : handlers) { String descr = handler.getClass().getSimpleName(); Object actual = factory.create().parseWithHandler(handler, args); assertEquals(descr + ": return value", expected, actual); } } @Test
Method method = candidates.get(0); CommandLine cmd = new CommandLine(method); List<Object> list = cmd.parseWithHandlers(new RunLast().useOut(out).useAnsi(ansi), new DefaultExceptionHandler<List<Object>>().useErr(err).useAnsi(ansi), args); return list == null ? null : list.get(0);
/** * Generates a bash completion script for the specified command class. * @param args command line options. Specify at least the {@code commandLineFQCN} mandatory parameter, which is * the fully qualified class name of the annotated {@code @Command} class to generate a completion script for. * Other parameters are optional. Specify {@code -h} to see details on the available options. */ public static void main(String... args) { new CommandLine(new App()).parseWithHandlers( new CommandLine.RunLast().andExit(EXIT_CODE_SUCCESS), CommandLine.defaultExceptionHandler().andExit(EXIT_CODE_INVALID_INPUT), args); }
List<Object> results = cmd.parseWithHandlers(new RunLast().useOut(out).useAnsi(ansi), new DefaultExceptionHandler<List<Object>>().useErr(err).useAnsi(ansi), args); @SuppressWarnings("unchecked") T result = (results == null || results.isEmpty()) ? null : (T) results.get(0); return result;
List<Object> results = cmd.parseWithHandlers(new RunLast().useOut(out).useAnsi(ansi), new DefaultExceptionHandler<List<Object>>().useErr(err).useAnsi(ansi), args); @SuppressWarnings("unchecked") T result = (results == null || results.isEmpty()) ? null : (T) results.get(0); return result;
cmd.parseWithHandlers(new RunLast().useOut(out).useAnsi(ansi), new DefaultExceptionHandler<List<Object>>().useErr(err).useAnsi(ansi), args);
cmd.parseWithHandlers(new RunLast().useOut(out).useAnsi(ansi), new DefaultExceptionHandler<List<Object>>().useErr(err).useAnsi(ansi), args);
@Test public void testUnannotatedCommandWithMixin() throws Exception { Method m = CommandLine.getCommandMethods(UnannotatedClassWithMixinAndOptionsAndPositionals.class, "sum").get(0); CommandLine commandLine = new CommandLine(m); List<CommandLine> parsed = commandLine.parse("-y foo -y bar -a 7 -b 11 13 42".split(" ")); assertEquals(1, parsed.size()); // get method args Object[] methodArgValues = parsed.get(0).getCommandSpec().argValues(); assertNotNull(methodArgValues); // verify args String[] arg0 = (String[]) methodArgValues[0]; assertArrayEquals(new String[] {"foo", "bar"}, arg0); SomeMixin arg1 = (SomeMixin) methodArgValues[1]; assertEquals(7, arg1.a); assertEquals(11, arg1.b); int[] arg2 = (int[]) methodArgValues[2]; assertArrayEquals(new int[] {13, 42}, arg2); // verify method is callable with args long result = (Long) m.invoke(new UnannotatedClassWithMixinAndOptionsAndPositionals(), methodArgValues); assertEquals(22, result); // verify same result with result handler List<Object> results = new RunLast().handleParseResult(parsed, System.out, CommandLine.Help.Ansi.OFF); assertEquals(1, results.size()); assertEquals(22L, results.get(0)); }
@Test public void testAnnotatedSubcommandWithDoubleMixin() throws Exception { AnnotatedClassWithMixinParameters command = new AnnotatedClassWithMixinParameters(); CommandLine commandLine = new CommandLine(command); List<CommandLine> parsed = commandLine.parse("-a 3 -b 5 sum -y foo -y bar -a 7 -b 11 13 42".split(" ")); assertEquals(2, parsed.size()); // get method args Object[] methodArgValues = parsed.get(1).getCommandSpec().argValues(); assertNotNull(methodArgValues); // verify args String[] arg0 = (String[]) methodArgValues[0]; assertArrayEquals(new String[] {"foo", "bar"}, arg0); SomeMixin arg1 = (SomeMixin) methodArgValues[1]; assertEquals(7, arg1.a); assertEquals(11, arg1.b); int[] arg2 = (int[]) methodArgValues[2]; assertArrayEquals(new int[] {13, 42}, arg2); // verify method is callable with args Method m = AnnotatedClassWithMixinParameters.class.getDeclaredMethod("sum", String[].class, SomeMixin.class, int[].class); long result = (Long) m.invoke(command, methodArgValues); assertEquals(30, result); // verify same result with result handler List<Object> results = new RunLast().handleParseResult(parsed, System.out, CommandLine.Help.Ansi.OFF); assertEquals(1, results.size()); assertEquals(30L, results.get(0)); }
@Test public void testAnnotatedMethodMultipleMixinsSubcommandWithDoubleMixin() throws Exception { Method m = CommandLine.getCommandMethods(AnnotatedClassWithMultipleMixinParameters.class, "sum").get(0); CommandLine commandLine = new CommandLine(m); List<CommandLine> parsed = commandLine.parse("-a 3 -b 5 -c 7".split(" ")); assertEquals(1, parsed.size()); // get method args Object[] methodArgValues = parsed.get(0).getCommandSpec().argValues(); assertNotNull(methodArgValues); // verify args SomeMixin arg0 = (SomeMixin) methodArgValues[0]; assertEquals(3, arg0.a); assertEquals(5, arg0.b); OtherMixin arg1 = (OtherMixin) methodArgValues[1]; assertEquals(7, arg1.c); // verify method is callable with args long result = (Long) m.invoke(new AnnotatedClassWithMultipleMixinParameters(), methodArgValues); assertEquals(15, result); // verify same result with result handler List<Object> results = new RunLast().handleParseResult(parsed, System.out, CommandLine.Help.Ansi.OFF); assertEquals(1, results.size()); assertEquals(15L, results.get(0)); }
@Test public void testOptionalListParameterShouldNotRememberValuesInCommandMethods() { @Command() class TestCommand { @Command(name="method") public String methodCommand(@Parameters(arity="0..*") List<String> methodValues) { return methodValues == null ? "null" : methodValues.toString(); } } CommandLine commandLine = new CommandLine(new TestCommand()); // problematic for @Command-method @Parameters List<Object> methodFirstExecutionResultWithParametersGiven = commandLine.parseWithHandlers( new RunLast(), new DefaultExceptionHandler<List<Object>>(), new String[] {"method","arg0", "arg1"}); List<Object> methodSecondExecutionResultWithoutParameters = commandLine.parseWithHandlers( new RunLast(), new DefaultExceptionHandler<List<Object>>(), new String[] {"method"}); assertEquals("[arg0, arg1]", methodFirstExecutionResultWithParametersGiven.get(0)); // fails, still "[arg0, arg1]" assertEquals("null", methodSecondExecutionResultWithoutParameters.get(0)); }
@Test public void testParseWithHandlerRunXxxReturnsCallableResultWithSubcommand() { @Command class App implements Callable<Object> { public Object call() { return "RETURN VALUE"; } } @Command(name = "sub") class Sub implements Callable<Object> { public Object call() { return "SUB RETURN VALUE"; } } CommandLineFactory factory = new CommandLineFactory() { public CommandLine create() {return new CommandLine(new App()).addSubcommand("sub", new Sub());} }; Object actual1 = factory.create().parseWithHandler(new RunFirst(), new String[] {"sub"}); assertEquals("RunFirst: return value", Arrays.asList("RETURN VALUE"), actual1); Object actual2 = factory.create().parseWithHandler(new RunLast(), new String[] {"sub"}); assertEquals("RunLast: return value", Arrays.asList("SUB RETURN VALUE"), actual2); Object actual3 = factory.create().parseWithHandler(new RunAll(), new String[] {"sub"}); assertEquals("RunAll: return value", Arrays.asList("RETURN VALUE", "SUB RETURN VALUE"), actual3); } @Test
@Test public void testOptionalListParameterInCommandClass() { @Command() class TestCommand implements Callable<String> { @Parameters(arity="0..*") private List<String> values; public String call() throws Exception { return values == null ? "null" : values.toString(); } } // seems to be working for @Command-class @Parameters CommandLine commandLine = new CommandLine(new TestCommand()); List<Object> firstExecutionResultWithParametersGiven = commandLine.parseWithHandlers( new RunLast(), new DefaultExceptionHandler<List<Object>>(), new String[] {"arg0", "arg1"}); List<Object> secondExecutionResultWithoutParameters = commandLine.parseWithHandlers( new RunLast(), new DefaultExceptionHandler<List<Object>>(), new String[] {}); assertEquals("[arg0, arg1]", firstExecutionResultWithParametersGiven.get(0)); assertEquals("null", secondExecutionResultWithoutParameters.get(0)); }
@Test public void testParseWithHandler2RunXxxReturnsCallableResultWithSubcommand() { @Command class App implements Callable<Object> { public Object call() { return "RETURN VALUE"; } } @Command(name = "sub") class Sub implements Callable<Object> { public Object call() { return "SUB RETURN VALUE"; } } CommandLineFactory factory = new CommandLineFactory() { public CommandLine create() {return new CommandLine(new App()).addSubcommand("sub", new Sub());} }; PrintStream out = new PrintStream(new ByteArrayOutputStream()); Object actual1 = factory.create().parseWithHandler(new RunFirst(), new String[]{"sub"}); assertEquals("RunFirst: return value", Arrays.asList("RETURN VALUE"), actual1); Object actual2 = factory.create().parseWithHandler(new RunLast(), new String[]{"sub"}); assertEquals("RunLast: return value", Arrays.asList("SUB RETURN VALUE"), actual2); Object actual3 = factory.create().parseWithHandler(new RunAll(), new String[]{"sub"}); assertEquals("RunAll: return value", Arrays.asList("RETURN VALUE", "SUB RETURN VALUE"), actual3); }
@Test public void testAnnotatedMethodMultipleMixinsSubcommandWithEmptyMixin() throws Exception { Method m = CommandLine.getCommandMethods(AnnotatedClassWithMultipleEmptyParameters.class, "sum").get(0); CommandLine commandLine = new CommandLine(m); List<CommandLine> parsed = commandLine.parse("-a 3".split(" ")); assertEquals(1, parsed.size()); // get method args Object[] methodArgValues = parsed.get(0).getCommandSpec().argValues(); assertNotNull(methodArgValues); // verify args int arg0 = (Integer) methodArgValues[0]; assertEquals(3, arg0); EmptyMixin arg1 = (EmptyMixin) methodArgValues[1]; // verify method is callable with args long result = (Long) m.invoke(new AnnotatedClassWithMultipleEmptyParameters(), methodArgValues); assertEquals(3, result); // verify same result with result handler List<Object> results = new RunLast().handleParseResult(parsed, System.out, CommandLine.Help.Ansi.OFF); assertEquals(1, results.size()); assertEquals(3L, results.get(0)); }
@SuppressWarnings("deprecation") private void verifyAllFail(Factory factory, String prefix, String suffix, String[] args) { IParseResultHandler[] handlers = new IParseResultHandler[] { new RunFirst(), new RunLast(), new RunAll() }; for (IParseResultHandler handler : handlers) { String descr = handler.getClass().getSimpleName(); try { new CommandLine(factory.create()).parseWithHandler(handler, System.out, args); fail(descr + ": expected exception"); } catch (ExecutionException ex) { String actual = ex.getMessage(); assertTrue(descr + ": " + actual, actual.startsWith(prefix)); assertTrue(descr + ": " + actual, actual.endsWith(suffix)); } } }
public static void main(String[] args) { final MetaManagementService service = new MetaManagementService(); final CommandLine cmd = new CommandLine(new Tools()); cmd.addSubcommand("AddBroker", new AddBrokerCommand(service)); cmd.addSubcommand("AddDb", new AddDbCommand(service)); cmd.addSubcommand("ReplaceBroker", new ReplaceBrokerCommand(service)); cmd.addSubcommand("ListBrokers", new ListBrokersCommand(service)); cmd.addSubcommand("ListBrokerGroups", new ListBrokerGroupsCommand(service)); cmd.addSubcommand("ListSubjectRoutes", new ListSubjectRoutesCommand(service)); cmd.addSubcommand("AddSubjectBrokerGroup", new AddSubjectBrokerGroupCommand(service)); cmd.addSubcommand("RemoveSubjectBrokerGroup", new RemoveSubjectBrokerGroupCommand(service)); cmd.addSubcommand("AddNewSubject", new AddNewSubjectCommand(service)); cmd.addSubcommand("ExtendSubjectRoute", new ExtendSubjectRouteCommand(service)); cmd.addSubcommand("MarkReadonly", new MarkBrokerReadonlyCommand(service)); cmd.addSubcommand("UnMarkReadonly", new UnMarkBrokerReadonlyCommand(service)); cmd.parseWithHandler(new CommandLine.RunLast(), args); }
/** * Generates a bash completion script for the specified command class. * @param args command line options. Specify at least the {@code commandLineFQCN} mandatory parameter, which is * the fully qualified class name of the annotated {@code @Command} class to generate a completion script for. * Other parameters are optional. Specify {@code -h} to see details on the available options. */ public static void main(String... args) { AbstractParseResultHandler<List<Object>> resultHandler = new CommandLine.RunLast(); DefaultExceptionHandler<List<Object>> exceptionHandler = CommandLine.defaultExceptionHandler(); if (exitOnError()) { exceptionHandler.andExit(EXIT_CODE_INVALID_INPUT); } List<Object> result = new CommandLine(new App()).parseWithHandlers(resultHandler, exceptionHandler, args); int exitCode = result == null ? EXIT_CODE_SUCCESS : (Integer) result.get(0); if ((exitCode == EXIT_CODE_SUCCESS && exitOnSuccess()) || (exitCode != EXIT_CODE_SUCCESS && exitOnError())) { System.exit(exitCode); } }
public static void main(String... args) { CommandLine cmd = new CommandLine(new ExitCodeDemo()); cmd.parseWithHandlers( new CommandLine.RunLast().andExit(123), CommandLine.defaultExceptionHandler().andExit(456), args); } }