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,52 @@
/*
* 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.standard;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.MethodParameter;
import org.springframework.shell.CompletionContext;
import org.springframework.shell.CompletionProposal;
import org.springframework.shell.CommandRegistry;
import org.springframework.stereotype.Component;
/**
* A {@link ValueProvider} that can be used to auto-complete names of shell commands.
*
* @author Eric Bottard
*/
@Component
public class CommandValueProvider extends ValueProviderSupport {
private final CommandRegistry commandRegistry;
@Lazy
@Autowired
public CommandValueProvider(CommandRegistry commandRegistry) {
this.commandRegistry = commandRegistry;
}
@Override
public List<CompletionProposal> complete(MethodParameter parameter, CompletionContext completionContext, String[] hints) {
return commandRegistry.listCommands().keySet().stream()
.map(CompletionProposal::new)
.collect(Collectors.toList());
}
}

View File

@@ -0,0 +1,54 @@
/*
* Copyright 2016 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.standard;
import java.util.ArrayList;
import java.util.List;
import org.springframework.core.MethodParameter;
import org.springframework.shell.CompletionContext;
import org.springframework.shell.CompletionProposal;
import org.springframework.stereotype.Component;
/**
* A {@link ValueProvider} that knows how to complete values for {@link Enum} typed parameters.
* @author Eric Bottard
*/
@Component
public class EnumValueProvider implements ValueProvider {
@Override
public boolean supports(MethodParameter parameter, CompletionContext completionContext) {
return Enum.class.isAssignableFrom(parameter.getParameterType());
}
@Override
public List<CompletionProposal> complete(MethodParameter parameter, CompletionContext completionContext, String[] hints) {
List<CompletionProposal> result = new ArrayList<>();
for (Object v : parameter.getParameterType().getEnumConstants()) {
Enum e = (Enum) v;
String prefix = completionContext.currentWordUpToCursor();
if (prefix == null) {
prefix = "";
}
if (e.name().startsWith(prefix)) {
result.add(new CompletionProposal(e.name()));
}
}
return result;
}
}

View File

@@ -0,0 +1,47 @@
/*
* 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.standard;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.stereotype.Component;
/**
* Indicates that an annotated class may contain shell methods (themselves annotated with {@link ShellMethod}) that
* is,
* methods that may be invoked reflectively by the shell.
*
* <p>This annotation is a specialization of {@link Component}.</p>
*
* @author Eric Bottard
* @see Component
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Component
public @interface ShellComponent {
/**
* Used to indicate a suggestion for a logical name for the component.
*/
String value() default "";
}

View File

@@ -0,0 +1,53 @@
/*
* 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.standard;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Used to mark a method as invokable via Spring Shell.
*
* @author Eric Bottard
* @author Florent Biville
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@Documented
public @interface ShellMethod {
/**
* The name(s) by which this method can be invoked via Spring Shell. If not specified, the actual method name
* will be used (turning camelCase humps into "-").
*/
String[] value() default {};
/**
* A description for the command. Should not contain any formatting (e.g. html) characters and would typically
* start with a capital letter and end with a dot.
*/
String help() default "";
/**
* The prefix to use for assigning parameters by name.
*/
String prefix() default "--";
}

View File

@@ -0,0 +1,80 @@
/*
* 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.standard;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Used to customize handling of a {@link ShellMethod} parameter.
*
* @author Eric Bottard
* @author Florent Biville
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface ShellOption {
String NULL = "__NULL__";
String NONE = "__NONE__";
/**
* Marker value to indicate that heuristics should be used to derive arity.
*/
int ARITY_USE_HEURISTICS = -1;
/**
* The key(s) (without the {@link ShellMethod#prefix()}) by which this parameter can be referenced
* when using named parameters. If none is specified, the actual method parameter name will be used.
*/
String[] value() default {};
/**
* Return the number of input "words" this parameter consumes. Default is 1, except when parameter type is boolean,
* in which case it is 0.
*/
int arity() default ARITY_USE_HEURISTICS;
/**
* The textual (pre-conversion) value to assign to this parameter if no value is provided by the user.
*/
String defaultValue() default NONE;
/**
* Return a short description of the parameter.
*/
String help() default "";
Class<? extends ValueProvider> valueProvider() default NoValueProvider.class;
/**
* Used to indicate to the framework that the given parameter should NOT be resolved by
* {@link StandardParameterResolver}. This is useful if several implementations of
* {@link org.springframework.shell.ParameterResolver} are present, given that the standard one can work with no
* annotation at all.
*/
boolean optOut() default false;
interface NoValueProvider extends ValueProvider {
}
}

View File

