Refactor packages and artifactIds to prepare for official migration to spring-projects repo.

Remove usage of component scan in favor of auto-conf

Fixes #61
This commit is contained in:
Eric Bottard
2017-08-03 18:06:28 +02:00
parent 5fd1f716d9
commit 6497df181d
91 changed files with 488 additions and 264 deletions

View File

@@ -0,0 +1,47 @@
/*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.shell.legacy;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.shell.converters.ArrayConverter;
import org.springframework.shell.converters.AvailableCommandsConverter;
import org.springframework.shell.converters.SimpleFileConverter;
/**
* Main configuration class for the Shell 2 - Shell 1 adapter.
*
* @author Camilo Gonzalez
*/
@Configuration
@ComponentScan(basePackageClasses = {ArrayConverter.class}, excludeFilters = @ComponentScan.Filter(
type = FilterType.ASSIGNABLE_TYPE,
value = {AvailableCommandsConverter.class, SimpleFileConverter.class}))
public class LegacyAdapterAutoConfiguration {
@Bean
public LegacyMethodTargetResolver legacyMethodTargetResolver() {
return new LegacyMethodTargetResolver();
}
@Bean
public LegacyParameterResolver legacyParameterResolver() {
return new LegacyParameterResolver();
}
}

View File

@@ -0,0 +1,69 @@
/*
* Copyright 2015-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.shell.legacy;
import static org.springframework.util.StringUtils.collectionToDelimitedString;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.shell.core.CommandMarker;
import org.springframework.shell.core.annotation.CliCommand;
import org.springframework.shell.MethodTarget;
import org.springframework.shell.MethodTargetResolver;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;
/**
* A {@link MethodTargetResolver} that discovers methods annotated with {@link CliCommand} on beans
* implementing the {@link CommandMarker} marker interface.
*
* @author Eric Bottard
* @author Florent Biville
* @author Camilo Gonzalez
*/
@Component
public class LegacyMethodTargetResolver implements MethodTargetResolver {
@Autowired
private ApplicationContext applicationContext;
@Override
public Map<String, MethodTarget> resolve() {
Map<String, MethodTarget> methodTargets = new HashMap<>();
Map<String, CommandMarker> beans = applicationContext.getBeansOfType(CommandMarker.class);
for (Object bean : beans.values()) {
Class<?> clazz = bean.getClass();
ReflectionUtils.doWithMethods(clazz, method -> {
CliCommand cliCommand = method.getAnnotation(CliCommand.class);
for (String key : cliCommand.value()) {
methodTargets.put(key, new MethodTarget(method, bean, cliCommand.help()));
}
}, method -> method.getAnnotation(CliCommand.class) != null);
}
return methodTargets;
}
@Override
public String toString() {
return getClass().getSimpleName() + " contributing "
+ collectionToDelimitedString(resolve().keySet(), ", ", "[", "]");
}
}

View File

