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,136 @@
/*
* 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.jcommander;
import static org.springframework.shell.Utils.unCamelify;
import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.springframework.beans.BeanUtils;
import org.springframework.core.MethodParameter;
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.ReflectionUtils;
import com.beust.jcommander.DynamicParameter;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
import com.beust.jcommander.ParametersDelegate;
/**
* Provides integration with JCommander.
*
* @author Eric Bottard
*/
public class JCommanderParameterResolver implements ParameterResolver {
private static final Collection<Class<? extends Annotation>> JCOMMANDER_ANNOTATIONS =
Arrays.asList(Parameter.class, DynamicParameter.class, ParametersDelegate.class);
@Override
public boolean supports(MethodParameter parameter) {
AtomicBoolean isSupported = new AtomicBoolean(false);
Class<?> parameterType = parameter.getParameterType();
ReflectionUtils.doWithFields(parameterType, field -> {
ReflectionUtils.makeAccessible(field);
boolean hasAnnotation = Arrays.stream(field.getAnnotations())
.map(Annotation::annotationType)
.anyMatch(JCOMMANDER_ANNOTATIONS::contains);
isSupported.compareAndSet(false, hasAnnotation);
});
ReflectionUtils.doWithMethods(parameterType, method -> {
ReflectionUtils.makeAccessible(method);
boolean hasAnnotation = Arrays.stream(method.getAnnotations())
.map(Annotation::annotationType)
.anyMatch(Parameter.class::equals);
isSupported.compareAndSet(false, hasAnnotation);
});
return isSupported.get();
}
@Override
public ValueResult resolve(MethodParameter methodParameter, List<String> words) {
JCommander jCommander = createJCommander(methodParameter);
jCommander.parse(words.toArray(new String[words.size()]));
return new ValueResult(methodParameter, jCommander.getObjects().get(0));
}
private JCommander createJCommander(MethodParameter methodParameter) {
Object pojo = BeanUtils.instantiateClass(methodParameter.getParameterType());
JCommander jCommander = new JCommander(pojo);
jCommander.setAcceptUnknownOptions(true);
return jCommander;
}
@Override
public Stream<ParameterDescription> describe(MethodParameter parameter) {
JCommander jCommander = createJCommander(parameter);
Stream<com.beust.jcommander.ParameterDescription> jCommanderDescriptions = streamAllJCommanderDescriptions(jCommander);
return jCommanderDescriptions
.map(j -> new ParameterDescription(parameter, unCamelify(j.getParameterized().getType().getSimpleName()))
.keys(Arrays.asList(j.getParameter().names()))
.help(j.getDescription())
.mandatoryKey(!j.equals(jCommander.getMainParameter()))
// Not ideal as this does not take reverse-conversion into account, but just toString()
.defaultValue(j.getDefault() == null ? "" : String.valueOf(j.getDefault()))
);
}
/**
* Return <em>all</em> JCommander parameter descriptions, including the "main" parameter if present.
*/
private Stream<com.beust.jcommander.ParameterDescription> streamAllJCommanderDescriptions(JCommander jCommander) {
return Stream.concat(
jCommander.getParameters().stream(),
jCommander.getMainParameter() != null ? Stream.of(jCommander.getMainParameter()) : Stream.empty()
);
}
@Override
public List<CompletionProposal> complete(MethodParameter parameter, CompletionContext context) {
JCommander jCommander = createJCommander(parameter);
List<String> words = context.getWords();
try {
jCommander.parseWithoutValidation(words.toArray(new String[words.size()]));
}
catch (ParameterException ignored) {
// Exception here certainly means current buffer is not parseable in full.
// Better to bail out now.
return Collections.emptyList();
}
return streamAllJCommanderDescriptions(jCommander)
.filter(p -> !p.isAssigned())
.flatMap(p -> Arrays.stream(p.getParameter().names()))
.map(CompletionProposal::new)
.collect(Collectors.toList());
}
}

View File

@@ -0,0 +1,34 @@
/*
* 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.jcommander;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;
/**
* Registers JCommanderParameterResolver and supporting beans as appropriate.
*
* @author Eric Bottard
*/
@Configuration
public class JCommanderParameterResolverAutoConfiguration {
@Bean
public JCommanderParameterResolver jCommanderParameterResolver() {
return new JCommanderParameterResolver();
}
}

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.
*/
/**
* Provides integration with JCommander.
*
* @author Eric Bottard
*/
package org.springframework.shell.jcommander;

View File

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

View File