@@ -0,0 +1,53 @@
/*
* 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.standard;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.ConversionService;
import org.springframework.shell.CommandRegistry;
import org.springframework.shell.MethodTargetResolver;
import org.springframework.shell.ParameterResolver;
/**
* Sets up all required beans for supporting the standard Shell API.
*
* @author Eric Bottard
*/
@Configuration
public class StandardAPIAutoConfiguration {
@Bean
public ValueProvider commandValueProvider(CommandRegistry commandRegistry) {
return new CommandValueProvider(commandRegistry);
}
@Bean
public ValueProvider enumValueProvider() {
return new EnumValueProvider();
}
@Bean
public MethodTargetResolver standardMethodTargetResolver() {
return new StandardMethodTargetResolver();
}
@Bean
public ParameterResolver standardParameterResolver(ConversionService conversionService) {
return new StandardParameterResolver(conversionService);
}
}

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.standard;
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.MethodTarget;
import org.springframework.shell.MethodTargetResolver;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;
/**
* The standard implementation of {@link MethodTargetResolver} for new shell applications,
* resolves methods annotated with {@link ShellMethod} on {@link ShellComponent} beans.
*
* @author Eric Bottard
* @author Florent Biville
* @author Camilo Gonzalez
*/
public class StandardMethodTargetResolver implements MethodTargetResolver {
@Autowired
private ApplicationContext applicationContext;
@Override
public Map<String, MethodTarget> resolve() {
Map<String, MethodTarget> methodTargets = new HashMap<>();
Map<String, Object> commandBeans = applicationContext.getBeansWithAnnotation(ShellComponent.class);
for (Object bean : commandBeans.values()) {
Class<?> clazz = bean.getClass();
ReflectionUtils.doWithMethods(clazz, method -> {
ShellMethod shellMapping = method.getAnnotation(ShellMethod.class);
String[] keys = shellMapping.value();
if (keys.length == 0) {
keys = new String[] {method.getName()};
}
for (String key : keys) {
methodTargets.put(key, new MethodTarget(method, bean, shellMapping.help()));
}
}, method -> method.getAnnotation(ShellMethod.class) != null);
}
return methodTargets;
}
@Override
public String toString() {
return getClass().getSimpleName() + " contributing "
+ collectionToDelimitedString(resolve().keySet(), ", ", "[", "]");
}
}

View File