@@ -0,0 +1,195 @@
/*
* Copyright 2015-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.shell.legacy;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.shell.core.Converter;
import org.springframework.shell.core.annotation.CliOption;
import org.springframework.shell.CompletionContext;
import org.springframework.shell.CompletionProposal;
import org.springframework.shell.ParameterDescription;
import org.springframework.shell.ParameterResolver;
import org.springframework.shell.ValueResult;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
/**
* Resolves parameters by looking at the {@link CliOption} annotation and acting accordingly.
*
* @author Eric Bottard
* @author Camilo Gonzalez
*/
@Component
public class LegacyParameterResolver implements ParameterResolver {
private static final String CLI_OPTION_NULL = "__NULL__";
/**
* Prefix used by Spring Shell 1 for the argument keys (<em>e.g.</em> command --key value).
*/
private static final String CLI_PREFIX = "--";
@Autowired(required = false)
private Collection<Converter<?>> converters = new ArrayList<>();
@Override
public boolean supports(MethodParameter parameter) {
return parameter.hasParameterAnnotation(CliOption.class);
}
@Override
public ValueResult resolve(MethodParameter methodParameter, List<String> words) {
CliOption cliOption = methodParameter.getParameterAnnotation(CliOption.class);
Optional<Converter<?>> converter = converters.stream()
.filter(c -> c.supports(methodParameter.getParameterType(), cliOption.optionContext()))
.findFirst();
Map<String, ParseResult> values = parseOptions(words);
Map<String, ValueResult> seenValues = convertValues(values, methodParameter, converter);
switch (seenValues.size()) {
case 0:
if (!cliOption.mandatory()) {
String value = cliOption.unspecifiedDefaultValue();
Object resolvedValue = converter
.orElseThrow(noConverterFound(cliOption.key()[0], value, methodParameter.getParameterType()))
.convertFromText(value, methodParameter.getParameterType(), cliOption.optionContext());
return new ValueResult(methodParameter, resolvedValue);
}
else {
throw new IllegalArgumentException("Could not find parameter values for " + prettifyKeys(Arrays.asList(cliOption.key())) + " in " + words);
}
case 1:
return seenValues.values().iterator().next();
default:
throw new RuntimeException("Option has been set multiple times via " + prettifyKeys(seenValues.keySet()));
}
}
@Override
public Stream<ParameterDescription> describe(MethodParameter parameter) {
Parameter jlrParameter = parameter.getMethod().getParameters()[parameter.getParameterIndex()];
CliOption option = jlrParameter.getAnnotation(CliOption.class);
ParameterDescription result = ParameterDescription.outOf(parameter);
result.help(option.help());
List<String> keys = Arrays.asList(option.key());
result.keys(keys.stream()
.filter(key -> !key.isEmpty())
.map(key -> CLI_PREFIX + key)
.collect(Collectors.toList()));
if (!option.mandatory()) {
result.defaultValue(CLI_OPTION_NULL.equals(option.unspecifiedDefaultValue()) ? "null" : option.unspecifiedDefaultValue());
}
if(!CLI_OPTION_NULL.equals(option.specifiedDefaultValue())) {
result.whenFlag(option.specifiedDefaultValue());
}
boolean containsEmptyKey = keys.contains("");
result.mandatoryKey(!containsEmptyKey);
return Stream.of(result);
}
@Override
public List<CompletionProposal> complete(MethodParameter parameter, CompletionContext context) {
return null;
}
private Map<String, ParseResult> parseOptions(List<String> words) {
Map<String, ParseResult> values = new HashMap<>();
for (int i = 0; i < words.size(); i++) {
int from = i;
String word = words.get(i);
if (word.startsWith(CLI_PREFIX)) {
String key = word.substring(CLI_PREFIX.length());
// If next word doesn't exist or starts with '--', this is an unary option. Store null
String value = i < words.size() - 1 && !words.get(i + 1).startsWith(CLI_PREFIX) ? words.get(++i) : null;
Assert.isTrue(!values.containsKey(key), String.format("Option %s%s has already been set", CLI_PREFIX, key));
values.put(key, new ParseResult(value, from));
} // Must be the 'anonymous' option
else {
Assert.isTrue(!values.containsKey(""), "Anonymous option has already been set");
values.put("", new ParseResult(word, from));
}
}
return values;
}
private Map<String, ValueResult> convertValues(Map<String, ParseResult> values, MethodParameter methodParameter, Optional<Converter<?>> converter) {
Map<String, ValueResult> seenValues = new HashMap<>();
CliOption option = methodParameter.getParameterAnnotation(CliOption.class);
for (String key : option.key()) {
if (values.containsKey(key)) {
ParseResult parseResult = values.get(key);
String value = parseResult.value;
if (value == null && !CLI_OPTION_NULL.equals(option.specifiedDefaultValue())) {
value = option.specifiedDefaultValue();
}
Class<?> parameterType = methodParameter.getParameterType();
Object resolvedValue = converter
.orElseThrow(noConverterFound(key, value, parameterType))
.convertFromText(value, parameterType, option.optionContext());
int from = parseResult.from;
int to = key.isEmpty() || parseResult.value == null ? from : from + 1;
BitSet wordsUsed = new BitSet();
wordsUsed.set(from, to + 1);
BitSet wordsUsedForValues = new BitSet();
if (parseResult.value != null) {
wordsUsedForValues.set(to);
}
seenValues.put(key, new ValueResult(methodParameter, resolvedValue, wordsUsed, wordsUsedForValues));
}
}
return seenValues;
}
/**
* Return the list of possible keys for an option, suitable for displaying in an error message.
*/
private String prettifyKeys(Collection<String> keys) {
return keys.stream().map(s -> "".equals(s) ? "<anonymous>" : CLI_PREFIX + s).collect(Collectors.joining(", ", "[", "]"));
}
private Supplier<IllegalStateException> noConverterFound(String key, String value, Class<?> parameterType) {
return () -> new IllegalStateException("No converter found for " + CLI_PREFIX + key + " from '" + value + "' to type " + parameterType);
}
private static class ParseResult {
private final String value;
private final Integer from;
public ParseResult(String value, Integer from) {
this.value = value;
this.from = from;
}
}
}

View File

@@ -0,0 +1,20 @@
/*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Provides integration with Spring Shell 1.
*/
package org.springframework.shell.legacy;

