Prevent double registration of commands

This commit is contained in:
Eric Bottard
2017-08-07 12:06:36 +02:00
parent 6497df181d
commit c8e4752119
11 changed files with 182 additions and 41 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;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
/**
* A {@link CommandRegistry} that supports registration of new commands.
*
* <p>Makes sure that no two commands are registered with the same name.</p>
*
* @author Eric Bottard
*/
public class ConfigurableCommandRegistry implements CommandRegistry {
private Map<String, MethodTarget> commands = new HashMap<>();
@Override
public Map<String, MethodTarget> listCommands() {
return new TreeMap<>(commands);
}
public void register(String name, MethodTarget target) {
MethodTarget previous = commands.get(name);
if (previous != null) {
throw new IllegalArgumentException(
String.format("Illegal registration for command '%s': Attempt to register both '%s' and '%s'", name, target, previous));
}
commands.put(name, target);
}
}

View File

@@ -16,19 +16,17 @@
package org.springframework.shell;
import java.util.Map;
/**
* Strategy interface for discovering commands.
* Strategy interface for registering commands.
*
* @author Eric Bottard
* @author Camilo Gonzalez
*/
public interface MethodTargetResolver {
public interface MethodTargetRegistrar {
/**
* Return a mapping from {@literal <command keyword(s)>} to actual behavior.
* Register mappings from {@literal <command keyword(s)>} to actual behavior.
*/
public Map<String, MethodTarget> resolve();
void register(ConfigurableCommandRegistry registry);
}

View File

@@ -33,8 +33,6 @@ import javax.validation.Validation;
import javax.validation.executable.ExecutableValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.core.MethodParameter;
import org.springframework.util.ReflectionUtils;
@@ -80,9 +78,11 @@ public class Shell implements CommandRegistry {
@PostConstruct
public void gatherMethodTargets() throws Exception {
for (MethodTargetResolver resolver : applicationContext.getBeansOfType(MethodTargetResolver.class).values()) {
methodTargets.putAll(resolver.resolve());
ConfigurableCommandRegistry registry = new ConfigurableCommandRegistry();
for (MethodTargetRegistrar resolver : applicationContext.getBeansOfType(MethodTargetRegistrar.class).values()) {
resolver.register(registry);
}
methodTargets = registry.listCommands();
}
/**

View File

@@ -0,0 +1,59 @@
/*
* 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;
import static org.hamcrest.collection.IsMapContaining.hasEntry;
import static org.hamcrest.collection.IsMapContaining.hasKey;
import static org.junit.Assert.*;
import org.hamcrest.collection.IsMapContaining;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
/**
* Unit tests for {@link ConfigurableCommandRegistry}.
*
* @author Eric Bottard
*/
public class ConfigurableCommandRegistryTest {
@Rule
public ExpectedException thrown= ExpectedException.none();
@Test
public void testRegistration() {
ConfigurableCommandRegistry registry = new ConfigurableCommandRegistry();
registry.register("foo", MethodTarget.of("toString", this, "some command"));
assertThat(registry.listCommands(), hasKey("foo"));
}
@Test
public void testDoubleRegistration() {
ConfigurableCommandRegistry registry = new ConfigurableCommandRegistry();
registry.register("foo", MethodTarget.of("toString", this, "some command"));
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("foo");
thrown.expectMessage("toString");
thrown.expectMessage("hashCode");
registry.register("foo", MethodTarget.of("hashCode", this, "some command"));
}
}

View File

@@ -35,7 +35,7 @@ import org.springframework.stereotype.Component;
*
* @author Eric Bottard
*/
@ShellComponent("")
@ShellComponent()
public class Commands {
@ShellMethod(help = "a command whose name looks the same as another one", value = "help me out")

View File

@@ -35,8 +35,8 @@ import org.springframework.shell.converters.SimpleFileConverter;
public class LegacyAdapterAutoConfiguration {
@Bean
public LegacyMethodTargetResolver legacyMethodTargetResolver() {
return new LegacyMethodTargetResolver();
public LegacyMethodTargetRegistrar legacyMethodTargetResolver() {
return new LegacyMethodTargetRegistrar();
}
@Bean

View File

@@ -20,18 +20,20 @@ import static org.springframework.util.StringUtils.collectionToDelimitedString;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.shell.ConfigurableCommandRegistry;
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.shell.MethodTargetRegistrar;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;
/**
* A {@link MethodTargetResolver} that discovers methods annotated with {@link CliCommand} on beans
* A {@link MethodTargetRegistrar} that discovers methods annotated with {@link CliCommand} on beans
* implementing the {@link CommandMarker} marker interface.
*
* @author Eric Bottard
@@ -39,31 +41,33 @@ import org.springframework.util.ReflectionUtils;
* @author Camilo Gonzalez
*/
@Component
public class LegacyMethodTargetResolver implements MethodTargetResolver {
public class LegacyMethodTargetRegistrar implements MethodTargetRegistrar {
@Autowired
private ApplicationContext applicationContext;
private Map<String, MethodTarget> commands = new TreeMap<>();
@Override
public Map<String, MethodTarget> resolve() {
Map<String, MethodTarget> methodTargets = new HashMap<>();
public void register(ConfigurableCommandRegistry registry) {
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()));
MethodTarget target = new MethodTarget(method, bean, cliCommand.help());
registry.register(key, target);
commands.put(key, target);
}
}, method -> method.getAnnotation(CliCommand.class) != null);
}
return methodTargets;
}
@Override
public String toString() {
return getClass().getSimpleName() + " contributing "
+ collectionToDelimitedString(resolve().keySet(), ", ", "[", "]");
+ collectionToDelimitedString(commands.keySet(), ", ", "[", "]");
}
}

View File

@@ -27,27 +27,32 @@ 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.ConfigurableCommandRegistry;
import org.springframework.shell.MethodTarget;
import org.springframework.shell.MethodTargetResolver;
import org.springframework.shell.MethodTargetRegistrar;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Created by ericbottard on 09/12/15.
* Unit tests for {@link LegacyMethodTargetRegistrar}.
*
* @author Eric Bottard
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = LegacyMethodTargetResolverTest.Config.class)
public class LegacyMethodTargetResolverTest {
@ContextConfiguration(classes = LegacyMethodTargetRegistrarTest.Config.class)
public class LegacyMethodTargetRegistrarTest {
@Autowired
private LegacyCommands legacyCommands;
@Autowired
private MethodTargetResolver resolver;
private MethodTargetRegistrar resolver;
@Test
public void findsMethodsAnnotatedWithCliCommand() throws Exception {
Map<String, MethodTarget> targets = resolver.resolve();
ConfigurableCommandRegistry registry = new ConfigurableCommandRegistry();
resolver.register(registry);
Map<String, MethodTarget> targets = registry.listCommands();
assertThat(targets).contains(entry(
"register module",
@@ -64,8 +69,8 @@ public class LegacyMethodTargetResolverTest {
}
@Bean
public MethodTargetResolver methodTargetResolver() {
return new LegacyMethodTargetResolver();
public MethodTargetRegistrar methodTargetResolver() {
return new LegacyMethodTargetRegistrar();
}
}

View File

@@ -0,0 +1,26 @@
/*
* 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.commands;
/**
* Tests for {@link StandardCommandsAutoConfiguration}.
*
* @author Eric Bottard
*/
public class StandardCommandsAutoConfigurationTest {
}

View File

@@ -20,7 +20,7 @@ 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.MethodTargetRegistrar;
import org.springframework.shell.ParameterResolver;
/**
@@ -42,8 +42,8 @@ public class StandardAPIAutoConfiguration {
}
@Bean
public MethodTargetResolver standardMethodTargetResolver() {
return new StandardMethodTargetResolver();
public MethodTargetRegistrar standardMethodTargetResolver() {
return new StandardMethodTargetRegistrar();
}
@Bean

View File

@@ -23,27 +23,28 @@ import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.shell.ConfigurableCommandRegistry;
import org.springframework.shell.MethodTarget;
import org.springframework.shell.MethodTargetResolver;
import org.springframework.stereotype.Component;
import org.springframework.shell.MethodTargetRegistrar;
import org.springframework.util.ReflectionUtils;
/**
* The standard implementation of {@link MethodTargetResolver} for new shell applications,
* The standard implementation of {@link MethodTargetRegistrar} 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 {
public class StandardMethodTargetRegistrar implements MethodTargetRegistrar {
@Autowired
private ApplicationContext applicationContext;
private Map<String, MethodTarget> commands = new HashMap<>();
@Override
public Map<String, MethodTarget> resolve() {
Map<String, MethodTarget> methodTargets = new HashMap<>();
public void register(ConfigurableCommandRegistry registry) {
Map<String, Object> commandBeans = applicationContext.getBeansWithAnnotation(ShellComponent.class);
for (Object bean : commandBeans.values()) {
Class<?> clazz = bean.getClass();
@@ -54,16 +55,17 @@ public class StandardMethodTargetResolver implements MethodTargetResolver {
keys = new String[] {method.getName()};
}
for (String key : keys) {
methodTargets.put(key, new MethodTarget(method, bean, shellMapping.help()));
MethodTarget target = new MethodTarget(method, bean, shellMapping.help());
registry.register(key, target);
commands.put(key, target);
}
}, method -> method.getAnnotation(ShellMethod.class) != null);
}
return methodTargets;
}
@Override
public String toString() {
return getClass().getSimpleName() + " contributing "
+ collectionToDelimitedString(resolve().keySet(), ", ", "[", "]");
+ collectionToDelimitedString(commands.keySet(), ", ", "[", "]");
}
}