@@ -0,0 +1,531 @@
/*
* 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.standard;
import static org.springframework.shell.Utils.unCamelify;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
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.core.convert.ConversionService;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.shell.CompletionContext;
import org.springframework.shell.CompletionProposal;
import org.springframework.shell.ParameterDescription;
import org.springframework.shell.ParameterMissingResolutionException;
import org.springframework.shell.ParameterResolver;
import org.springframework.shell.UnfinishedParameterResolutionException;
import org.springframework.shell.Utils;
import org.springframework.shell.ValueResult;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.ConcurrentReferenceHashMap;
import org.springframework.util.ObjectUtils;
/**
* Default ParameterResolver implementation that supports the following features:<ul>
* <li>named parameters (recognized because they start with some {@link ShellMethod#prefix()})</li>
* <li>implicit named parameters (from the actual method parameter name)</li>
* <li>positional parameters (in order, for all parameter values that were not resolved <i>via</i> named
* parameters)</li>
* <li>default values (for all remaining parameters)</li>
* </ul>
*
* <p>Method arguments can consume several words of input at once (driven by {@link ShellOption#arity()}, default 1).
* If several words are consumed, they will be joined together as a comma separated value and passed to the {@link
* ConversionService}
* (which will typically return a List or array).</p>
*
* <p>Boolean parameters are by default expected to have an arity of 0, allowing invocations in the form {@code rm
* --force --dir /foo}:
* the presence of {@code --force} passes {@code true} as a parameter value, while its absence passes {@code false}.
* Both
* the default arity of 0 and the default value of {@code false} can be overridden <i>via</i> {@link ShellOption}
* if needed.</p>
* @author Eric Bottard
* @author Florent Biville
* @author Camilo Gonzalez
*/
@Component
public class StandardParameterResolver implements ParameterResolver {
private final ConversionService conversionService;
private Collection<ValueProvider> valueProviders = new HashSet<>();
/**
* A cache from method+input to String representation of actual parameter values.
* Note that the converted result is not cached, to allow dynamic computation to happen at every invocation
* if needed (e.g. if a remote service is involved).
*/
private final Map<CacheKey, Map<Parameter, ParameterRawValue>> parameterCache = new ConcurrentReferenceHashMap<>();
@Autowired
public StandardParameterResolver(ConversionService conversionService) {
this.conversionService = conversionService;
}
@Autowired(required = false)
public void setValueProviders(Collection<ValueProvider> valueProviders) {
this.valueProviders = valueProviders;
}
@Override
public boolean supports(MethodParameter parameter) {
boolean optOut = parameter.hasParameterAnnotation(ShellOption.class) && parameter.getParameterAnnotation(ShellOption.class).optOut();
return !optOut && parameter.getMethodAnnotation(ShellMethod.class) != null;
}
@Override
public ValueResult resolve(MethodParameter methodParameter, List<String> words) {
String prefix = prefixForMethod(methodParameter.getMethod());
CacheKey cacheKey = new CacheKey(methodParameter.getMethod(), words);
Map<Parameter, ParameterRawValue> resolved = parameterCache.computeIfAbsent(cacheKey, (k) -> {
Map<Parameter, ParameterRawValue> result = new HashMap<>();
Map<String, String> namedParameters = new HashMap<>();
// index of words that haven't yet been used to resolve parameter values
List<Integer> unusedWords = new ArrayList<>();
Set<String> possibleKeys = gatherAllPossibleKeys(methodParameter.getMethod());
// First, resolve all parameters passed by-name
for (int i = 0; i < words.size(); i++) {
int from = i;
String word = words.get(i);
if (possibleKeys.contains(word)) {
String key = word;
Parameter parameter = lookupParameterForKey(methodParameter.getMethod(), key, prefix);
int arity = getArity(parameter);
if (i + 1 + arity > words.size()) {
String input = words.subList(i, words.size()).stream().collect(Collectors.joining(" "));
throw new UnfinishedParameterResolutionException(describe(Utils.createMethodParameter(parameter)).findFirst().get(), input);
}
Assert.isTrue(i + 1 + arity <= words.size(), String.format("Not enough input for parameter '%s'", word));
String raw = words.subList(i + 1, i + 1 + arity).stream().collect(Collectors.joining(","));
Assert.isTrue(!namedParameters.containsKey(key), String.format("Parameter for '%s' has already been specified", word));
namedParameters.put(key, raw);
if (arity == 0) {
boolean defaultValue = booleanDefaultValue(parameter);
// Boolean parameter has been specified. Use the opposite of the default value
result.put(parameter, ParameterRawValue.explicit(String.valueOf(!defaultValue), key, from, from));
} else {
i += arity;
result.put(parameter, ParameterRawValue.explicit(raw, key, from, i));
}
} // store for later processing of positional params
else {
unusedWords.add(i);
}
}
// Now have a second pass over params and treat them as positional
int offset = 0;
Parameter[] parameters = methodParameter.getMethod().getParameters();
for (int i = 0, parametersLength = parameters.length; i < parametersLength; i++) {
Parameter parameter = parameters[i];
// Compute the intersection between possible keys for the param and what we've already seen for named params
Collection<String> keys = getKeysForParameter(methodParameter.getMethod(), i).collect(Collectors.toSet());
Collection<String> copy = new HashSet<>(keys);
copy.retainAll(namedParameters.keySet());
if (copy.isEmpty()) { // Was not set via a key (including aliases), must be positional
int arity = getArity(parameter);
if (arity > 0 && (offset + arity) <= unusedWords.size()) {
String raw = unusedWords.subList(offset, offset + arity).stream()
.map(index -> words.get(index))
.collect(Collectors.joining(","));
int from = unusedWords.get(offset);
int to = from + arity - 1;
result.put(parameter, ParameterRawValue.explicit(raw, null, from, to));
offset += arity;
} // No more input. Try defaultValues
else {
Optional<String> defaultValue = defaultValueFor(parameter);
defaultValue.ifPresent(value -> result.put(parameter, ParameterRawValue.implicit(value, null, null, null)));
}
}
else if (copy.size() > 1) {
throw new IllegalArgumentException("Named parameter has been specified multiple times via " + quote(copy));
}
}
Assert.isTrue(offset == unusedWords.size(),
"Too many arguments: the following could not be mapped to parameters: "
+ unusedWords.subList(offset, unusedWords.size()).stream()
.map(index -> words.get(index)).collect(Collectors.joining(" ", "'", "'")));
return result;
});
Parameter param = methodParameter.getMethod().getParameters()[methodParameter.getParameterIndex()];
if (!resolved.containsKey(param)) {
throw new ParameterMissingResolutionException(describe(methodParameter).findFirst().get());
}
ParameterRawValue parameterRawValue = resolved.get(param);
Object value = convertRawValue(parameterRawValue, methodParameter);
BitSet wordsUsed = getWordsUsed(parameterRawValue);
BitSet wordsUsedForValue = getWordsUsedForValue(parameterRawValue);
return new ValueResult(methodParameter, value, wordsUsed, wordsUsedForValue);
}
private BitSet getWordsUsed(ParameterRawValue parameterRawValue) {
if (parameterRawValue.from != null) {
BitSet wordsUsed = new BitSet();
wordsUsed.set(parameterRawValue.from, parameterRawValue.to + 1);
return wordsUsed;
}
return null;
}
private BitSet getWordsUsedForValue(ParameterRawValue parameterRawValue) {
if (parameterRawValue.from != null) {
BitSet wordsUsedForValue = new BitSet();
wordsUsedForValue.set(parameterRawValue.from, parameterRawValue.to + 1);
if (parameterRawValue.key != null) {
wordsUsedForValue.clear(parameterRawValue.from);
}
return wordsUsedForValue;
}
return null;
}
private Object convertRawValue(ParameterRawValue parameterRawValue, MethodParameter methodParameter) {
String s = parameterRawValue.value;
if (ShellOption.NULL.equals(s)) {
return null;
}
else {
return conversionService.convert(s, TypeDescriptor.valueOf(String.class), new TypeDescriptor(methodParameter));
}
}
private Set<String> gatherAllPossibleKeys(Method method) {
final String prefix = prefixForMethod(method);
return Arrays.stream(method.getParameters())
.flatMap(p -> {
ShellOption option = p.getAnnotation(ShellOption.class);
if (option != null && option.value().length > 0) {
return Arrays.stream(option.value());
}
else {
return Stream.of(prefix + Utils.createMethodParameter(p).getParameterName());
}
}).collect(Collectors.toSet());
}
private String prefixForMethod(Method method) {
return method.getAnnotation(ShellMethod.class).prefix();
}
private Optional<String> defaultValueFor(Parameter parameter) {
Optional<String> defaultValue = Optional.empty();
ShellOption option = parameter.getAnnotation(ShellOption.class);
if (option != null && !ShellOption.NONE.equals(option.defaultValue())) {
defaultValue = Optional.of(option.defaultValue());
}
else if (option == null && getArity(parameter) == 0) {
return Optional.of("false");
}
return defaultValue;
}
private boolean booleanDefaultValue(Parameter parameter) {
ShellOption option = parameter.getAnnotation(ShellOption.class);
if (option != null && !ShellOption.NULL.equals(option.defaultValue())) {
return Boolean.parseBoolean(option.defaultValue());
}
return false;
}
@Override
public Stream<ParameterDescription> describe(MethodParameter parameter) {
Parameter jlrParameter = parameter.getMethod().getParameters()[parameter.getParameterIndex()];
int arity = getArity(jlrParameter);
Class<?> type = parameter.getParameterType();
ShellOption option = jlrParameter.getAnnotation(ShellOption.class);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < arity; i++) {
if (i > 0) {
sb.append(" ");
}
sb.append(arity > 1 ? unCamelify(removeMultiplicityFromType(parameter).getSimpleName()) : unCamelify(type.getSimpleName()));
}
ParameterDescription result = ParameterDescription.outOf(parameter);
result.formal(sb.toString());
if (option != null) {
result.help(option.help());
Optional<String> defaultValue = defaultValueFor(jlrParameter);
if (defaultValue.isPresent()) {
result.defaultValue(defaultValue.map(dv -> dv.equals(ShellOption.NULL) ? "<none>" : dv).get());
}
}
result
.keys(getKeysForParameter(parameter.getMethod(), parameter.getParameterIndex())
.collect(Collectors.toList()))
.mandatoryKey(false);
return Stream.of(result);
}
@Override
public List<CompletionProposal> complete(MethodParameter methodParameter, CompletionContext context) {
boolean set;
Exception unfinished = null;
// First try to see if this parameter has been set, even to some unfinished value
ParameterRawValue parameterRawValue = null;
int arity = 1;
try {
resolve(methodParameter, context.getWords());
CacheKey cacheKey = new CacheKey(methodParameter.getMethod(), context.getWords());
Parameter parameter = methodParameter.getMethod().getParameters()[methodParameter.getParameterIndex()];
arity = getArity(parameter);
parameterRawValue = parameterCache.get(cacheKey).get(parameter);
set = parameterRawValue.explicit;
}
catch (ParameterMissingResolutionException e) {
set = false;
}
catch (Exception e) {
unfinished = e;
set = false;
// Most likely what is already typed would fail resolution (eg type conversion failure)
// Exit early and let other parameters have a chance at being proposed
//return Collections.emptyList();
}
// There are 4 possible cases:
// 1) parameter not set at all
// 2) parameter set via its key, not enough input to consume a value
// 3) parameter set with multiple values, enough to cover arity. We're done
// 4) parameter set, and some value bound. But maybe that value is just a prefix to what the user actually wants
// 4.1) or maybe that value was resolved by position, but is a prefix of an actual valid key
if (!set) {
if (unfinished == null) { // case 1 above
return argumentKeysThatStartWithContextPrefix(methodParameter, context);
} // case 2
else {
return valueCompletions(methodParameter, context);
}
}
else {
List<CompletionProposal> result = new ArrayList<>();
Object value = convertRawValue(parameterRawValue, methodParameter);
if (value instanceof Collection && ((Collection) value).size() == arity
|| (ObjectUtils.isArray(value) && Array.getLength(value) == arity)) {
// We're done already
return result;
}
// Case 4
result.addAll(valueCompletions(methodParameter, context));
if (parameterRawValue.positional()) {
// Case 4.1: There exists "--command foo" and user has typed "--comm" which (wrongly) got resolved as a positional param
result.addAll(argumentKeysThatStartWithContextPrefix(methodParameter, context));
}
return result;
}
}
private List<CompletionProposal> valueCompletions(MethodParameter methodParameter, CompletionContext completionContext) {
return valueProviders.stream()
.filter(vp -> vp.supports(methodParameter, completionContext))
.map(vp -> vp.complete(methodParameter, completionContext, null))
.findFirst().orElseGet(() -> Collections.emptyList());
}
private List<CompletionProposal> argumentKeysThatStartWithContextPrefix(MethodParameter methodParameter, CompletionContext context) {
String prefix = context.currentWordUpToCursor() != null ? context.currentWordUpToCursor() : "";
return describe(methodParameter).flatMap(pd -> pd.keys().stream())
.filter(k -> k.startsWith(prefix))
.map(CompletionProposal::new)
.collect(Collectors.toList());
}
/**
* In case of {@code foo[] or Collection<Foo>} and arity > 1, return the element type.
*/
private Class<?> removeMultiplicityFromType(MethodParameter parameter) {
Class<?> parameterType = parameter.getParameterType();
if (parameterType.isArray()) {
return parameterType.getComponentType();
}
else if (Collection.class.isAssignableFrom(parameterType)) {
return parameter.getNestedParameterType();
}
else {
throw new RuntimeException("For " + parameter + " (with arity > 1) expected an array/collection type");
}
}
/**
* Surrounds the parameter keys with quotes.
*/
private String quote(Collection<String> keys) {
return keys.stream().collect(Collectors.joining(", ", "'", "'"));
}
/**
* Return the arity of a given parameter. The default arity is 1, except for
* booleans where arity is 0 (can be overridden back to 1 via an annotation)
*/
private int getArity(Parameter parameter) {
ShellOption option = parameter.getAnnotation(ShellOption.class);
int inferred = (parameter.getType() == boolean.class || parameter.getType() == Boolean.class) ? 0 : 1;
return option != null && option.arity() != ShellOption.ARITY_USE_HEURISTICS ? option.arity() : inferred;
}
/**
* Return the key(s) the i-th parameter of the command method, resolved either from the {@link ShellOption}
* annotation,
* or from the actual parameter name.
*/
private Stream<String> getKeysForParameter(Method method, int index) {
String prefix = prefixForMethod(method);
Parameter p = method.getParameters()[index];
ShellOption option = p.getAnnotation(ShellOption.class);
if (option != null && option.value().length > 0) {
return Arrays.stream(option.value());
}
else {
return Stream.of(prefix + Utils.createMethodParameter(p).getParameterName());
}
}
/**
* Return the method parameter that should be bound to the given key.
*/
private Parameter lookupParameterForKey(Method method, String key, String prefix) {
Parameter[] parameters = method.getParameters();
for (int i = 0, parametersLength = parameters.length; i < parametersLength; i++) {
Parameter p = parameters[i];
if (getKeysForParameter(method, i).anyMatch(k -> k.equals(key))) {
return p;
}
}
throw new IllegalArgumentException(String.format("Could not look up parameter for '%s%s' in %s", prefix, key, method));
}
private static class CacheKey {
private final Method method;
private final List<String> words;
private CacheKey(Method method, List<String> words) {
this.method = method;
this.words = words;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CacheKey cacheKey = (CacheKey) o;
return Objects.equals(method, cacheKey.method) &&
Objects.equals(words, cacheKey.words);
}
@Override
public int hashCode() {
return Objects.hash(method, words);
}
@Override
public String toString() {
return method.getName() + " " + words;
}
}
private static class ParameterRawValue {
private CompletionContext context;
private Integer from;
private Integer to;
private Integer keyIndex;
/**
* The raw String value that got bound to a parameter.
*/
private final String value;
/**
* If false, the value resolved is the result of applying defaults.
*/
private final boolean explicit;
/**
* The key that was used to set the parameter, or null if resolution happened by position.
*/
private final String key;
private ParameterRawValue(String value, boolean explicit, String key, Integer from, Integer to) {
this.value = value;
this.explicit = explicit;
this.key = key;
this.from = from;
this.to = to;
}
public static ParameterRawValue explicit(String value, String key, Integer from, Integer to) {
return new ParameterRawValue(value, true, key, from, to);
}
public static ParameterRawValue implicit(String value, String key, Integer from, Integer to) {
return new ParameterRawValue(value, false, key, from, to);
}
public boolean positional() {
return key == null;
}
@Override
public String toString() {
return "ParameterRawValue{" +
"value='" + value + '\'' +
", explicit=" + explicit +
", key='" + key + '\'' +
", from=" + from +
", to=" + to +
'}';
}
}
}

