Add parameter injectors (#104)

This commit is contained in:
Alexander Söderberg 2020-10-25 05:45:38 +01:00
parent e4efffe577
commit c2065aabd1
11 changed files with 469 additions and 17 deletions

View file

@ -26,6 +26,8 @@ package cloud.commandframework.annotations;
import cloud.commandframework.Command;
import cloud.commandframework.CommandManager;
import cloud.commandframework.Description;
import cloud.commandframework.annotations.injection.ParameterInjectorRegistry;
import cloud.commandframework.annotations.injection.RawArgs;
import cloud.commandframework.arguments.CommandArgument;
import cloud.commandframework.arguments.flags.CommandFlag;
import cloud.commandframework.arguments.parser.ArgumentParseResult;
@ -70,6 +72,7 @@ public final class AnnotationParser<C> {
private final SyntaxParser syntaxParser = new SyntaxParser();
private final ArgumentExtractor argumentExtractor = new ArgumentExtractor();
private final ParameterInjectorRegistry<C> parameterInjectorRegistry = new ParameterInjectorRegistry<>();
private final CommandManager<C> manager;
private final Map<Class<? extends Annotation>, Function<? extends Annotation, ParserParameters>> annotationMappers;
@ -106,16 +109,26 @@ public final class AnnotationParser<C> {
annotation.value(),
Caption.of(annotation.failureCaption())
));
this.getParameterInjectorRegistry().registerInjector(
CommandContext.class,
(context, annotations) -> context
);
this.getParameterInjectorRegistry().registerInjector(
String[].class,
(context, annotations) -> annotations.annotation(RawArgs.class) == null
? null
: context.getRawInput().toArray(new String[0])
);
}
@SuppressWarnings("unchecked")
static <A extends Annotation> @Nullable A getAnnotationRecursively(
final @NonNull Annotation[] annotations,
final @NonNull AnnotationAccessor annotations,
final @NonNull Class<A> clazz,
final @NonNull Set<Class<? extends Annotation>> checkedAnnotations
) {
A innerCandidate = null;
for (final Annotation annotation : annotations) {
for (final Annotation annotation : annotations.annotations()) {
if (!checkedAnnotations.add(annotation.annotationType())) {
continue;
}
@ -125,7 +138,10 @@ public final class AnnotationParser<C> {
if (annotation.annotationType().getPackage().getName().startsWith("java.lang")) {
continue;
}
final A inner = getAnnotationRecursively(annotation.annotationType().getAnnotations(), clazz, checkedAnnotations);
final A inner = getAnnotationRecursively(
AnnotationAccessor.of(annotation.annotationType()),
clazz,
checkedAnnotations);
if (inner != null) {
innerCandidate = inner;
}
@ -137,9 +153,17 @@ public final class AnnotationParser<C> {
final @NonNull Method method,
final @NonNull Class<A> clazz
) {
A annotation = getAnnotationRecursively(method.getAnnotations(), clazz, new HashSet<>());
A annotation = getAnnotationRecursively(
AnnotationAccessor.of(method),
clazz,
new HashSet<>()
);
if (annotation == null) {
annotation = getAnnotationRecursively(method.getDeclaringClass().getAnnotations(), clazz, new HashSet<>());
annotation = getAnnotationRecursively(
AnnotationAccessor.of(method.getDeclaringClass()),
clazz,
new HashSet<>()
);
}
return annotation;
}
@ -181,6 +205,17 @@ public final class AnnotationParser<C> {
this.preprocessorMappers.put(annotation, preprocessorMapper);
}
/**
* Get the parameter injector registry instance that is used to inject non-{@link Argument argument} parameters
* into {@link CommandMethod} annotated {@link Method methods}
*
* @return Parameter injector registry
* @since 1.2.0
*/
public @NonNull ParameterInjectorRegistry<C> getParameterInjectorRegistry() {
return this.parameterInjectorRegistry;
}
/**
* Scan a class instance of {@link CommandMethod} annotations and attempt to
* compile them into {@link Command} instances
@ -302,7 +337,7 @@ public final class AnnotationParser<C> {
try {
/* Construct the handler */
final CommandExecutionHandler<C> commandExecutionHandler
= new MethodCommandExecutionHandler<>(instance, commandArguments, method);
= new MethodCommandExecutionHandler<>(instance, commandArguments, method, this.parameterInjectorRegistry);
builder = builder.handler(commandExecutionHandler);
} catch (final Exception e) {
throw new RuntimeException("Failed to construct command execution handler", e);
@ -399,10 +434,10 @@ public final class AnnotationParser<C> {
this.manager.getParserRegistry().getSuggestionProvider(suggestionProviderName);
argumentBuilder.withSuggestionsProvider(
suggestionsFunction.orElseThrow(() ->
new IllegalArgumentException(String.format(
"There is no suggestion provider with name '%s'. Did you forget to register it?",
suggestionProviderName
)))
new IllegalArgumentException(String.format(
"There is no suggestion provider with name '%s'. Did you forget to register it?",
suggestionProviderName
)))
);
}
/* Build the argument */

View file

@ -23,6 +23,8 @@
//
package cloud.commandframework.annotations;
import cloud.commandframework.annotations.injection.ParameterInjector;
import cloud.commandframework.annotations.injection.ParameterInjectorRegistry;
import cloud.commandframework.arguments.CommandArgument;
import cloud.commandframework.arguments.flags.FlagContext;
import cloud.commandframework.context.CommandContext;
@ -34,6 +36,7 @@ import java.lang.invoke.MethodHandles;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
@ -42,17 +45,21 @@ class MethodCommandExecutionHandler<C> implements CommandExecutionHandler<C> {
private final Parameter[] parameters;
private final MethodHandle methodHandle;
private final Map<String, CommandArgument<C, ?>> commandArguments;
private final ParameterInjectorRegistry<C> injectorRegistry;
private final AnnotationAccessor annotationAccessor;
MethodCommandExecutionHandler(
final @NonNull Object instance,
final @NonNull Map<@NonNull String,
@NonNull CommandArgument<@NonNull C, @NonNull ?>> commandArguments,
@NonNull final Method method
final @NonNull Map<@NonNull String, @NonNull CommandArgument<@NonNull C, @NonNull ?>> commandArguments,
final @NonNull Method method,
final @NonNull ParameterInjectorRegistry<C> injectorRegistry
) throws Exception {
this.commandArguments = commandArguments;
method.setAccessible(true);
this.methodHandle = MethodHandles.lookup().unreflect(method).bindTo(instance);
this.parameters = method.getParameters();
this.injectorRegistry = injectorRegistry;
this.annotationAccessor = AnnotationAccessor.of(method);
}
@Override
@ -82,10 +89,25 @@ class MethodCommandExecutionHandler<C> implements CommandExecutionHandler<C> {
if (parameter.getType().isAssignableFrom(commandContext.getSender().getClass())) {
arguments.add(commandContext.getSender());
} else {
throw new IllegalArgumentException(String.format(
"Unknown command parameter '%s' in method '%s'",
parameter.getName(), this.methodHandle.toString()
));
final Collection<ParameterInjector<C, ?>> injectors = this.injectorRegistry.injectors(parameter.getType());
Object value = null;
for (final ParameterInjector<C, ?> injector : injectors) {
value = injector.create(
commandContext,
this.annotationAccessor
);
if (value != null) {
break;
}
}
if (value != null) {
arguments.add(value);
} else {
throw new IllegalArgumentException(String.format(
"Unknown command parameter '%s' in method '%s'",
parameter.getName(), this.methodHandle.toString()
));
}
}
}
}

View file

@ -0,0 +1,53 @@
//
// MIT License
//
// Copyright (c) 2020 Alexander Söderberg & Contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
package cloud.commandframework.annotations.injection;
import cloud.commandframework.annotations.AnnotationAccessor;
import cloud.commandframework.context.CommandContext;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Injector that injects parameters into {@link cloud.commandframework.annotations.CommandMethod} annotated
* methods
*
* @param <C> Command sender type
* @param <T> Type of the value that is injected by this injector
* @since 1.2.0
*/
@FunctionalInterface
public interface ParameterInjector<C, T> {
/**
* Attempt to create a a value that should then be injected into the {@link cloud.commandframework.annotations.CommandMethod}
* annotated method. If the injector cannot (or shouldn't) create a value, it is free to return {@code null}.
*
* @param context Command context that is requesting the injection
* @param annotationAccessor Annotation accessor proxying the method which the value is being injected into
* @return The value, if it could be created. Else {@code null}, in which case no value will be injected
* by this particular injector
*/
@Nullable T create(@NonNull CommandContext<C> context, @NonNull AnnotationAccessor annotationAccessor);
}

View file

@ -0,0 +1,82 @@
//
// MIT License
//
// Copyright (c) 2020 Alexander Söderberg & Contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
package cloud.commandframework.annotations.injection;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* Registry containing mappings between {@link Class classes} and {@link ParameterInjector injectors}
*
* @param <C> Command sender type
* @since 1.2.0
*/
public final class ParameterInjectorRegistry<C> {
private volatile int injectorCount = 0;
private final Map<Class<?>, List<ParameterInjector<C, ?>>> injectors = new HashMap<>();
/**
* Register an injector for a particular type
*
* @param clazz Type that the injector should inject for. This type will matched using
* {@link Class#isAssignableFrom(Class)}
* @param injector The injector that should inject the value into the command method
* @param <T> Injected type
*/
public synchronized <T> void registerInjector(
final @NonNull Class<T> clazz,
final @NonNull ParameterInjector<C, T> injector
) {
this.injectors.computeIfAbsent(clazz, missingClass -> new LinkedList<>()).add(injector);
this.injectorCount++;
}
/**
* Get a collection of all injectors that could potentially inject a value of the given type
*
* @param clazz Type to query for
* @param <T> Generic type
* @return Immutable collection containing all injectors that could potentially inject a value of the given type
*/
public synchronized <T> @NonNull Collection<@NonNull ParameterInjector<C, ?>> injectors(
final @NonNull Class<T> clazz
) {
final List<@NonNull ParameterInjector<C, ?>> injectors = new ArrayList<>(this.injectorCount);
for (final Map.Entry<Class<?>, List<ParameterInjector<C, ?>>> entry : this.injectors.entrySet()) {
if (clazz.isAssignableFrom(entry.getKey())) {
injectors.addAll(entry.getValue());
}
}
return Collections.unmodifiableCollection(injectors);
}
}

View file

@ -0,0 +1,41 @@
//
// MIT License
//
// Copyright (c) 2020 Alexander Söderberg & Contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
package cloud.commandframework.annotations.injection;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Used to inject {@link cloud.commandframework.context.CommandContext#getRawInput()} into a
* {@link cloud.commandframework.annotations.CommandMethod}
* <p>
* This should only be used on {@code String[]}
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RawArgs {
}

View file

@ -0,0 +1,28 @@
//
// MIT License
//
// Copyright (c) 2020 Alexander Söderberg & Contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
/**
* Classes related to parameter injection
*/
package cloud.commandframework.annotations.injection;

View file

@ -61,6 +61,11 @@ class AnnotationParserTest {
"some-name",
(context, input) -> NAMED_SUGGESTIONS
);
/* Register a parameter injector */
annotationParser.getParameterInjectorRegistry().registerInjector(
InjectableValue.class,
(context, annotations) -> new InjectableValue("Hello World!")
);
}
@Test
@ -109,6 +114,11 @@ class AnnotationParserTest {
final Regex regex = AnnotationParser.getMethodOrClassAnnotation(annotatedMethod, Regex.class);
}
@Test
void testParameterInjection() {
manager.executeCommand(new TestCommandSender(), "inject").join();
}
@ProxiedBy("proxycommand")
@CommandMethod("test|t literal <int> [string]")
public void testCommand(
@ -136,6 +146,12 @@ class AnnotationParserTest {
) {
}
@CommandMethod("inject")
public void testInjectedParameters(
final InjectableValue injectableValue
) {
System.out.printf("Injected value: %s\n", injectableValue.toString());
}
@CommandPermission("some.permission")
@Target(ElementType.METHOD)
@ -169,4 +185,20 @@ class AnnotationParserTest {
private @interface Bad2 {
}
private static final class InjectableValue {
private final String value;
private InjectableValue(final String value) {
this.value = value;
}
@Override
public String toString() {
return this.value;
}
}
}