View File

@@ -0,0 +1,2 @@
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.shell.legacy.LegacyAdapterAutoConfiguration

View File

@@ -0,0 +1,25 @@
/*
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.shell.legacy;
/**
* Created by ericbottard on 09/12/15.
*/
public enum ArtifactType {
source, processor, sink, task
}

View File

@@ -0,0 +1,78 @@
/*
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.shell.legacy;
import java.lang.reflect.Method;
import org.springframework.shell.core.CommandMarker;
import org.springframework.shell.core.annotation.CliCommand;
import org.springframework.shell.core.annotation.CliOption;
import org.springframework.util.ReflectionUtils;
/**
* Created by ericbottard on 09/12/15.
*/
public class LegacyCommands implements CommandMarker {
public static final Method REGISTER_METHOD = ReflectionUtils.findMethod(LegacyCommands.class, "register", String.class, ArtifactType.class, String.class, boolean.class);
public static final Method SUM_METHOD = ReflectionUtils.findMethod(LegacyCommands.class, "sum", int.class, int.class);
public static final Method LEGACY_ECHO_METHOD = ReflectionUtils.findMethod(LegacyCommands.class, "legacyEcho", String.class);
public static final Method SOME_METHOD = ReflectionUtils.findMethod(LegacyCommands.class, "someMethod", String.class, boolean.class);
@CliCommand(value = "register module", help = "Register a new module")
public String register(
@CliOption(mandatory = true,
key = {"", "name"},
help = "the name for the registered module")
String name,
@CliOption(mandatory = true,
key = {"type"},
help = "the type for the registered module")
ArtifactType type,
@CliOption(mandatory = true,
key = {"coordinates", "coords"},
help = "coordinates to the module archive")
String coordinates,
@CliOption(key = "force",
help = "force update if module already exists (only if not in use)",
specifiedDefaultValue = "true",
unspecifiedDefaultValue = "false")
boolean force) {
return String.format(("Successfully registered module '%s:%s'"), type, name);
}
@CliCommand(value = "sum", help = "adds two numbers")
public int sum(
@CliOption(key = "v1", unspecifiedDefaultValue = "38") int a,
@CliOption(key = "v2", specifiedDefaultValue = "42") int b
) {
return a + b;
}
@CliCommand(value = "legacy-echo", help = "Echoes a message")
public String legacyEcho(@CliOption(key = "", mandatory = true) String message) {
return message;
}
@CliCommand(value = "someMethod", help = "Method used for testing purposes")
public String someMethod(
@CliOption(key = "key", mandatory = false, help = "The optional parameter") String parameter,
@CliOption(key = "option", help = "an option", specifiedDefaultValue = "true", unspecifiedDefaultValue = "false") boolean option) {
return parameter + ", " + option;
}
}

View File