View File

@@ -0,0 +1,32 @@
/*
* Copyright 2016 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.standard;
import java.util.List;
import org.springframework.core.MethodParameter;
import org.springframework.shell.CompletionContext;
import org.springframework.shell.CompletionProposal;
/**
*/
public interface ValueProvider {
boolean supports(MethodParameter parameter, CompletionContext completionContext);
List<CompletionProposal> complete(MethodParameter parameter, CompletionContext completionContext, String[] hints);
}

View File

@@ -0,0 +1,38 @@
/*
* Copyright 2016 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.standard;
import org.springframework.core.MethodParameter;
import org.springframework.shell.CompletionContext;
/**
* Base class for {@link ValueProvider} that match by type. Subclasses {@literal C} will be selected for parameters
* whose {@literal @}{@link ShellOption#valueProvider()} return the concrete class {@literal C}.
*
* @author Eric Bottard
*/
public abstract class ValueProviderSupport implements ValueProvider {
@Override
public boolean supports(MethodParameter parameter, CompletionContext completionContext) {
ShellOption annotation = parameter.getParameterAnnotation(ShellOption.class);
if (annotation == null) {
return false;
}
return annotation.valueProvider().isAssignableFrom(this.getClass());
}
}

View File

@@ -0,0 +1,22 @@
/*
* 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.
*/
/**
* Contains infrastructure for describing commands with the "new" preferred Spring Shell programming model.
*
* @author Eric Bottard
*/
package org.springframework.shell.standard;