@@ -0,0 +1,64 @@
/*
* 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.jcommander;
import java.util.ArrayList;
import java.util.List;
import com.beust.jcommander.Parameter;
/**
* A POJO with fields annotated with JCommander annotations.
*
* @author Eric Bottard
* @see MyLordCommands#genesis(FieldCollins)
*/
public class FieldCollins {
@Parameter(names = {"--name", "-n"}, description = "what's in a name?")
private String name;
@Parameter(names = "-level")
private int level = 3;
@Parameter(description = "rest")
private List<String> rest = new ArrayList<>();
public List<String> getRest() {
return rest;
}
public void setRest(List<String> rest) {
this.rest = rest;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
}

View File

@@ -0,0 +1,114 @@
/*
* 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.jcommander;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import java.util.stream.Stream;
import org.junit.Test;
import org.springframework.core.MethodParameter;
import org.springframework.shell.CompletionContext;
import org.springframework.shell.CompletionProposal;
import org.springframework.shell.ParameterDescription;
import org.springframework.shell.Utils;
import org.springframework.util.ReflectionUtils;
/**
* Unit test for {@link JCommanderParameterResolver}.
*
* @author Eric Bottard
* @author Florent Biville
*/
public class JCommanderParameterResolverTest {
private static final Method COMMAND_METHOD = ReflectionUtils.findMethod(MyLordCommands.class, "genesis", FieldCollins.class);
private JCommanderParameterResolver resolver = new JCommanderParameterResolver();
@Test
public void testSupportsJCommanderPojos() throws Exception {
assertThat(resolver.supports(Utils.createMethodParameter(COMMAND_METHOD, 0))).isEqualTo(true);
}
@Test
public void testDoesNotSupportsNonJCommanderPojos() throws Exception {
Method method = ReflectionUtils.findMethod(MyLordCommands.class, "apocalypse", String.class);
assertThat(resolver.supports(Utils.createMethodParameter(method, 0))).isFalse();
}
@Test
public void testPojoValuesAreCorrectlySet() {
MethodParameter methodParameter = Utils.createMethodParameter(COMMAND_METHOD, 0);
FieldCollins resolved = (FieldCollins) resolver
.resolve(methodParameter, asList("--name foo -level 2 something-else yet-something-else".split(" ")))
.resolvedValue();
assertThat(resolved.getName()).isEqualTo("foo");
assertThat(resolved.getLevel()).isEqualTo(2);
assertThat(resolved.getRest()).containsOnlyOnce("something-else", "yet-something-else");
}
@Test
public void testDescribe() {
MethodParameter methodParameter = Utils.createMethodParameter(COMMAND_METHOD, 0);
Stream<ParameterDescription> desciptions = resolver.describe(methodParameter);
ParameterDescription name = new ParameterDescription(methodParameter, "string")
.keys(Arrays.asList("--name", "-n"))
.help("what's in a name?")
.defaultValue("");
ParameterDescription level = new ParameterDescription(methodParameter, "int")
.keys(singletonList("-level"))
.defaultValue("3");
ParameterDescription rest = new ParameterDescription(methodParameter, "list")
.defaultValue("[]")
.mandatoryKey(false)
.help("rest");
assertThat(desciptions).contains(name, level, rest);
}
@Test
public void testCanComplete() {
MethodParameter methodParameter = Utils.createMethodParameter(COMMAND_METHOD, 0);
CompletionContext context = new CompletionContext(Collections.emptyList(), 0, 0);
Stream<String> proposals = resolver.complete(methodParameter, context).stream().map(CompletionProposal::value);
assertThat(proposals).containsExactly("--name", "-n", "-level");
context = new CompletionContext(Arrays.asList("-n", "foo"), 0, 0);
proposals = resolver.complete(methodParameter, context).stream().map(CompletionProposal::value);
assertThat(proposals).containsExactly("-level");
}
@Test
public void testCannotComplete() {
MethodParameter methodParameter = Utils.createMethodParameter(COMMAND_METHOD, 0);
CompletionContext context = new CompletionContext(Arrays.asList("--name"), 0, 0);
Stream<String> proposals = resolver.complete(methodParameter, context).stream().map(CompletionProposal::value);
assertThat(proposals).isEmpty();
}
}

View File

@@ -0,0 +1,40 @@
/*
* 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.jcommander;
/**
* An hypothetical command class, with one method using JCommander args, and the other not.
*
* @author Eric Bottard
*/
public class MyLordCommands {
/**
* This method should be supported.
*/
public void genesis(FieldCollins fieldCollins) {
}
/**
* This method is not.
*/
public void apocalypse(String param) {
}
}