@@ -0,0 +1,72 @@
/*
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.shell.legacy;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.data.MapEntry.entry;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.shell.MethodTarget;
import org.springframework.shell.MethodTargetResolver;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Created by ericbottard on 09/12/15.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = LegacyMethodTargetResolverTest.Config.class)
public class LegacyMethodTargetResolverTest {
@Autowired
private LegacyCommands legacyCommands;
@Autowired
private MethodTargetResolver resolver;
@Test
public void findsMethodsAnnotatedWithCliCommand() throws Exception {
Map<String, MethodTarget> targets = resolver.resolve();
assertThat(targets).contains(entry(
"register module",
new MethodTarget(LegacyCommands.REGISTER_METHOD, legacyCommands, "Register a new module" )
));
}
@Configuration
static class Config {
@Bean
public LegacyCommands legacyCommands() {
return new LegacyCommands();
}
@Bean
public MethodTargetResolver methodTargetResolver() {
return new LegacyMethodTargetResolver();
}
}
}

View File

@@ -0,0 +1,280 @@
/*
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.shell.legacy;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.shell.ValueResultAsserts.assertThat;
import static org.springframework.shell.legacy.LegacyCommands.REGISTER_METHOD;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.MethodParameter;
import org.springframework.shell.converters.BooleanConverter;
import org.springframework.shell.converters.EnumConverter;
import org.springframework.shell.converters.StringConverter;
import org.springframework.shell.core.Converter;
import org.springframework.shell.core.annotation.CliOption;
import org.springframework.shell.ParameterDescription;
import org.springframework.shell.ParameterResolver;
import org.springframework.shell.Utils;
import org.springframework.shell.ValueResult;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = LegacyParameterResolverTest.Config.class)
public class LegacyParameterResolverTest {
private static final int NAME_OR_ANONYMOUS = 0;
private static final int TYPE = 1;
private static final int COORDINATES = 2;
private static final int FORCE = 3;
@Autowired
ParameterResolver parameterResolver;
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void supportsParameterAnnotatedWithCliOption() throws Exception {
MethodParameter methodParameter = Utils.createMethodParameter(REGISTER_METHOD, NAME_OR_ANONYMOUS);
boolean result = parameterResolver.supports(methodParameter);
assertThat(result).isTrue();
}
@Test
public void resolvesParameterAnnotatedWithCliOption() throws Exception {
MethodParameter methodParameter = Utils.createMethodParameter(REGISTER_METHOD, NAME_OR_ANONYMOUS);
assertThat(resolve(methodParameter, "--foo bar --name baz --qix bux")).hasValue("baz").usesWords(2, 3)
.usesWordsForValue(3);
}
@Test
public void resolvesAnonymousParameterAnnotatedWithCliOption() throws Exception {
MethodParameter methodParameter = Utils.createMethodParameter(REGISTER_METHOD, NAME_OR_ANONYMOUS);
assertThat(resolve(methodParameter, "--foo bar baz --qix bux")).hasValue("baz").usesWords(2)
.usesWordsForValue(2);
assertThat(resolve(methodParameter, "baz --foo bar --qix bux")).hasValue("baz").usesWords(0)
.usesWordsForValue(0);
}
@Test
public void usesLegacyConverters() throws Exception {
MethodParameter methodParameter = Utils.createMethodParameter(REGISTER_METHOD, TYPE);
assertThat(resolve(methodParameter, "--foo bar --name baz --qix bux --type processor"))
.hasValue(ArtifactType.processor).usesWords(6, 7).usesWordsForValue(7);
}
@Test
public void testUnspecifiedDefaultValue() throws Exception {
MethodParameter methodParameter = Utils.createMethodParameter(REGISTER_METHOD, FORCE);
assertThat(resolve(methodParameter, "--foo bar --name baz --qix bux"))
.hasValue(false).notUsesWords().notUsesWordsForValue();
}
@Test
public void testSpecifiedDefaultValue() throws Exception {
MethodParameter methodParameter = Utils.createMethodParameter(REGISTER_METHOD, FORCE);
assertThat(resolve(methodParameter, "--force --foo bar --name baz --qix bux"))
.hasValue(true).usesWords(0).notUsesWordsForValue();
assertThat(resolve(methodParameter, "--foo bar --name baz --qix bux --force"))
.hasValue(true).usesWords(6).notUsesWordsForValue();
}
@Test
public void testParameterNotFound() throws Exception {
MethodParameter methodParameter = Utils.createMethodParameter(REGISTER_METHOD, COORDINATES);
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage(
"Could not find parameter values for [--coordinates, --coords] in [--force, --foo, bar, --name, baz, --qix, bux]");
resolve(methodParameter, "--force --foo bar --name baz --qix bux");
}
@Test
public void testParameterFoundWithSameNameTooManyTimes() throws Exception {
MethodParameter methodParameter = Utils.createMethodParameter(REGISTER_METHOD, COORDINATES);
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Option --coordinates has already been set");
resolve(methodParameter, "--force --coordinates bar --coordinates baz --qix bux");
}
@Test
public void testNoConverterFound() throws Exception {
MethodParameter methodParameter = Utils.createMethodParameter(LegacyCommands.SUM_METHOD, 0);
thrown.expect(IllegalStateException.class);
thrown.expectMessage("No converter found for --v1 from '1' to type int");
resolve(methodParameter, "--v1 1 --v2 2");
}
@Test
public void testNoConverterFoundForUnspecifiedValue() throws Exception {
MethodParameter methodParameter = Utils.createMethodParameter(LegacyCommands.SUM_METHOD, 0);
thrown.expect(IllegalStateException.class);
thrown.expectMessage("No converter found for --v1 from '38' to type int");
resolve(methodParameter, "--v2 2");
}
@Test
public void testNoConverterFoundForSpecifiedValue() throws Exception {
MethodParameter methodParameter = Utils.createMethodParameter(LegacyCommands.SUM_METHOD, 1);
thrown.expect(IllegalStateException.class);
thrown.expectMessage("No converter found for --v2 from '42' to type int");
resolve(methodParameter, "--v1 1 --v2");
}
@Test
public void testDescribeBothDefaultsNotDeclared() {
MethodParameter methodParameter = Utils.createMethodParameter(LegacyCommands.REGISTER_METHOD, 1);
ParameterDescription description = parameterResolver.describe(methodParameter).findFirst().get();
assertThat(description.keys()).containsExactly("--type");
assertThat(description.formal()).isEqualTo(Utils.unCamelify(ArtifactType.class.getSimpleName()));
assertThat(description.defaultValue().isPresent()).isFalse();
assertThat(description.mandatoryKey()).isTrue();
String expectedHelp = methodParameter.getParameterAnnotation(CliOption.class).help();
assertThat(description.help()).isEqualTo(expectedHelp);
}
@Test
public void testDescribeBothDefaultsDeclared() {
MethodParameter methodParameter = Utils.createMethodParameter(LegacyCommands.SOME_METHOD, 1);
ParameterDescription description = parameterResolver.describe(methodParameter).findFirst().get();
assertThat(description.keys()).containsExactly("--option");
assertThat(description.formal()).isEqualTo(boolean.class.getName());
assertThat(description.defaultValue().get()).isEqualTo("false");
assertThat(description.defaultValueWhenFlag().get()).isEqualTo("true");
assertThat(description.mandatoryKey()).isTrue();
String expectedHelp = methodParameter.getParameterAnnotation(CliOption.class).help();
assertThat(description.help()).isEqualTo(expectedHelp);
}
@Test
public void testDescribeOnlySpecifiedDefaultDeclared() {
MethodParameter methodParameter = Utils.createMethodParameter(LegacyCommands.SUM_METHOD, 1);
ParameterDescription description = parameterResolver.describe(methodParameter).findFirst().get();
assertThat(description.keys()).containsExactly("--v2");
assertThat(description.formal()).isEqualTo(int.class.getName());
assertThat(description.defaultValue().get()).isEqualTo("null");
assertThat(description.defaultValueWhenFlag().get()).isEqualTo("42");
assertThat(description.mandatoryKey()).isTrue();
String expectedHelp = methodParameter.getParameterAnnotation(CliOption.class).help();
assertThat(description.help()).isEqualTo(expectedHelp);
}
@Test
public void testDescribeOnlyUnspecifiedDefaultDeclared() {
MethodParameter methodParameter = Utils.createMethodParameter(LegacyCommands.SUM_METHOD, 0);
ParameterDescription description = parameterResolver.describe(methodParameter).findFirst().get();
assertThat(description.keys()).containsExactly("--v1");
assertThat(description.formal()).isEqualTo(int.class.getName());
assertThat(description.defaultValue().get()).isEqualTo("38");
assertThat(description.mandatoryKey()).isTrue();
String expectedHelp = methodParameter.getParameterAnnotation(CliOption.class).help();
assertThat(description.help()).isEqualTo(expectedHelp);
}
@Test
public void testDescribeDefaultKey() {
MethodParameter methodParameter = Utils.createMethodParameter(LegacyCommands.LEGACY_ECHO_METHOD, 0);
ParameterDescription description = parameterResolver.describe(methodParameter).findFirst().get();
assertThat(description.keys()).isEmpty();
assertThat(description.formal()).isEqualTo(Utils.unCamelify(String.class.getSimpleName()));
assertThat(description.defaultValue().isPresent()).isFalse();
assertThat(description.mandatoryKey()).isFalse();
String expectedHelp = methodParameter.getParameterAnnotation(CliOption.class).help();
assertThat(description.help()).isEqualTo(expectedHelp);
}
@Test
public void testDescribeNonMandatoryNoDefaults() {
MethodParameter methodParameter = Utils.createMethodParameter(LegacyCommands.SOME_METHOD, 0);
ParameterDescription description = parameterResolver.describe(methodParameter).findFirst().get();
assertThat(description.keys()).containsExactly("--key");
assertThat(description.formal()).isEqualTo(Utils.unCamelify(String.class.getSimpleName()));
assertThat(description.defaultValue().get()).isEqualTo("null");
assertThat(description.mandatoryKey()).isTrue();
String expectedHelp = methodParameter.getParameterAnnotation(CliOption.class).help();
assertThat(description.help()).isEqualTo(expectedHelp);
}
private ValueResult resolve(MethodParameter methodParameter, String command) {
ValueResult result = parameterResolver.resolve(methodParameter, asList(command.split(" ")));
return result;
}
@Configuration
static class Config {
@Bean
public Converter<String> stringConverter() {
return new StringConverter();
}
@Bean
public Converter<Boolean> booleanConverter() {
return new BooleanConverter();
}
@Bean
public Converter<Enum<?>> enumConverter() {
return new EnumConverter();
}
@Bean
public ParameterResolver parameterResolver() {
return new LegacyParameterResolver();
}
}
}