View File

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

View File

@@ -0,0 +1,87 @@
/*
* 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.standard;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.core.MethodParameter;
import org.springframework.shell.CompletionContext;
import org.springframework.shell.CompletionProposal;
import org.springframework.shell.MethodTarget;
import org.springframework.shell.CommandRegistry;
import org.springframework.shell.Utils;
import org.springframework.util.ReflectionUtils;
/**
* Unit tests for {@link CommandValueProvider}.
*
* @author Eric Bottard
*/
public class CommandValueProviderTest {
@Mock
private CommandRegistry shell;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testValues() {
CommandValueProvider valueProvider = new CommandValueProvider(shell);
Method help = ReflectionUtils.findMethod(Command.class, "help", String.class);
MethodParameter methodParameter = Utils.createMethodParameter(help, 0);
CompletionContext completionContext = new CompletionContext(Arrays.asList("help", "m"), 0, 0);
boolean supports = valueProvider.supports(methodParameter, completionContext);
assertThat(supports).isEqualTo(true);
Map<String, MethodTarget> commands = new HashMap<>();
commands.put("me", null);
commands.put("meow", null);
commands.put("yourself", null);
when(shell.listCommands()).thenReturn(commands);
List<CompletionProposal> proposals = valueProvider.complete(methodParameter, completionContext, new String[0]);
assertThat(proposals).extracting("value", String.class)
.contains("me", "meow", "yourself");
}
public static class Command {
public void help(@ShellOption(valueProvider = CommandValueProvider.class) String command) {
}
}
}

View File

@@ -0,0 +1,91 @@
/*
* 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.standard;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.springframework.core.MethodParameter;
import org.springframework.shell.CompletionContext;
import org.springframework.shell.CompletionProposal;
/**
* An example commands class.
*
* @author Eric Bottard
* @author Florent Biville
*/
public class Remote {
/**
* A command method that showcases<ul>
* <li>default handling for booleans (force)</li>
* <li>default parameter name discovery (name)</li>
* <li>default value supplying (foo and bar)</li>
* </ul>
*/
@ShellMethod(help = "switch channels")
public void zap(boolean force,
String name,
@ShellOption(defaultValue="defoolt") String foo,
@ShellOption(value = {"--bar", "--baz"}, defaultValue = "last") String bar) {
}
@ShellMethod(help = "bye bye")
public void shutdown(@ShellOption Delay delay) {
}
@ShellMethod(help = "a different prefix", prefix = "-")
public void prefixTest(@ShellOption String message) {
}
@ShellMethod(help = "add 3 numbers together")
public void add(@ShellOption(arity = 3, valueProvider = NumberValueProvider.class) List<Integer> numbers) {
}
@ShellMethod(help = "add 3 numbers together (array)")
public void addAsArray(@ShellOption(arity = 3, valueProvider = NumberValueProvider.class) int[] numbers) {
}
public enum Delay {
small, medium, big;
}
public static class NumberValueProvider extends ValueProviderSupport {
private final String[] values;
public NumberValueProvider(String... values) {
this.values = values;
}
@Override
public List<CompletionProposal> complete(MethodParameter parameter, CompletionContext completionContext, String[] hints) {
String prefix = completionContext.currentWord() != null ? completionContext.currentWord() : "";
return Stream.of(values)
.filter(n -> n.startsWith(prefix))
.map(CompletionProposal::new)
.collect(Collectors.toList());
}
}
}

View File

@@ -0,0 +1,253 @@
/*
* 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.standard;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.shell.ValueResultAsserts.assertThat;
import static org.springframework.util.ReflectionUtils.findMethod;
import java.lang.reflect.Method;
import java.util.List;
import java.util.stream.Collectors;
import org.jline.reader.ParsedLine;
import org.jline.reader.impl.DefaultParser;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.shell.CompletionContext;
import org.springframework.shell.CompletionProposal;
import org.springframework.shell.ParameterMissingResolutionException;
import org.springframework.shell.UnfinishedParameterResolutionException;
import org.springframework.shell.Utils;
import org.springframework.shell.ValueResult;
/**
* Unit tests for DefaultParameterResolver.
* @author Eric Bottard
* @author Florent Biville
*/
public class StandardParameterResolverTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
private StandardParameterResolver resolver = new StandardParameterResolver(new DefaultConversionService());
// Tests for resolution
@Test
public void testParses() throws Exception {
Method method = findMethod(Remote.class, "zap", boolean.class, String.class, String.class, String.class);
List<String> words = asList("--force --name --foo y".split(" "));
ValueResult result0 = resolver.resolve(Utils.createMethodParameter(method, 0), words);
assertThat(result0).hasValue(true).usesWords(0).notUsesWordsForValue();
assertThat(result0.wordsUsed(words)).containsExactly("--force");
ValueResult result1 = resolver.resolve(Utils.createMethodParameter(method, 1), words);
assertThat(result1).hasValue("--foo").usesWords(1, 2).usesWordsForValue(2);
assertThat(result1.wordsUsed(words)).containsExactly("--name", "--foo");
assertThat(result1.wordsUsedForValue(words)).containsExactly("--foo");
ValueResult result2 = resolver.resolve(Utils.createMethodParameter(method, 2), words);
assertThat(result2).hasValue("y").usesWords(3).usesWordsForValue(3);
assertThat(result2.wordsUsed(words)).containsExactly("y");
ValueResult result3 = resolver.resolve(Utils.createMethodParameter(method, 3), words);
assertThat(result3).hasValue("last").notUsesWords().notUsesWordsForValue();
}
@Test
public void testParsesWithMethodPrefix() throws Exception {
Method method = findMethod(Remote.class, "prefixTest", String.class);
ValueResult result = resolver.resolve(Utils.createMethodParameter(method, 0),
asList("-message abc".split(" ")));
assertThat(result).hasValue("abc").usesWords(0, 1).usesWordsForValue(1);
}
@Test
public void testParameterSpecifiedTwiceViaDifferentAliases() throws Exception {
Method method = findMethod(Remote.class, "zap", boolean.class, String.class, String.class, String.class);
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Named parameter has been specified multiple times via '--bar, --baz'");
resolver.resolve(
Utils.createMethodParameter(method, 0),
asList("--force --name --foo y --bar x --baz z".split(" "))
);
}
@Test
public void testParameterSpecifiedTwiceViaSameKey() throws Exception {
Method method = findMethod(Remote.class, "zap", boolean.class, String.class, String.class, String.class);
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Parameter for '--baz' has already been specified");
resolver.resolve(
Utils.createMethodParameter(method, 0),
asList("--force --name --foo y --baz x --baz z".split(" "))
);
}
@Test
public void testTooMuchInput() throws Exception {
Method method = findMethod(Remote.class, "zap", boolean.class, String.class, String.class, String.class);
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("the following could not be mapped to parameters: 'leftover'");
resolver.resolve(
Utils.createMethodParameter(method, 0),
asList("--foo hello --name bar --force --bar well leftover".split(" "))
);
}
@Test
public void testIncompleteCommandResolution() throws Exception {
Method method = findMethod(Remote.class, "shutdown", Remote.Delay.class);
thrown.expect(UnfinishedParameterResolutionException.class);
thrown.expectMessage("Error trying to resolve '--delay delay' using [--delay]");
resolver.resolve(
Utils.createMethodParameter(method, 0),
asList("--delay".split(" "))
);
}
@Test
public void testIncompleteCommandResolutionBigArity() throws Exception {
Method method = findMethod(Remote.class, "add", List.class);
thrown.expect(UnfinishedParameterResolutionException.class);
thrown.expectMessage("Error trying to resolve '--numbers list list list' using [--numbers 1 2]");
resolver.resolve(
Utils.createMethodParameter(method, 0),
asList("--numbers 1 2".split(" "))
);
}
@Test
public void testUnresolvableArg() throws Exception {
Method method = findMethod(Remote.class, "zap", boolean.class, String.class, String.class, String.class);
thrown.expect(ParameterMissingResolutionException.class);
thrown.expectMessage("Parameter '--name string' should be specified");
resolver.resolve(
Utils.createMethodParameter(method, 1),
asList("--foo hello --force --bar well".split(" "))
);
}
// Tests for completion
@Test
public void testParameterKeyNotYetSetAppearsInProposals() {
Method method = findMethod(Remote.class, "zap", boolean.class, String.class, String.class, String.class);
List<String> completions = resolver.complete(
Utils.createMethodParameter(method, 1),
contextFor("")
).stream().map(CompletionProposal::value).collect(Collectors.toList());
assertThat(completions).contains("--name");
completions = resolver.complete(
Utils.createMethodParameter(method, 1),
contextFor("--force ")
).stream().map(CompletionProposal::value).collect(Collectors.toList());
assertThat(completions).contains("--name");
}
@Test
public void testParameterKeyNotFullySpecified() {
Method method = findMethod(Remote.class, "zap", boolean.class, String.class, String.class, String.class);
List<String> completions = resolver.complete(
Utils.createMethodParameter(method, 1),
contextFor("--na")
).stream().map(CompletionProposal::value).collect(Collectors.toList());
assertThat(completions).contains("--name");
completions = resolver.complete(
Utils.createMethodParameter(method, 1),
contextFor("--force --na")
).stream().map(CompletionProposal::value).collect(Collectors.toList());
assertThat(completions).contains("--name");
}
@Test
public void testNoMoreAvailableParameters() {
Method method = findMethod(Remote.class, "zap", boolean.class, String.class, String.class, String.class);
List<String> completions = resolver.complete(
Utils.createMethodParameter(method, 2), // trying to complete --foo
contextFor("--name ") // but input is currently focused on --name
).stream().map(CompletionProposal::value).collect(Collectors.toList());
assertThat(completions).isEmpty();
}
@Test
public void testNotTheRightTimeToCompleteThatParameter() {
Method method = findMethod(Remote.class, "shutdown", Remote.Delay.class);
List<String> completions = resolver.complete(
Utils.createMethodParameter(method, 0),
contextFor("--delay 323")
).stream().map(CompletionProposal::value).collect(Collectors.toList());
assertThat(completions).isEmpty();
}
@Test
public void testValueCompletionWithNonDefaultArity() {
resolver.setValueProviders(singletonList(new Remote.NumberValueProvider("12", "42", "7")));
Method[] methods = {
findMethod(org.springframework.shell.standard.Remote.class, "add", List.class),
findMethod(org.springframework.shell.standard.Remote.class, "addAsArray", int[].class),
};
for (Method method : methods) {
List<String> completions = resolver
.complete(Utils.createMethodParameter(method, 0), contextFor("--numbers ")).stream()
.map(CompletionProposal::value).collect(Collectors.toList());
assertThat(completions).contains("12", "42", "7");
completions = resolver.complete(Utils.createMethodParameter(method, 0), contextFor("--numbers 42 "))
.stream().map(CompletionProposal::value).collect(Collectors.toList());
assertThat(completions).contains("12", "7");
completions = resolver.complete(Utils.createMethodParameter(method, 0), contextFor("--numbers 42 34 "))
.stream().map(CompletionProposal::value).collect(Collectors.toList());
assertThat(completions).contains("12", "7");
completions = resolver.complete(Utils.createMethodParameter(method, 0), contextFor("--numbers 42 34 66 "))
.stream().map(CompletionProposal::value).collect(Collectors.toList());
assertThat(completions).isEmpty(); // All 3 have already been set
}
}
private CompletionContext contextFor(String input) {
DefaultParser defaultParser = new DefaultParser();
ParsedLine parsed = defaultParser.parse(input, input.length());
List<String> words = parsed.words().stream().filter(w -> w.length() > 0).collect(Collectors.toList());
return new CompletionContext(words, parsed.wordIndex(), parsed.wordCursor());
}
}