Clean up generics (and get rid of the type parameter for command meta data)

This commit is contained in:
Alexander Söderberg 2020-09-19 12:14:09 +02:00
parent 1a85251fc6
commit ccd0e8ae0e
No known key found for this signature in database
GPG key ID: C0207FF7EA146678
50 changed files with 577 additions and 596 deletions

View file

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
@ -25,7 +26,7 @@ public class MavenWrapperDownloader {
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
@ -54,7 +55,7 @@ public class MavenWrapperDownloader {
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if(mavenWrapperPropertyFile.exists()) {
if (mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
@ -65,7 +66,7 @@ public class MavenWrapperDownloader {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if(mavenWrapperPropertyFileInputStream != null) {
if (mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
@ -76,8 +77,8 @@ public class MavenWrapperDownloader {
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if(!outputFile.getParentFile().exists()) {
if(!outputFile.getParentFile().mkdirs()) {
if (!outputFile.getParentFile().exists()) {
if (!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}

View file

@ -57,7 +57,7 @@ import java.util.regex.Pattern;
* @param <C> Command sender type
* @param <M> Command meta type
*/
public final class AnnotationParser<C, M extends CommandMeta> {
public final class AnnotationParser<C> {
private static final Predicate<String> PATTERN_ARGUMENT_LITERAL = Pattern.compile("([A-Za-z0-9]+)(|([A-Za-z0-9]+))*")
.asPredicate();
@ -67,8 +67,8 @@ public final class AnnotationParser<C, M extends CommandMeta> {
.asPredicate();
private final Function<ParserParameters, M> metaMapper;
private final CommandManager<C, M> manager;
private final Function<ParserParameters, CommandMeta> metaMapper;
private final CommandManager<C> manager;
private final Map<Class<? extends Annotation>, Function<? extends Annotation, ParserParameters>> annotationMappers;
private final Class<C> commandSenderClass;
@ -82,9 +82,9 @@ public final class AnnotationParser<C, M extends CommandMeta> {
* {@link com.intellectualsites.commands.arguments.parser.ParserParameter}. Mappers for the
* parser parameters can be registered using {@link #registerAnnotationMapper(Class, Function)}
*/
public AnnotationParser(@Nonnull final CommandManager<C, M> manager,
public AnnotationParser(@Nonnull final CommandManager<C> manager,
@Nonnull final Class<C> commandSenderClass,
@Nonnull final Function<ParserParameters, M> metaMapper) {
@Nonnull final Function<ParserParameters, CommandMeta> metaMapper) {
this.commandSenderClass = commandSenderClass;
this.manager = manager;
this.metaMapper = metaMapper;
@ -105,7 +105,7 @@ public final class AnnotationParser<C, M extends CommandMeta> {
}
@Nonnull
private M createMeta(@Nonnull final Annotation[] annotations) {
private CommandMeta createMeta(@Nonnull final Annotation[] annotations) {
final ParserParameters parameters = ParserParameters.empty();
for (final Annotation annotation : annotations) {
@SuppressWarnings("ALL") final Function function = this.annotationMappers.get(annotation.annotationType());
@ -127,7 +127,7 @@ public final class AnnotationParser<C, M extends CommandMeta> {
* @return Collection of parsed annotations
*/
@Nonnull
public <T> Collection<Command<C, M>> parse(@Nonnull final T instance) {
public <T> Collection<Command<C>> parse(@Nonnull final T instance) {
final Method[] methods = instance.getClass().getDeclaredMethods();
final Collection<CommandMethodPair> commandMethodPairs = new ArrayList<>();
for (final Method method : methods) {
@ -144,28 +144,31 @@ public final class AnnotationParser<C, M extends CommandMeta> {
}
commandMethodPairs.add(new CommandMethodPair(method, commandMethod));
}
final Collection<Command<C, M>> commands = this.construct(instance, commandMethodPairs);
for (final Command<C, M> command : commands) {
this.manager.command(command);
final Collection<Command<C>> commands = this.construct(instance, commandMethodPairs);
for (final Command<C> command : commands) {
@SuppressWarnings("ALL") final CommandManager commandManager = this.manager;
//noinspection all
commandManager.command(command);
}
return commands;
}
@Nonnull
@SuppressWarnings("unchecked")
private Collection<Command<C, M>> construct(@Nonnull final Object instance,
@Nonnull final Collection<CommandMethodPair> methodPairs) {
final Collection<Command<C, M>> commands = new ArrayList<>();
private Collection<Command<C>> construct(@Nonnull final Object instance,
@Nonnull final Collection<CommandMethodPair> methodPairs) {
final Collection<Command<C>> commands = new ArrayList<>();
for (final CommandMethodPair commandMethodPair : methodPairs) {
final CommandMethod commandMethod = commandMethodPair.getCommandMethod();
final Method method = commandMethodPair.getMethod();
final LinkedHashMap<String, SyntaxFragment> tokens = this.parseSyntax(commandMethod.value());
/* Determine command name */
final String commandToken = commandMethod.value().split(" ")[0].split("\\|")[0];
@SuppressWarnings("ALL") final CommandManager manager = this.manager;
@SuppressWarnings("ALL")
Command.Builder builder = this.manager.commandBuilder(commandToken,
tokens.get(commandToken).getMinor(),
this.createMeta(method.getAnnotations()));
Command.Builder builder = manager.commandBuilder(commandToken,
tokens.get(commandToken).getMinor(),
this.createMeta(method.getAnnotations()));
final Collection<ArgumentParameterPair> arguments = this.getArguments(method);
final Map<String, CommandArgument<C, ?>> commandArguments = Maps.newHashMap();
/* Go through all annotated parameters and build up the argument tree */
@ -270,7 +273,7 @@ public final class AnnotationParser<C, M extends CommandMeta> {
if (syntaxFragment == null || syntaxFragment.getArgumentMode() == ArgumentMode.LITERAL) {
throw new IllegalArgumentException(String.format(
"Invalid command argument '%s' in method '%s': "
+ "Missing syntax mapping", argumentPair.getArgument().value(), method.getName()));
+ "Missing syntax mapping", argumentPair.getArgument().value(), method.getName()));
}
final Argument argument = argumentPair.getArgument();
@SuppressWarnings("ALL") final CommandArgument.Builder argumentBuilder = CommandArgument.ofType(parameter.getType(),
@ -329,6 +332,12 @@ public final class AnnotationParser<C, M extends CommandMeta> {
}
enum ArgumentMode {
LITERAL,
OPTIONAL,
REQUIRED
}
private static final class CommandMethodPair {
private final Method method;
@ -351,7 +360,6 @@ public final class AnnotationParser<C, M extends CommandMeta> {
}
private static final class ArgumentParameterPair {
private final Parameter parameter;
@ -374,14 +382,6 @@ public final class AnnotationParser<C, M extends CommandMeta> {
}
enum ArgumentMode {
LITERAL,
OPTIONAL,
REQUIRED
}
private static final class SyntaxFragment {
private final String major;

View file

@ -37,7 +37,7 @@ import java.util.concurrent.CompletionException;
class AnnotationParserTest {
private static CommandManager<TestCommandSender, SimpleCommandMeta> manager;
private static CommandManager<TestCommandSender> manager;
private static AnnotationParser<TestCommandSender, SimpleCommandMeta> annotationParser;
@BeforeAll
@ -48,7 +48,7 @@ class AnnotationParserTest {
@Test
void testMethodConstruction() {
final Collection<Command<TestCommandSender, SimpleCommandMeta>> commands = annotationParser.parse(this);
final Collection<Command<TestCommandSender>> commands = annotationParser.parse(this);
Assertions.assertFalse(commands.isEmpty());
manager.executeCommand(new TestCommandSender(), "test 10").join();
manager.executeCommand(new TestCommandSender(), "t 10").join();

View file

@ -30,7 +30,7 @@ import com.intellectualsites.commands.meta.SimpleCommandMeta;
import javax.annotation.Nonnull;
public class TestCommandManager extends CommandManager<TestCommandSender, SimpleCommandMeta> {
public class TestCommandManager extends CommandManager<TestCommandSender> {
protected TestCommandManager() {
super(CommandExecutionCoordinator.simpleCoordinator(), CommandRegistrationHandler.nullCommandRegistrationHandler());

View file

@ -41,21 +41,20 @@ import java.util.function.Consumer;
* A command consists out of a chain of {@link CommandArgument command arguments}.
*
* @param <C> Command sender type
* @param <M> Command meta type
*/
@SuppressWarnings("unused")
public class Command<C, M extends CommandMeta> {
public class Command<C> {
@Nonnull private final List<CommandArgument<C, ?>> arguments;
@Nonnull private final CommandExecutionHandler<C> commandExecutionHandler;
@Nullable private final Class<? extends C> senderType;
@Nonnull private final String commandPermission;
@Nonnull private final M commandMeta;
@Nonnull private final CommandMeta commandMeta;
/**
* Construct a new command
*
* @param commandArguments Command arguments
* @param commandArguments Command arguments
* @param commandExecutionHandler Execution handler
* @param senderType Required sender type. May be {@code null}
* @param commandPermission Command permission
@ -65,7 +64,7 @@ public class Command<C, M extends CommandMeta> {
@Nonnull final CommandExecutionHandler<C> commandExecutionHandler,
@Nullable final Class<? extends C> senderType,
@Nonnull final String commandPermission,
@Nonnull final M commandMeta) {
@Nonnull final CommandMeta commandMeta) {
this.arguments = Objects.requireNonNull(commandArguments, "Command arguments may not be null");
if (this.arguments.size() == 0) {
throw new IllegalArgumentException("At least one command argument is required");
@ -93,7 +92,7 @@ public class Command<C, M extends CommandMeta> {
/**
* Construct a new command
*
* @param commandArguments Command arguments
* @param commandArguments Command arguments
* @param commandExecutionHandler Execution handler
* @param senderType Required sender type. May be {@code null}
* @param commandMeta Command meta instance
@ -101,14 +100,14 @@ public class Command<C, M extends CommandMeta> {
public Command(@Nonnull final List<CommandArgument<C, ?>> commandArguments,
@Nonnull final CommandExecutionHandler<C> commandExecutionHandler,
@Nullable final Class<? extends C> senderType,
@Nonnull final M commandMeta) {
@Nonnull final CommandMeta commandMeta) {
this(commandArguments, commandExecutionHandler, senderType, "", commandMeta);
}
/**
* Construct a new command
*
* @param commandArguments Command arguments
* @param commandArguments Command arguments
* @param commandExecutionHandler Execution handler
* @param commandPermission Command permission
* @param commandMeta Command meta instance
@ -116,7 +115,7 @@ public class Command<C, M extends CommandMeta> {
public Command(@Nonnull final List<CommandArgument<C, ?>> commandArguments,
@Nonnull final CommandExecutionHandler<C> commandExecutionHandler,
@Nonnull final String commandPermission,
@Nonnull final M commandMeta) {
@Nonnull final CommandMeta commandMeta) {
this(commandArguments, commandExecutionHandler, null, "", commandMeta);
}
@ -127,13 +126,12 @@ public class Command<C, M extends CommandMeta> {
* @param commandMeta Command meta instance
* @param aliases Command aliases
* @param <C> Command sender type
* @param <M> Command meta type
* @return Command builder
*/
@Nonnull
public static <C, M extends CommandMeta> Builder<C, M> newBuilder(@Nonnull final String commandName,
@Nonnull final M commandMeta,
@Nonnull final String... aliases) {
public static <C> Builder<C> newBuilder(@Nonnull final String commandName,
@Nonnull final CommandMeta commandMeta,
@Nonnull final String... aliases) {
return new Builder<>(null, commandMeta, null,
Collections.singletonList(StaticArgument.required(commandName, aliases)),
new CommandExecutionHandler.NullCommandExecutionHandler<>(), "");
@ -185,7 +183,7 @@ public class Command<C, M extends CommandMeta> {
* @return Command meta
*/
@Nonnull
public M getCommandMeta() {
public CommandMeta getCommandMeta() {
return this.commandMeta;
}
@ -196,7 +194,7 @@ public class Command<C, M extends CommandMeta> {
* @param other Command to compare to
* @return List containing the longest shared argument chain
*/
public List<CommandArgument<C, ?>> getSharedArgumentChain(@Nonnull final Command<C, M> other) {
public List<CommandArgument<C, ?>> getSharedArgumentChain(@Nonnull final Command<C> other) {
final List<CommandArgument<C, ?>> commandArguments = new LinkedList<>();
for (int i = 0; i < this.arguments.size() && i < other.arguments.size(); i++) {
if (this.arguments.get(i).equals(other.arguments.get(i))) {
@ -214,19 +212,18 @@ public class Command<C, M extends CommandMeta> {
* setter method will return a new builder instance.
*
* @param <C> Command sender type
* @param <M> Command meta type
*/
public static final class Builder<C, M extends CommandMeta> {
public static final class Builder<C> {
@Nonnull private final M commandMeta;
@Nonnull private final CommandMeta commandMeta;
@Nonnull private final List<CommandArgument<C, ?>> commandArguments;
@Nonnull private final CommandExecutionHandler<C> commandExecutionHandler;
@Nullable private final Class<? extends C> senderType;
@Nonnull private final String commandPermission;
@Nullable private final CommandManager<C, M> commandManager;
@Nullable private final CommandManager<C> commandManager;
private Builder(@Nullable final CommandManager<C, M> commandManager,
@Nonnull final M commandMeta,
private Builder(@Nullable final CommandManager<C> commandManager,
@Nonnull final CommandMeta commandMeta,
@Nullable final Class<? extends C> senderType,
@Nonnull final List<CommandArgument<C, ?>> commandArguments,
@Nonnull final CommandExecutionHandler<C> commandExecutionHandler,
@ -248,7 +245,7 @@ public class Command<C, M extends CommandMeta> {
* @return New builder instance using the provided command manager
*/
@Nonnull
public Builder<C, M> manager(@Nullable final CommandManager<C, M> commandManager) {
public Builder<C> manager(@Nullable final CommandManager<C> commandManager) {
return new Builder<>(commandManager, this.commandMeta, this.senderType, this.commandArguments,
this.commandExecutionHandler, this.commandPermission);
}
@ -261,7 +258,7 @@ public class Command<C, M extends CommandMeta> {
* @return New builder instance with the modified command chain
*/
@Nonnull
public Builder<C, M> literal(@Nonnull final String main, @Nonnull final String... aliases) {
public Builder<C> literal(@Nonnull final String main, @Nonnull final String... aliases) {
return this.argument(StaticArgument.required(main, aliases));
}
@ -269,11 +266,11 @@ public class Command<C, M extends CommandMeta> {
* Add a new command argument to the command
*
* @param argument Argument to add
* @param <T> Argument type
* @param <T> Argument type
* @return New builder instance with the command argument inserted into the argument list
*/
@Nonnull
public <T> Builder<C, M> argument(@Nonnull final CommandArgument<C, T> argument) {
public <T> Builder<C> argument(@Nonnull final CommandArgument<C, T> argument) {
final List<CommandArgument<C, ?>> commandArguments = new LinkedList<>(this.commandArguments);
commandArguments.add(argument);
return new Builder<>(this.commandManager, this.commandMeta, this.senderType, commandArguments,
@ -290,9 +287,9 @@ public class Command<C, M extends CommandMeta> {
* @return New builder instance with the command argument inserted into the argument list
*/
@Nonnull
public <T> Builder<C, M> argument(@Nonnull final Class<T> clazz,
@Nonnull final String name,
@Nonnull final Consumer<CommandArgument.Builder<C, T>> builderConsumer) {
public <T> Builder<C> argument(@Nonnull final Class<T> clazz,
@Nonnull final String name,
@Nonnull final Consumer<CommandArgument.Builder<C, T>> builderConsumer) {
final CommandArgument.Builder<C, T> builder = CommandArgument.ofType(clazz, name);
if (this.commandManager != null) {
builder.manager(this.commandManager);
@ -308,7 +305,7 @@ public class Command<C, M extends CommandMeta> {
* @return New builder instance using the command execution handler
*/
@Nonnull
public Builder<C, M> handler(@Nonnull final CommandExecutionHandler<C> commandExecutionHandler) {
public Builder<C> handler(@Nonnull final CommandExecutionHandler<C> commandExecutionHandler) {
return new Builder<>(this.commandManager, this.commandMeta, this.senderType, this.commandArguments,
commandExecutionHandler, this.commandPermission);
}
@ -320,7 +317,7 @@ public class Command<C, M extends CommandMeta> {
* @return New builder instance using the command execution handler
*/
@Nonnull
public Builder<C, M> withSenderType(@Nonnull final Class<? extends C> senderType) {
public Builder<C> withSenderType(@Nonnull final Class<? extends C> senderType) {
return new Builder<>(this.commandManager, this.commandMeta, senderType, this.commandArguments,
this.commandExecutionHandler, this.commandPermission);
}
@ -332,7 +329,7 @@ public class Command<C, M extends CommandMeta> {
* @return New builder instance using the command permission
*/
@Nonnull
public Builder<C, M> withPermission(@Nonnull final String permission) {
public Builder<C> withPermission(@Nonnull final String permission) {
return new Builder<>(this.commandManager, this.commandMeta, this.senderType, this.commandArguments,
this.commandExecutionHandler, permission);
}
@ -343,7 +340,7 @@ public class Command<C, M extends CommandMeta> {
* @return Built command
*/
@Nonnull
public Command<C, M> build() {
public Command<C> build() {
return new Command<>(Collections.unmodifiableList(this.commandArguments),
this.commandExecutionHandler, this.senderType, this.commandPermission, this.commandMeta);
}

View file

@ -57,18 +57,17 @@ import java.util.function.Function;
* The manager is responsible for command registration, parsing delegation, etc.
*
* @param <C> Command sender type
* @param <M> Command meta type
*/
@SuppressWarnings("unused")
public abstract class CommandManager<C, M extends CommandMeta> {
public abstract class CommandManager<C> {
private final CommandContextFactory<C> commandContextFactory = new StandardCommandContextFactory<>();
private final ServicePipeline servicePipeline = ServicePipeline.builder().build();
private final ParserRegistry<C> parserRegistry = new StandardParserRegistry<>();
private final CommandExecutionCoordinator<C, M> commandExecutionCoordinator;
private final CommandRegistrationHandler<M> commandRegistrationHandler;
private final CommandTree<C, M> commandTree;
private final CommandExecutionCoordinator<C> commandExecutionCoordinator;
private final CommandRegistrationHandler commandRegistrationHandler;
private final CommandTree<C> commandTree;
private CommandSyntaxFormatter<C> commandSyntaxFormatter = new StandardCommandSyntaxFormatter<>();
private CommandSuggestionProcessor<C> commandSuggestionProcessor = new FilteringCommandSuggestionProcessor<>();
@ -80,8 +79,8 @@ public abstract class CommandManager<C, M extends CommandMeta> {
* @param commandRegistrationHandler Command registration handler
*/
public CommandManager(
@Nonnull final Function<CommandTree<C, M>, CommandExecutionCoordinator<C, M>> commandExecutionCoordinator,
@Nonnull final CommandRegistrationHandler<M> commandRegistrationHandler) {
@Nonnull final Function<CommandTree<C>, CommandExecutionCoordinator<C>> commandExecutionCoordinator,
@Nonnull final CommandRegistrationHandler commandRegistrationHandler) {
this.commandTree = CommandTree.newTree(this, commandRegistrationHandler);
this.commandExecutionCoordinator = commandExecutionCoordinator.apply(commandTree);
this.commandRegistrationHandler = commandRegistrationHandler;
@ -159,7 +158,7 @@ public abstract class CommandManager<C, M extends CommandMeta> {
* @param command Command to register
* @return The command manager instance
*/
public CommandManager<C, M> command(@Nonnull final Command<C, M> command) {
public CommandManager<C> command(@Nonnull final Command<C> command) {
this.commandTree.insertCommand(command);
return this;
}
@ -189,7 +188,7 @@ public abstract class CommandManager<C, M extends CommandMeta> {
* @return Command registration handler
*/
@Nonnull
protected CommandRegistrationHandler<M> getCommandRegistrationHandler() {
protected CommandRegistrationHandler getCommandRegistrationHandler() {
return this.commandRegistrationHandler;
}
@ -211,9 +210,9 @@ public abstract class CommandManager<C, M extends CommandMeta> {
* @return Builder instance
*/
@Nonnull
public Command.Builder<C, M> commandBuilder(@Nonnull final String name,
@Nonnull final Collection<String> aliases,
@Nonnull final M meta) {
public Command.Builder<C> commandBuilder(@Nonnull final String name,
@Nonnull final Collection<String> aliases,
@Nonnull final CommandMeta meta) {
return Command.newBuilder(name, meta, aliases.toArray(new String[0]));
}
@ -222,25 +221,28 @@ public abstract class CommandManager<C, M extends CommandMeta> {
*
* @param name Command name
* @param meta Command meta
* @param aliases Command aliases
* @return Builder instance
*/
@Nonnull
public Command.Builder<C, M> commandBuilder(@Nonnull final String name,
@Nonnull final M meta) {
return Command.newBuilder(name, meta);
public Command.Builder<C> commandBuilder(@Nonnull final String name,
@Nonnull final CommandMeta meta,
@Nonnull final String... aliases) {
return Command.newBuilder(name, meta, aliases);
}
/**
* Create a new command builder using a default command meta instance.
*
* @param name Command name
* @param name Command name
* @param aliases Command aliases
* @return Builder instance
* @throws UnsupportedOperationException If the command manager does not support default command meta creation
* @see #createDefaultCommandMeta() Default command meta creation
*/
@Nonnull
public Command.Builder<C, M> commandBuilder(@Nonnull final String name) {
return Command.<C, M>newBuilder(name, this.createDefaultCommandMeta()).manager(this);
public Command.Builder<C> commandBuilder(@Nonnull final String name, @Nonnull final String... aliases) {
return Command.<C>newBuilder(name, this.createDefaultCommandMeta(), aliases).manager(this);
}
/**
@ -263,7 +265,7 @@ public abstract class CommandManager<C, M extends CommandMeta> {
* @return Command tree
*/
@Nonnull
public CommandTree<C, M> getCommandTree() {
public CommandTree<C> getCommandTree() {
return this.commandTree;
}
@ -274,7 +276,7 @@ public abstract class CommandManager<C, M extends CommandMeta> {
* @throws UnsupportedOperationException If the command manager does not support this operation
*/
@Nonnull
public abstract M createDefaultCommandMeta();
public abstract CommandMeta createDefaultCommandMeta();
/**
* Register a new command preprocessor. The order they are registered in is respected, and they
@ -297,12 +299,12 @@ public abstract class CommandManager<C, M extends CommandMeta> {
*/
public State preprocessContext(@Nonnull final CommandContext<C> context, @Nonnull final LinkedList<String> inputQueue) {
this.servicePipeline.pump(new CommandPreprocessingContext<>(context, inputQueue))
.through(new TypeToken<CommandPreprocessor<C>>() {
})
.getResult();
.through(new TypeToken<CommandPreprocessor<C>>() {
})
.getResult();
return context.<String>get(AcceptingCommandPreprocessor.PROCESSED_INDICATOR_KEY).orElse("").isEmpty()
? State.REJECTED
: State.ACCEPTED;
? State.REJECTED
: State.ACCEPTED;
}
/**

View file

@ -35,7 +35,6 @@ import com.intellectualsites.commands.exceptions.NoCommandInLeafException;
import com.intellectualsites.commands.exceptions.NoPermissionException;
import com.intellectualsites.commands.exceptions.NoSuchCommandException;
import com.intellectualsites.commands.internal.CommandRegistrationHandler;
import com.intellectualsites.commands.meta.CommandMeta;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
@ -57,18 +56,17 @@ import java.util.stream.Collectors;
* Tree containing all commands and command paths
*
* @param <C> Command sender type
* @param <M> Command meta type
*/
public final class CommandTree<C, M extends CommandMeta> {
public final class CommandTree<C> {
private final Object commandLock = new Object();
private final Node<CommandArgument<C, ?>> internalTree = new Node<>(null);
private final CommandManager<C, M> commandManager;
private final CommandRegistrationHandler<M> commandRegistrationHandler;
private final CommandManager<C> commandManager;
private final CommandRegistrationHandler commandRegistrationHandler;
private CommandTree(@Nonnull final CommandManager<C, M> commandManager,
@Nonnull final CommandRegistrationHandler<M> commandRegistrationHandler) {
private CommandTree(@Nonnull final CommandManager<C> commandManager,
@Nonnull final CommandRegistrationHandler commandRegistrationHandler) {
this.commandManager = commandManager;
this.commandRegistrationHandler = commandRegistrationHandler;
}
@ -79,13 +77,12 @@ public final class CommandTree<C, M extends CommandMeta> {
* @param commandManager Command manager
* @param commandRegistrationHandler Command registration handler
* @param <C> Command sender type
* @param <M> Command meta type
* @return New command tree
*/
@Nonnull
public static <C, M extends CommandMeta> CommandTree<C, M> newTree(
@Nonnull final CommandManager<C, M> commandManager,
@Nonnull final CommandRegistrationHandler<M> commandRegistrationHandler) {
public static <C> CommandTree<C> newTree(
@Nonnull final CommandManager<C> commandManager,
@Nonnull final CommandRegistrationHandler commandRegistrationHandler) {
return new CommandTree<>(commandManager, commandRegistrationHandler);
}
@ -99,13 +96,13 @@ public final class CommandTree<C, M extends CommandMeta> {
* @throws NoPermissionException If the sender lacks permission to execute the command
* @throws InvalidSyntaxException If the command syntax is invalid
*/
public Optional<Command<C, M>> parse(@Nonnull final CommandContext<C> commandContext,
@Nonnull final Queue<String> args) throws
public Optional<Command<C>> parse(@Nonnull final CommandContext<C> commandContext,
@Nonnull final Queue<String> args) throws
NoSuchCommandException, NoPermissionException, InvalidSyntaxException {
final Optional<Command<C, M>> commandOptional = parseCommand(new ArrayList<>(),
commandContext,
args,
this.internalTree);
final Optional<Command<C>> commandOptional = parseCommand(new ArrayList<>(),
commandContext,
args,
this.internalTree);
commandOptional.flatMap(Command::getSenderType).ifPresent(requiredType -> {
if (!requiredType.isAssignableFrom(commandContext.getSender().getClass())) {
throw new InvalidCommandSenderException(commandContext.getSender(), requiredType, Collections.emptyList());
@ -114,10 +111,10 @@ public final class CommandTree<C, M extends CommandMeta> {
return commandOptional;
}
private Optional<Command<C, M>> parseCommand(@Nonnull final List<CommandArgument<C, ?>> parsedArguments,
@Nonnull final CommandContext<C> commandContext,
@Nonnull final Queue<String> commandQueue,
@Nonnull final Node<CommandArgument<C, ?>> root) {
private Optional<Command<C>> parseCommand(@Nonnull final List<CommandArgument<C, ?>> parsedArguments,
@Nonnull final CommandContext<C> commandContext,
@Nonnull final Queue<String> commandQueue,
@Nonnull final Node<CommandArgument<C, ?>> root) {
String permission = this.isPermitted(commandContext.getSender(), root);
if (permission != null) {
throw new NoPermissionException(permission, commandContext.getSender(), this.getChain(root)
@ -126,10 +123,10 @@ public final class CommandTree<C, M extends CommandMeta> {
.collect(Collectors.toList()));
}
final Optional<Command<C, M>> parsedChild = this.attemptParseUnambiguousChild(parsedArguments,
commandContext,
root,
commandQueue);
final Optional<Command<C>> parsedChild = this.attemptParseUnambiguousChild(parsedArguments,
commandContext,
root,
commandQueue);
// noinspection all
if (parsedChild != null) {
return parsedChild;
@ -191,10 +188,10 @@ public final class CommandTree<C, M extends CommandMeta> {
}
@Nullable
private Optional<Command<C, M>> attemptParseUnambiguousChild(@Nonnull final List<CommandArgument<C, ?>> parsedArguments,
@Nonnull final CommandContext<C> commandContext,
@Nonnull final Node<CommandArgument<C, ?>> root,
@Nonnull final Queue<String> commandQueue) {
private Optional<Command<C>> attemptParseUnambiguousChild(@Nonnull final List<CommandArgument<C, ?>> parsedArguments,
@Nonnull final CommandContext<C> commandContext,
@Nonnull final Node<CommandArgument<C, ?>> root,
@Nonnull final Queue<String> commandQueue) {
String permission;
final List<Node<CommandArgument<C, ?>>> children = root.getChildren();
if (children.size() == 1 && !(children.get(0).getValue() instanceof StaticArgument)) {
@ -253,7 +250,7 @@ public final class CommandTree<C, M extends CommandMeta> {
.stream()
.map(Node::getValue)
.collect(
Collectors.toList()));
Collectors.toList()));
}
} else {
parsedArguments.add(child.getValue());
@ -262,9 +259,9 @@ public final class CommandTree<C, M extends CommandMeta> {
} else if (result.getFailure().isPresent()) {
throw new ArgumentParseException(result.getFailure().get(), commandContext.getSender(),
this.getChain(child)
.stream()
.map(Node::getValue)
.collect(Collectors.toList()));
.stream()
.map(Node::getValue)
.collect(Collectors.toList()));
}
}
}
@ -286,8 +283,8 @@ public final class CommandTree<C, M extends CommandMeta> {
@Nonnull
private List<String> getSuggestions(@Nonnull final CommandContext<C> commandContext,
@Nonnull final Queue<String> commandQueue,
@Nonnull final Node<CommandArgument<C, ?>> root) {
@Nonnull final Queue<String> commandQueue,
@Nonnull final Node<CommandArgument<C, ?>> root) {
/* If the sender isn't allowed to access the root node, no suggestions are needed */
if (this.isPermitted(commandContext.getSender(), root) != null) {
@ -360,7 +357,7 @@ public final class CommandTree<C, M extends CommandMeta> {
* @param command Command to insert
*/
@SuppressWarnings("unchecked")
public void insertCommand(@Nonnull final Command<C, M> command) {
public void insertCommand(@Nonnull final Command<C> command) {
synchronized (this.commandLock) {
Node<CommandArgument<C, ?>> node = this.internalTree;
for (final CommandArgument<C, ?> argument : command.getArguments()) {
@ -394,8 +391,9 @@ public final class CommandTree<C, M extends CommandMeta> {
}
if (node.isLeaf()) {
return this.commandManager.hasPermission(sender,
Objects.requireNonNull(Objects.requireNonNull(node.value, "node.value").getOwningCommand(),
"owning command").getCommandPermission())
Objects.requireNonNull(
Objects.requireNonNull(node.value, "node.value").getOwningCommand(),
"owning command").getCommandPermission())
? null : Objects.requireNonNull(node.value.getOwningCommand(), "owning command").getCommandPermission();
}
/*
@ -433,8 +431,7 @@ public final class CommandTree<C, M extends CommandMeta> {
if (leaf.getOwningCommand() == null) {
throw new NoCommandInLeafException(leaf);
} else {
// noinspection unchecked
final Command<C, M> owningCommand = (Command<C, M>) leaf.getOwningCommand();
final Command<C> owningCommand = leaf.getOwningCommand();
this.commandRegistrationHandler.registerCommand(owningCommand);
}
});
@ -451,9 +448,9 @@ public final class CommandTree<C, M extends CommandMeta> {
// Go through all nodes from the tail upwards until a collision occurs
for (final Node<CommandArgument<C, ?>> commandArgumentNode : chain) {
if (commandArgumentNode.nodeMeta.containsKey("permission") && !commandArgumentNode.nodeMeta.get("permission")
.equalsIgnoreCase(
node.nodeMeta
.get("permission"))) {
.equalsIgnoreCase(
node.nodeMeta
.get("permission"))) {
commandArgumentNode.nodeMeta.put("permission", "");
} else {
commandArgumentNode.nodeMeta.put("permission", node.nodeMeta.get("permission"));
@ -513,12 +510,8 @@ public final class CommandTree<C, M extends CommandMeta> {
}
@Nullable
private Command<C, M> cast(@Nullable final Command<C, ?> command) {
if (command == null) {
return null;
}
@SuppressWarnings("unchecked") final Command<C, M> casted = (Command<C, M>) command;
return casted;
private Command<C> cast(@Nullable final Command<C> command) {
return command;
}
/**

View file

@ -42,13 +42,13 @@ public @interface Range {
*
* @return String serialized number
*/
@Nonnull String min() default "";
@Nonnull String min() default "";
/**
* Maximum value accepted by the parser
*
* @return String serialized number
*/
@Nonnull String max() default "";
@Nonnull String max() default "";
}

View file

@ -76,7 +76,7 @@ public class CommandArgument<C, T> implements Comparable<CommandArgument<?, ?>>
*/
private final Class<T> valueType;
private Command<C, ?> owningCommand;
private Command<C> owningCommand;
/**
* Construct a new command argument
@ -105,10 +105,10 @@ public class CommandArgument<C, T> implements Comparable<CommandArgument<?, ?>>
/**
* Construct a new command argument
*
* @param required Whether or not the argument is required
* @param name The argument name
* @param parser The argument parser
* @param valueType Type produced by the parser
* @param required Whether or not the argument is required
* @param name The argument name
* @param parser The argument parser
* @param valueType Type produced by the parser
*/
public CommandArgument(final boolean required,
@Nonnull final String name,
@ -174,7 +174,7 @@ public class CommandArgument<C, T> implements Comparable<CommandArgument<?, ?>>
* @return Owning command
*/
@Nullable
public Command<C, ?> getOwningCommand() {
public Command<C> getOwningCommand() {
return this.owningCommand;
}
@ -183,7 +183,7 @@ public class CommandArgument<C, T> implements Comparable<CommandArgument<?, ?>>
*
* @param owningCommand Owning command
*/
public void setOwningCommand(@Nonnull final Command<C, ?> owningCommand) {
public void setOwningCommand(@Nonnull final Command<C> owningCommand) {
if (this.owningCommand != null) {
throw new IllegalStateException("Cannot replace owning command");
}
@ -265,7 +265,7 @@ public class CommandArgument<C, T> implements Comparable<CommandArgument<?, ?>>
private final Class<T> valueType;
private final String name;
private CommandManager<C, ?> manager;
private CommandManager<C> manager;
private boolean required = true;
private ArgumentParser<C, T> parser;
private String defaultValue = "";
@ -284,7 +284,7 @@ public class CommandArgument<C, T> implements Comparable<CommandArgument<?, ?>>
* @return Builder instance
*/
@Nonnull
public Builder<C, T> manager(@Nonnull final CommandManager<C, ?> manager) {
public Builder<C, T> manager(@Nonnull final CommandManager<C> manager) {
this.manager = manager;
return this;
}
@ -357,7 +357,7 @@ public class CommandArgument<C, T> implements Comparable<CommandArgument<?, ?>>
public CommandArgument<C, T> build() {
if (this.parser == null && this.manager != null) {
this.parser = this.manager.getParserRegistry().createParser(TypeToken.of(valueType), ParserParameters.empty())
.orElse(null);
.orElse(null);
}
if (this.parser == null) {
this.parser = (c, i) -> ArgumentParseResult

View file

@ -57,7 +57,7 @@ public final class StaticArgument<C> extends CommandArgument<C, String> {
*/
@Nonnull
public static <C> StaticArgument<C> required(@Nonnull final String name,
@Nonnull final String... aliases) {
@Nonnull final String... aliases) {
return new StaticArgument<>(true, name, aliases);
}
@ -71,7 +71,7 @@ public final class StaticArgument<C> extends CommandArgument<C, String> {
*/
@Nonnull
public static <C> StaticArgument<C> optional(@Nonnull final String name,
@Nonnull final String... aliases) {
@Nonnull final String... aliases) {
return new StaticArgument<>(false, name, aliases);
}

View file

@ -54,7 +54,8 @@ public class ParserParameter<T> {
*
* @return Parameter key
*/
@Nonnull public String getKey() {
@Nonnull
public String getKey() {
return this.key;
}
@ -63,7 +64,8 @@ public class ParserParameter<T> {
*
* @return Expected type
*/
@Nonnull public TypeToken<T> getExpectedType() {
@Nonnull
public TypeToken<T> getExpectedType() {
return this.expectedType;
}

View file

@ -52,7 +52,7 @@ public final class ParserParameters {
* @param parameter Parameter
* @param value Value
* @param <T> Value type
* @return Constructed instance
* @return Constructed instance
*/
@Nonnull
public static <T> ParserParameters single(@Nonnull final ParserParameter<T> parameter, @Nonnull final T value) {

View file

@ -32,29 +32,26 @@ import javax.annotation.Nonnull;
*/
public final class StandardParameters {
private StandardParameters() {
}
/**
* Minimum value accepted by a numerical parser
*/
public static final ParserParameter<Number> RANGE_MIN = create("min", TypeToken.of(Number.class));
/**
* Maximum value accepted by a numerical parser
*/
public static final ParserParameter<Number> RANGE_MAX = create("max", TypeToken.of(Number.class));
/**
* Command description
*/
public static final ParserParameter<String> DESCRIPTION = create("description", TypeToken.of(String.class));
/**
* Command completions
*/
public static final ParserParameter<String[]> COMPLETIONS = create("completions", TypeToken.of(String[].class));
private StandardParameters() {
}
private static <T> ParserParameter<T> create(@Nonnull final String key, @Nonnull final TypeToken<T> expectedType) {
return new ParserParameter<>(key, expectedType);
}

View file

@ -148,9 +148,9 @@ public final class StandardParserRegistry<C> implements ParserRegistry<C> {
if (producer == null) {
/* Give enums special treatment */
if (actualType.isSubtypeOf(Enum.class)) {
@SuppressWarnings("all")
final EnumArgument.EnumParser enumArgument = new EnumArgument.EnumParser((Class<Enum>)
actualType.getRawType());
@SuppressWarnings("all") final EnumArgument.EnumParser enumArgument = new EnumArgument.EnumParser((Class<Enum>)
actualType
.getRawType());
// noinspection all
return Optional.of(enumArgument);
}

View file

@ -89,10 +89,18 @@ public final class BooleanArgument<C> extends CommandArgument<C, Boolean> {
*/
@Nonnull
public static <C> CommandArgument<C, Boolean> optional(@Nonnull final String name,
final String defaultNum) {
final String defaultNum) {
return BooleanArgument.<C>newBuilder(name).asOptionalWithDefault(defaultNum).build();
}
/**
* Get the liberal boolean
*
* @return Liberal boolean
*/
public boolean isLiberal() {
return liberal;
}
public static final class Builder<C> extends CommandArgument.Builder<C, Boolean> {
@ -127,16 +135,6 @@ public final class BooleanArgument<C> extends CommandArgument<C, Boolean> {
}
/**
* Get the liberal boolean
*
* @return Liberal boolean
*/
public boolean isLiberal() {
return liberal;
}
public static final class BooleanParser<C> implements ArgumentParser<C, Boolean> {
private static final List<String> LIBERAL = Arrays.asList("TRUE", "YES", "ON", "FALSE", "NO", "OFF");

View file

@ -26,8 +26,8 @@ package com.intellectualsites.commands.arguments.standard;
import com.intellectualsites.commands.arguments.CommandArgument;
import com.intellectualsites.commands.arguments.parser.ArgumentParseResult;
import com.intellectualsites.commands.arguments.parser.ArgumentParser;
import com.intellectualsites.commands.exceptions.parsing.NumberParseException;
import com.intellectualsites.commands.context.CommandContext;
import com.intellectualsites.commands.exceptions.parsing.NumberParseException;
import javax.annotation.Nonnull;
import java.util.List;
@ -90,11 +90,29 @@ public final class ByteArgument<C> extends CommandArgument<C, Byte> {
* @param <C> Command sender type
* @return Created argument
*/
@Nonnull public static <C> CommandArgument<C, Byte> optional(@Nonnull final String name,
final byte defaultNum) {
@Nonnull
public static <C> CommandArgument<C, Byte> optional(@Nonnull final String name,
final byte defaultNum) {
return ByteArgument.<C>newBuilder(name).asOptionalWithDefault(Byte.toString(defaultNum)).build();
}
/**
* Get the minimum accepted byteeger that could have been parsed
*
* @return Minimum byteeger
*/
public byte getMin() {
return this.min;
}
/**
* Get the maximum accepted byteeger that could have been parsed
*
* @return Maximum byteeger
*/
public byte getMax() {
return this.max;
}
public static final class Builder<C> extends CommandArgument.Builder<C, Byte> {
@ -142,26 +160,6 @@ public final class ByteArgument<C> extends CommandArgument<C, Byte> {
}
/**
* Get the minimum accepted byteeger that could have been parsed
*
* @return Minimum byteeger
*/
public byte getMin() {
return this.min;
}
/**
* Get the maximum accepted byteeger that could have been parsed
*
* @return Maximum byteeger
*/
public byte getMax() {
return this.max;
}
public static final class ByteParser<C> implements ArgumentParser<C, Byte> {
private final byte min;

View file

@ -85,7 +85,7 @@ public final class CharArgument<C> extends CommandArgument<C, Character> {
*/
@Nonnull
public static <C> CommandArgument<C, Character> optional(@Nonnull final String name,
final String defaultNum) {
final String defaultNum) {
return CharArgument.<C>newBuilder(name).asOptionalWithDefault(defaultNum).build();
}

View file

@ -26,8 +26,8 @@ package com.intellectualsites.commands.arguments.standard;
import com.intellectualsites.commands.arguments.CommandArgument;
import com.intellectualsites.commands.arguments.parser.ArgumentParseResult;
import com.intellectualsites.commands.arguments.parser.ArgumentParser;
import com.intellectualsites.commands.exceptions.parsing.NumberParseException;
import com.intellectualsites.commands.context.CommandContext;
import com.intellectualsites.commands.exceptions.parsing.NumberParseException;
import javax.annotation.Nonnull;
import java.util.Queue;
@ -94,10 +94,27 @@ public final class DoubleArgument<C> extends CommandArgument<C, Double> {
*/
@Nonnull
public static <C> CommandArgument<C, Double> optional(@Nonnull final String name,
final double defaultNum) {
final double defaultNum) {
return DoubleArgument.<C>newBuilder(name).asOptionalWithDefault(Double.toString(defaultNum)).build();
}
/**
* Get the minimum accepted double that could have been parsed
*
* @return Minimum double
*/
public double getMin() {
return this.min;
}
/**
* Get the maximum accepted double that could have been parsed
*
* @return Maximum double
*/
public double getMax() {
return this.max;
}
public static final class Builder<C> extends CommandArgument.Builder<C, Double> {
@ -145,26 +162,6 @@ public final class DoubleArgument<C> extends CommandArgument<C, Double> {
}
/**
* Get the minimum accepted double that could have been parsed
*
* @return Minimum double
*/
public double getMin() {
return this.min;
}
/**
* Get the maximum accepted double that could have been parsed
*
* @return Maximum double
*/
public double getMax() {
return this.max;
}
public static final class DoubleParser<C> implements ArgumentParser<C, Double> {
private final double min;

View file

@ -192,6 +192,14 @@ public class EnumArgument<C, E extends Enum<E>> extends CommandArgument<C, E> {
this.enumClass = enumClass;
}
@Nonnull
@SuppressWarnings("all")
private static String join(@Nonnull final Class<? extends Enum> clazz) {
final EnumSet<?> enumSet = EnumSet.allOf(clazz);
return enumSet.stream()
.map(e -> e.toString().toLowerCase())
.collect(Collectors.joining(", "));
}
/**
* Get the input provided by the sender
@ -217,15 +225,6 @@ public class EnumArgument<C, E extends Enum<E>> extends CommandArgument<C, E> {
return String.format("'%s' is not one of the following: %s", this.input, join(enumClass));
}
@Nonnull
@SuppressWarnings("all")
private static String join(@Nonnull final Class<? extends Enum> clazz) {
final EnumSet<?> enumSet = EnumSet.allOf(clazz);
return enumSet.stream()
.map(e -> e.toString().toLowerCase())
.collect(Collectors.joining(", "));
}
}
}

View file

@ -26,8 +26,8 @@ package com.intellectualsites.commands.arguments.standard;
import com.intellectualsites.commands.arguments.CommandArgument;
import com.intellectualsites.commands.arguments.parser.ArgumentParseResult;
import com.intellectualsites.commands.arguments.parser.ArgumentParser;
import com.intellectualsites.commands.exceptions.parsing.NumberParseException;
import com.intellectualsites.commands.context.CommandContext;
import com.intellectualsites.commands.exceptions.parsing.NumberParseException;
import javax.annotation.Nonnull;
import java.util.Queue;
@ -94,10 +94,27 @@ public final class FloatArgument<C> extends CommandArgument<C, Float> {
*/
@Nonnull
public static <C> CommandArgument<C, Float> optional(@Nonnull final String name,
final float defaultNum) {
final float defaultNum) {
return FloatArgument.<C>newBuilder(name).asOptionalWithDefault(Float.toString(defaultNum)).build();
}
/**
* Get the minimum accepted float that could have been parsed
*
* @return Minimum float
*/
public float getMin() {
return this.min;
}
/**
* Get the maximum accepted float that could have been parsed
*
* @return Maximum float
*/
public float getMax() {
return this.max;
}
public static final class Builder<C> extends CommandArgument.Builder<C, Float> {
@ -145,26 +162,6 @@ public final class FloatArgument<C> extends CommandArgument<C, Float> {
}
/**
* Get the minimum accepted float that could have been parsed
*
* @return Minimum float
*/
public float getMin() {
return this.min;
}
/**
* Get the maximum accepted float that could have been parsed
*
* @return Maximum float
*/
public float getMax() {
return this.max;
}
public static final class FloatParser<C> implements ArgumentParser<C, Float> {
private final float min;

View file

@ -26,8 +26,8 @@ package com.intellectualsites.commands.arguments.standard;
import com.intellectualsites.commands.arguments.CommandArgument;
import com.intellectualsites.commands.arguments.parser.ArgumentParseResult;
import com.intellectualsites.commands.arguments.parser.ArgumentParser;
import com.intellectualsites.commands.exceptions.parsing.NumberParseException;
import com.intellectualsites.commands.context.CommandContext;
import com.intellectualsites.commands.exceptions.parsing.NumberParseException;
import javax.annotation.Nonnull;
import java.util.Collections;
@ -102,10 +102,27 @@ public final class IntegerArgument<C> extends CommandArgument<C, Integer> {
*/
@Nonnull
public static <C> CommandArgument<C, Integer> optional(@Nonnull final String name,
final int defaultNum) {
final int defaultNum) {
return IntegerArgument.<C>newBuilder(name).asOptionalWithDefault(Integer.toString(defaultNum)).build();
}
/**
* Get the minimum accepted integer that could have been parsed
*
* @return Minimum integer
*/
public int getMin() {
return this.min;
}
/**
* Get the maximum accepted integer that could have been parsed
*
* @return Maximum integer
*/
public int getMax() {
return this.max;
}
public static final class Builder<C> extends CommandArgument.Builder<C, Integer> {
@ -153,26 +170,6 @@ public final class IntegerArgument<C> extends CommandArgument<C, Integer> {
}
/**
* Get the minimum accepted integer that could have been parsed
*
* @return Minimum integer
*/
public int getMin() {
return this.min;
}
/**
* Get the maximum accepted integer that could have been parsed
*
* @return Maximum integer
*/
public int getMax() {
return this.max;
}
public static final class IntegerParser<C> implements ArgumentParser<C, Integer> {
private final int min;
@ -189,6 +186,29 @@ public final class IntegerArgument<C> extends CommandArgument<C, Integer> {
this.max = max;
}
@Nonnull
static List<String> getSuggestions(final long min, final long max, @Nonnull final String input) {
if (input.isEmpty()) {
return IntStream.range(0, MAX_SUGGESTIONS_INCREMENT).mapToObj(Integer::toString).collect(Collectors.toList());
}
try {
final long inputNum = Long.parseLong(input);
if (inputNum > max) {
return Collections.emptyList();
} else {
final List<String> suggestions = new LinkedList<>();
suggestions.add(input); /* It's a valid number, so we suggest it */
for (int i = 0; i < MAX_SUGGESTIONS_INCREMENT
&& (inputNum * NUMBER_SHIFT_MULTIPLIER) + i <= max; i++) {
suggestions.add(Long.toString((inputNum * NUMBER_SHIFT_MULTIPLIER) + i));
}
return suggestions;
}
} catch (final Exception ignored) {
return Collections.emptyList();
}
}
@Nonnull
@Override
public ArgumentParseResult<Integer> parse(
@ -240,29 +260,6 @@ public final class IntegerArgument<C> extends CommandArgument<C, Integer> {
return getSuggestions(this.min, this.max, input);
}
@Nonnull
static List<String> getSuggestions(final long min, final long max, @Nonnull final String input) {
if (input.isEmpty()) {
return IntStream.range(0, MAX_SUGGESTIONS_INCREMENT).mapToObj(Integer::toString).collect(Collectors.toList());
}
try {
final long inputNum = Long.parseLong(input);
if (inputNum > max) {
return Collections.emptyList();
} else {
final List<String> suggestions = new LinkedList<>();
suggestions.add(input); /* It's a valid number, so we suggest it */
for (int i = 0; i < MAX_SUGGESTIONS_INCREMENT
&& (inputNum * NUMBER_SHIFT_MULTIPLIER) + i <= max; i++) {
suggestions.add(Long.toString((inputNum * NUMBER_SHIFT_MULTIPLIER) + i));
}
return suggestions;
}
} catch (final Exception ignored) {
return Collections.emptyList();
}
}
}

View file

@ -26,8 +26,8 @@ package com.intellectualsites.commands.arguments.standard;
import com.intellectualsites.commands.arguments.CommandArgument;
import com.intellectualsites.commands.arguments.parser.ArgumentParseResult;
import com.intellectualsites.commands.arguments.parser.ArgumentParser;
import com.intellectualsites.commands.exceptions.parsing.NumberParseException;
import com.intellectualsites.commands.context.CommandContext;
import com.intellectualsites.commands.exceptions.parsing.NumberParseException;
import javax.annotation.Nonnull;
import java.util.List;
@ -95,10 +95,27 @@ public final class LongArgument<C> extends CommandArgument<C, Long> {
*/
@Nonnull
public static <C> CommandArgument<C, Long> optional(@Nonnull final String name,
final long defaultNum) {
final long defaultNum) {
return LongArgument.<C>newBuilder(name).asOptionalWithDefault(Long.toString(defaultNum)).build();
}
/**
* Get the minimum accepted long that could have been parsed
*
* @return Minimum long
*/
public long getMin() {
return this.min;
}
/**
* Get the maximum accepted long that could have been parsed
*
* @return Maximum long
*/
public long getMax() {
return this.max;
}
public static final class Builder<C> extends CommandArgument.Builder<C, Long> {
@ -146,26 +163,6 @@ public final class LongArgument<C> extends CommandArgument<C, Long> {
}
/**
* Get the minimum accepted long that could have been parsed
*
* @return Minimum long
*/
public long getMin() {
return this.min;
}
/**
* Get the maximum accepted long that could have been parsed
*
* @return Maximum long
*/
public long getMax() {
return this.max;
}
private static final class LongParser<C> implements ArgumentParser<C, Long> {
private final long min;

View file

@ -95,10 +95,27 @@ public final class ShortArgument<C> extends CommandArgument<C, Short> {
*/
@Nonnull
public static <C> CommandArgument<C, Short> optional(@Nonnull final String name,
final short defaultNum) {
final short defaultNum) {
return ShortArgument.<C>newBuilder(name).asOptionalWithDefault(Short.toString(defaultNum)).build();
}
/**
* Get the minimum accepted short that could have been parsed
*
* @return Minimum short
*/
public short getMin() {
return this.min;
}
/**
* Get the maximum accepted short that could have been parsed
*
* @return Maximum short
*/
public short getMax() {
return this.max;
}
public static final class Builder<C> extends CommandArgument.Builder<C, Short> {
@ -146,26 +163,6 @@ public final class ShortArgument<C> extends CommandArgument<C, Short> {
}
/**
* Get the minimum accepted short that could have been parsed
*
* @return Minimum short
*/
public short getMin() {
return this.min;
}
/**
* Get the maximum accepted short that could have been parsed
*
* @return Maximum short
*/
public short getMax() {
return this.max;
}
public static final class ShortParser<C> implements ArgumentParser<C, Short> {
private final short min;

View file

@ -95,7 +95,7 @@ public final class StringArgument<C> extends CommandArgument<C, String> {
*/
@Nonnull
public static <C> CommandArgument<C, String> optional(@Nonnull final String name,
final String defaultNum) {
final String defaultNum) {
return StringArgument.<C>newBuilder(name).asOptionalWithDefault(defaultNum).build();
}

View file

@ -25,7 +25,6 @@ package com.intellectualsites.commands.execution;
import com.intellectualsites.commands.CommandTree;
import com.intellectualsites.commands.context.CommandContext;
import com.intellectualsites.commands.meta.CommandMeta;
import javax.annotation.Nonnull;
import java.util.Queue;
@ -39,18 +38,17 @@ import java.util.function.Function;
* not command may be executed in parallel, etc.
*
* @param <C> Command sender type
* @param <M> Command meta type
*/
public abstract class CommandExecutionCoordinator<C, M extends CommandMeta> {
public abstract class CommandExecutionCoordinator<C> {
private final CommandTree<C, M> commandTree;
private final CommandTree<C> commandTree;
/**
* Construct a new command execution coordinator
*
* @param commandTree Command tree
*/
public CommandExecutionCoordinator(@Nonnull final CommandTree<C, M> commandTree) {
public CommandExecutionCoordinator(@Nonnull final CommandTree<C> commandTree) {
this.commandTree = commandTree;
}
@ -58,11 +56,10 @@ public abstract class CommandExecutionCoordinator<C, M extends CommandMeta> {
* Returns a simple command execution coordinator that executes all commands immediately, on the calling thread
*
* @param <C> Command sender type
* @param <M> Command meta type
* @return New coordinator instance
*/
public static <C, M extends CommandMeta> Function<CommandTree<C, M>,
CommandExecutionCoordinator<C, M>> simpleCoordinator() {
public static <C> Function<CommandTree<C>,
CommandExecutionCoordinator<C>> simpleCoordinator() {
return SimpleCoordinator::new;
}
@ -74,7 +71,7 @@ public abstract class CommandExecutionCoordinator<C, M extends CommandMeta> {
* @return Future that completes with the result
*/
public abstract CompletableFuture<CommandResult<C>> coordinateExecution(@Nonnull CommandContext<C> commandContext,
@Nonnull Queue<String> input);
@Nonnull Queue<String> input);
/**
* Get the command tree
@ -82,7 +79,7 @@ public abstract class CommandExecutionCoordinator<C, M extends CommandMeta> {
* @return Command tree
*/
@Nonnull
protected CommandTree<C, M> getCommandTree() {
protected CommandTree<C> getCommandTree() {
return this.commandTree;
}
@ -91,18 +88,17 @@ public abstract class CommandExecutionCoordinator<C, M extends CommandMeta> {
* A simple command execution coordinator that executes all commands immediately, on the calling thread
*
* @param <C> Command sender type
* @param <M> Command meta type
*/
public static final class SimpleCoordinator<C, M extends CommandMeta> extends
CommandExecutionCoordinator<C, M> {
public static final class SimpleCoordinator<C> extends
CommandExecutionCoordinator<C> {
private SimpleCoordinator(@Nonnull final CommandTree<C, M> commandTree) {
private SimpleCoordinator(@Nonnull final CommandTree<C> commandTree) {
super(commandTree);
}
@Override
public CompletableFuture<CommandResult<C>> coordinateExecution(@Nonnull final CommandContext<C> commandContext,
@Nonnull final Queue<String> input) {
@Nonnull final Queue<String> input) {
final CompletableFuture<CommandResult<C>> completableFuture = new CompletableFuture<>();
try {
this.getCommandTree().parse(commandContext, input).ifPresent(

View file

@ -50,7 +50,8 @@ public class CommandResult<C> {
*
* @return Command context
*/
@Nonnull public CommandContext<C> getCommandContext() {
@Nonnull
public CommandContext<C> getCommandContext() {
return this.commandContext;
}

View file

@ -33,7 +33,7 @@ import com.intellectualsites.services.types.ConsumerService;
* {@link ConsumerService#interrupt()}
*
* @param <C> Command sender type
* {@inheritDoc}
* {@inheritDoc}
*/
public interface CommandPreprocessor<C> extends ConsumerService<CommandPreprocessingContext<C>> {
}

View file

@ -24,7 +24,6 @@
package com.intellectualsites.commands.internal;
import com.intellectualsites.commands.Command;
import com.intellectualsites.commands.meta.CommandMeta;
import javax.annotation.Nonnull;
@ -32,11 +31,19 @@ import javax.annotation.Nonnull;
* Utility that registers commands natively for whatever
* platform the library is used in. This can do nothing, if
* the target platform does not have its own concept of commands
*
* @param <M> Command meta type
*/
@FunctionalInterface
public interface CommandRegistrationHandler<M extends CommandMeta> {
public interface CommandRegistrationHandler {
/**
* Create a new {@link CommandRegistrationHandler} that does nothing
*
* @return Constructed registration
*/
@Nonnull
static CommandRegistrationHandler nullCommandRegistrationHandler() {
return new NullCommandRegistrationHandler();
}
/**
* Attempt to register the command
@ -45,26 +52,15 @@ public interface CommandRegistrationHandler<M extends CommandMeta> {
* @return {@code true} if the command was registered successfully,
* else {@code false}
*/
boolean registerCommand(@Nonnull Command<?, M> command);
boolean registerCommand(@Nonnull Command<?> command);
/**
* Create a new {@link CommandRegistrationHandler} that does nothing
*
* @param <M> Command meta type
* @return Constructed registration
*/
static <M extends CommandMeta> CommandRegistrationHandler<M> nullCommandRegistrationHandler() {
return new NullCommandRegistrationHandler<>();
}
final class NullCommandRegistrationHandler<M extends CommandMeta> implements CommandRegistrationHandler<M> {
final class NullCommandRegistrationHandler implements CommandRegistrationHandler {
private NullCommandRegistrationHandler() {
}
@Override
public boolean registerCommand(@Nonnull final Command<?, M> command) {
public boolean registerCommand(@Nonnull final Command<?> command) {
return true;
}

View file

@ -24,6 +24,8 @@
package com.intellectualsites.commands.meta;
import javax.annotation.Nonnull;
import java.util.Map;
import java.util.Optional;
/**
* Object that is associated with a {@link com.intellectualsites.commands.Command}.
@ -31,7 +33,7 @@ import javax.annotation.Nonnull;
* <p>
* Appropriate use for command meta would be fixed state, such as command descriptions.
*/
public class CommandMeta {
public abstract class CommandMeta {
/**
* Create a new simple command meta builder
@ -49,4 +51,31 @@ public class CommandMeta {
return "";
}
/**
* Get the value associated with a key
*
* @param key Key
* @return Optional that may contain the associated value
*/
@Nonnull
public abstract Optional<String> getValue(@Nonnull String key);
/**
* Get the value if it exists, else return the default value
*
* @param key Key
* @param defaultValue Default value
* @return Value, or default value
*/
@Nonnull
public abstract String getOrDefault(@Nonnull String key, @Nonnull String defaultValue);
/**
* Get a copy of the meta map
*
* @return Copy of meta map
*/
@Nonnull
public abstract Map<String, String> getAll();
}

View file

@ -57,40 +57,26 @@ public class SimpleCommandMeta extends CommandMeta {
*
* @return Empty instance
*/
@Nonnull public static SimpleCommandMeta empty() {
@Nonnull
public static SimpleCommandMeta empty() {
return SimpleCommandMeta.builder().build();
}
/**
* Get the value associated with a key
*
* @param key Key
* @return Optional that may contain the associated value
*/
@Override
@Nonnull
public Optional<String> getValue(@Nonnull final String key) {
public final Optional<String> getValue(@Nonnull final String key) {
return Optional.ofNullable(this.metaMap.get(key));
}
/**
* Get the value if it exists, else return the default value
*
* @param key Key
* @param defaultValue Default value
* @return Value, or default value
*/
@Override
@Nonnull
public String getOrDefault(@Nonnull final String key, @Nonnull final String defaultValue) {
public final String getOrDefault(@Nonnull final String key, @Nonnull final String defaultValue) {
return this.getValue(key).orElse(defaultValue);
}
/**
* Get a copy of the meta map
*
* @return Copy of meta map
*/
@Override
@Nonnull
public Map<String, String> getAll() {
public final Map<String, String> getAll() {
return new HashMap<>(this.metaMap);
}

View file

@ -24,6 +24,7 @@
/**
* cloud API main package
*
* @see com.intellectualsites.commands.CommandManager Command manager class
*/
package com.intellectualsites.commands;

View file

@ -36,23 +36,23 @@ import javax.annotation.Nonnull;
public class CommandPreProcessorTest {
private static CommandManager<TestCommandSender, SimpleCommandMeta> manager;
private static CommandManager<TestCommandSender> manager;
@BeforeAll
static void newTree() {
manager = new TestCommandManager();
manager.command(manager.commandBuilder("test", SimpleCommandMeta.empty())
.argument(EnumArgument.required(SampleEnum.class, "enum"))
.handler(
commandContext -> System.out.printf("enum = %s | integer = %d\n",
commandContext.<SampleEnum>get(
"enum").orElse(
SampleEnum.VALUE1),
commandContext.<Integer>get(
"int").orElseThrow(
() -> new NullPointerException(
"int"))))
.build());
.argument(EnumArgument.required(SampleEnum.class, "enum"))
.handler(
commandContext -> System.out.printf("enum = %s | integer = %d\n",
commandContext.<SampleEnum>get(
"enum").orElse(
SampleEnum.VALUE1),
commandContext.<Integer>get(
"int").orElseThrow(
() -> new NullPointerException(
"int"))))
.build());
manager.registerCommandPreProcessor(new SamplePreprocessor());
}

View file

@ -26,7 +26,6 @@ package com.intellectualsites.commands;
import com.intellectualsites.commands.arguments.standard.EnumArgument;
import com.intellectualsites.commands.arguments.standard.IntegerArgument;
import com.intellectualsites.commands.arguments.standard.StringArgument;
import com.intellectualsites.commands.meta.SimpleCommandMeta;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
@ -37,7 +36,7 @@ import java.util.List;
public class CommandSuggestionsTest {
private static CommandManager<TestCommandSender, SimpleCommandMeta> manager;
private static CommandManager<TestCommandSender> manager;
@BeforeAll
static void setupManager() {
@ -47,18 +46,18 @@ public class CommandSuggestionsTest {
manager.command(manager.commandBuilder("test")
.literal("var")
.argument(StringArgument.<TestCommandSender>newBuilder("str")
.withSuggestionsProvider((c, s) -> Arrays.asList("one", "two"))
.build())
.withSuggestionsProvider((c, s) -> Arrays.asList("one", "two"))
.build())
.argument(EnumArgument.required(TestEnum.class, "enum"))
.build());
manager.command(manager.commandBuilder("test")
.literal("comb")
.argument(StringArgument.<TestCommandSender>newBuilder("str")
.literal("comb")
.argument(StringArgument.<TestCommandSender>newBuilder("str")
.withSuggestionsProvider((c, s) -> Arrays.asList("one", "two"))
.build())
.argument(IntegerArgument.<TestCommandSender>newBuilder("num")
.argument(IntegerArgument.<TestCommandSender>newBuilder("num")
.withMin(1).withMax(95).asOptional().build())
.build());
.build());
}
@Test
@ -68,7 +67,7 @@ public class CommandSuggestionsTest {
Assertions.assertTrue(suggestions.isEmpty());
final String input2 = "test ";
final List<String> suggestions2 = manager.suggest(new TestCommandSender(), input2);
Assertions.assertEquals(Arrays.asList("comb", "one", "two","var"), suggestions2);
Assertions.assertEquals(Arrays.asList("comb", "one", "two", "var"), suggestions2);
}
@Test
@ -109,7 +108,8 @@ public class CommandSuggestionsTest {
public enum TestEnum {
FOO, BAR
FOO,
BAR
}
}

View file

@ -40,7 +40,7 @@ import java.util.concurrent.CompletionException;
class CommandTreeTest {
private static final int EXPECTED_INPUT_NUMBER = 15;
private static CommandManager<TestCommandSender, SimpleCommandMeta> manager;
private static CommandManager<TestCommandSender> manager;
@BeforeAll
static void newTree() {
@ -53,25 +53,25 @@ class CommandTreeTest {
SimpleCommandMeta.empty())
.literal("opt", "öpt")
.argument(IntegerArgument
.optional("num", EXPECTED_INPUT_NUMBER))
.optional("num", EXPECTED_INPUT_NUMBER))
.build())
.command(manager.commandBuilder("req").withSenderType(SpecificCommandSender.class).build());
}
@Test
void parse() {
final Optional<Command<TestCommandSender, SimpleCommandMeta>> command = manager.getCommandTree()
.parse(new CommandContext<>(
new TestCommandSender()),
new LinkedList<>(
Arrays.asList("test",
"one")));
final Optional<Command<TestCommandSender>> command = manager.getCommandTree()
.parse(new CommandContext<>(
new TestCommandSender()),
new LinkedList<>(
Arrays.asList("test",
"one")));
Assertions.assertTrue(command.isPresent());
Assertions.assertThrows(NoPermissionException.class, () -> manager.getCommandTree()
.parse(new CommandContext<>(
new TestCommandSender()),
new LinkedList<>(
Arrays.asList("test", "two"))));
new TestCommandSender()),
new LinkedList<>(
Arrays.asList("test", "two"))));
manager.getCommandTree()
.parse(new CommandContext<>(new TestCommandSender()), new LinkedList<>(Arrays.asList("test", "opt")))
.ifPresent(c -> c.getCommandExecutionHandler().execute(new CommandContext<>(new TestCommandSender())));
@ -106,9 +106,9 @@ class CommandTreeTest {
manager.commandBuilder("default")
.argument(manager.argumentBuilder(Integer.class, "int").build())
.handler(context -> {
final int number = context.getRequired("int");
System.out.printf("Supplied number is: %d\n", number);
})
final int number = context.getRequired("int");
System.out.printf("Supplied number is: %d\n", number);
})
.build()
);
manager.executeCommand(new TestCommandSender(), "default 5").join();

View file

@ -72,12 +72,12 @@ public class ParserRegistryTest {
Assertions.assertTrue(parserParameters.has(StandardParameters.RANGE_MIN));
Assertions.assertTrue(parserParameters.has(StandardParameters.RANGE_MAX));
final ArgumentParser<TestCommandSender, ?> parser = parserRegistry.createParser(parsedType,
parserParameters)
.orElseThrow(
() -> new NullPointerException("No parser found"));
parserParameters)
.orElseThrow(
() -> new NullPointerException(
"No parser found"));
Assertions.assertTrue(parser instanceof IntegerArgument.IntegerParser);
@SuppressWarnings("unchecked")
final IntegerArgument.IntegerParser<TestCommandSender> integerParser =
@SuppressWarnings("unchecked") final IntegerArgument.IntegerParser<TestCommandSender> integerParser =
(IntegerArgument.IntegerParser<TestCommandSender>) parser;
Assertions.assertEquals(RANGE_MIN, integerParser.getMin());
Assertions.assertEquals(RANGE_MAX, integerParser.getMax());

View file

@ -29,7 +29,7 @@ import com.intellectualsites.commands.meta.SimpleCommandMeta;
import javax.annotation.Nonnull;
public class TestCommandManager extends CommandManager<TestCommandSender, SimpleCommandMeta> {
public class TestCommandManager extends CommandManager<TestCommandSender> {
protected TestCommandManager() {
super(CommandExecutionCoordinator.simpleCoordinator(), CommandRegistrationHandler.nullCommandRegistrationHandler());

View file

@ -47,15 +47,15 @@ import java.util.function.Function;
/**
* Command manager for use with JLine
*/
public class JLineCommandManager extends CommandManager<JLineCommandSender, SimpleCommandMeta> implements Completer {
public class JLineCommandManager extends CommandManager<JLineCommandSender> implements Completer {
/**
* Construct a new JLine command manager
*
* @param executionCoordinatorFunction Function producing a new coordinator
*/
public JLineCommandManager(@Nonnull final Function<CommandTree<JLineCommandSender, SimpleCommandMeta>,
CommandExecutionCoordinator<JLineCommandSender, SimpleCommandMeta>> executionCoordinatorFunction) {
public JLineCommandManager(@Nonnull final Function<CommandTree<JLineCommandSender>,
CommandExecutionCoordinator<JLineCommandSender>> executionCoordinatorFunction) {
super(executionCoordinatorFunction, CommandRegistrationHandler.nullCommandRegistrationHandler());
}
@ -78,35 +78,35 @@ public class JLineCommandManager extends CommandManager<JLineCommandSender, Simp
jLineCommandManager.command(
jLineCommandManager.commandBuilder("stop", SimpleCommandMeta.empty())
.handler(commandContext ->
shouldStop[0] = true)
shouldStop[0] = true)
.build())
.command(jLineCommandManager.commandBuilder("echo", SimpleCommandMeta.empty())
.argument(String.class, "string", builder ->
builder.asRequired()
.withParser(((commandContext, inputQueue) -> {
final StringBuilder stringBuilder =
new StringBuilder();
while (!inputQueue.isEmpty()) {
stringBuilder.append(inputQueue.remove());
if (!inputQueue.isEmpty()) {
stringBuilder.append(" ");
}
}
return ArgumentParseResult.success(
stringBuilder.toString());
})).build())
.handler(commandContext -> commandContext.get("string")
.ifPresent(
System.out::println))
.build())
.argument(String.class, "string", builder ->
builder.asRequired()
.withParser(((commandContext, inputQueue) -> {
final StringBuilder stringBuilder =
new StringBuilder();
while (!inputQueue.isEmpty()) {
stringBuilder.append(inputQueue.remove());
if (!inputQueue.isEmpty()) {
stringBuilder.append(" ");
}
}
return ArgumentParseResult.success(
stringBuilder.toString());
})).build())
.handler(commandContext -> commandContext.get("string")
.ifPresent(
System.out::println))
.build())
.command(jLineCommandManager.commandBuilder("test", SimpleCommandMeta.empty())
.argument(StaticArgument.required("one"))
.handler(commandContext -> System.out.println("Test (1)"))
.build())
.argument(StaticArgument.required("one"))
.handler(commandContext -> System.out.println("Test (1)"))
.build())
.command(jLineCommandManager.commandBuilder("test", SimpleCommandMeta.empty())
.argument(StaticArgument.required("two"))
.handler(commandContext -> System.out.println("Test (2)"))
.build());
.argument(StaticArgument.required("two"))
.handler(commandContext -> System.out.println("Test (2)"))
.build());
System.out.println("Ready...");
while (!shouldStop[0]) {
final String line = lineReader.readLine();
@ -139,8 +139,8 @@ public class JLineCommandManager extends CommandManager<JLineCommandSender, Simp
@Override
public final void complete(@Nonnull final LineReader lineReader,
@Nonnull final ParsedLine parsedLine,
@Nonnull final List<Candidate> list) {
@Nonnull final ParsedLine parsedLine,
@Nonnull final List<Candidate> list) {
final String line = parsedLine.line();
if (line == null || line.isEmpty() || !line.startsWith("/")) {
System.out.println("Cannot suggest: empty line");
@ -157,7 +157,7 @@ public class JLineCommandManager extends CommandManager<JLineCommandSender, Simp
@Override
public final boolean hasPermission(@Nonnull final JLineCommandSender sender, @Nonnull final String permission) {
return true;
return true;
}
}

View file

@ -81,7 +81,7 @@ public final class CloudBrigadierManager<C, S> {
? extends ArgumentType<?>>> mappers;
private final Map<Class<?>, Supplier<ArgumentType<?>>> defaultArgumentTypeSuppliers;
private final Supplier<CommandContext<C>> dummyContextProvider;
private final CommandManager<C, ?> commandManager;
private final CommandManager<C> commandManager;
/**
* Create a new cloud brigadier manager
@ -89,7 +89,7 @@ public final class CloudBrigadierManager<C, S> {
* @param commandManager Command manager
* @param dummyContextProvider Provider of dummy context for completions
*/
public CloudBrigadierManager(@Nonnull final CommandManager<C, ?> commandManager,
public CloudBrigadierManager(@Nonnull final CommandManager<C> commandManager,
@Nonnull final Supplier<CommandContext<C>>
dummyContextProvider) {
this.mappers = Maps.newHashMap();
@ -184,14 +184,14 @@ public final class CloudBrigadierManager<C, S> {
* Register a cloud-Brigadier mapping
*
* @param argumentType cloud argument type
* @param mapper mapper function
* @param <T> cloud argument value type
* @param <K> cloud argument type
* @param <O> Brigadier argument type value
* @param mapper mapper function
* @param <T> cloud argument value type
* @param <K> cloud argument type
* @param <O> Brigadier argument type value
*/
public <T, K extends CommandArgument<C, T>, O> void registerMapping(@Nonnull final TypeToken<K> argumentType,
@Nonnull final Function<? extends K,
? extends ArgumentType<O>> mapper) {
? extends ArgumentType<O>> mapper) {
this.mappers.put(argumentType.getRawType(), mapper);
}
@ -211,8 +211,8 @@ public final class CloudBrigadierManager<C, S> {
*
* @param argumentType cloud argument type
* @param argument cloud argument
* @param <T> cloud argument value type (generic)
* @param <K> cloud argument type (generic)
* @param <T> cloud argument value type (generic)
* @param <K> cloud argument type (generic)
* @return Brigadier argument type
*/
@Nullable
@ -268,9 +268,9 @@ public final class CloudBrigadierManager<C, S> {
}
private ArgumentBuilder<S, ?> constructCommandNode(@Nonnull final CommandTree.Node<CommandArgument<C, ?>> root,
@Nonnull final BiPredicate<S, String> permissionChecker,
@Nonnull final com.mojang.brigadier.Command<S> executor,
@Nonnull final SuggestionProvider<S> suggestionProvider) {
@Nonnull final BiPredicate<S, String> permissionChecker,
@Nonnull final com.mojang.brigadier.Command<S> executor,
@Nonnull final SuggestionProvider<S> suggestionProvider) {
ArgumentBuilder<S, ?> argumentBuilder;
if (root.getValue() instanceof StaticArgument) {

View file

@ -37,11 +37,11 @@ import com.intellectualsites.commands.arguments.standard.EnumArgument;
import com.intellectualsites.commands.arguments.standard.FloatArgument;
import com.intellectualsites.commands.arguments.standard.IntegerArgument;
import com.intellectualsites.commands.arguments.standard.StringArgument;
import com.intellectualsites.commands.bukkit.BukkitCommandMeta;
import com.intellectualsites.commands.bukkit.BukkitCommandMetaBuilder;
import com.intellectualsites.commands.execution.CommandExecutionCoordinator;
import com.intellectualsites.commands.paper.PaperCommandManager;
import com.intellectualsites.commands.bukkit.parsers.WorldArgument;
import com.intellectualsites.commands.execution.CommandExecutionCoordinator;
import com.intellectualsites.commands.meta.SimpleCommandMeta;
import com.intellectualsites.commands.paper.PaperCommandManager;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
@ -54,7 +54,6 @@ import org.bukkit.plugin.java.JavaPlugin;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.function.Function;
@ -68,46 +67,43 @@ public final class BukkitTest extends JavaPlugin {
@Override
public void onEnable() {
try {
final PaperCommandManager<CommandSender> mgr = new PaperCommandManager<>(
final CommandManager<CommandSender> mgr = new PaperCommandManager<>(
this,
CommandExecutionCoordinator
.simpleCoordinator(),
CommandExecutionCoordinator
.simpleCoordinator(),
Function.identity(),
Function.identity()
);
final AnnotationParser<CommandSender, BukkitCommandMeta> annotationParser
final AnnotationParser<CommandSender> annotationParser
= new AnnotationParser<>(mgr, CommandSender.class, p ->
BukkitCommandMetaBuilder.builder().withDescription(p.get(StandardParameters.DESCRIPTION,
"No description")).build());
annotationParser.parse(this);
mgr.registerBrigadier();
mgr.command(mgr.commandBuilder("gamemode",
Collections.singleton("gajmöde"),
BukkitCommandMetaBuilder.builder()
.withDescription("Your ugli")
.build())
//noinspection all
((PaperCommandManager<CommandSender>) mgr).registerBrigadier();
mgr.command(mgr.commandBuilder("gamemode", this.metaWithDescription("Your ugli"), "gajmöde")
.argument(EnumArgument.required(GameMode.class, "gamemode"))
.argument(StringArgument.<CommandSender>newBuilder("player")
.withSuggestionsProvider((v1, v2) -> {
final List<String> suggestions =
new ArrayList<>(
Bukkit.getOnlinePlayers()
.stream()
.map(Player::getName)
.collect(Collectors.toList()));
suggestions.add("dog");
suggestions.add("cat");
return suggestions;
}).build())
.withSuggestionsProvider((v1, v2) -> {
final List<String> suggestions =
new ArrayList<>(
Bukkit.getOnlinePlayers()
.stream()
.map(Player::getName)
.collect(Collectors.toList()));
suggestions.add("dog");
suggestions.add("cat");
return suggestions;
}).build())
.handler(c -> ((Player) c.getSender())
.setGameMode(c.<GameMode>get("gamemode")
.orElse(GameMode.SURVIVAL)))
.setGameMode(c.<GameMode>get("gamemode")
.orElse(GameMode.SURVIVAL)))
.build())
.command(mgr.commandBuilder("kenny")
.literal("sux")
.argument(IntegerArgument
.<CommandSender>newBuilder("perc")
.withMin(PERC_MIN).withMax(PERC_MAX).build())
.<CommandSender>newBuilder("perc")
.withMin(PERC_MIN).withMax(PERC_MAX).build())
.handler(context -> {
((Player) context.getSender()).sendMessage(String.format(
"Kenny sux %d%%",
@ -182,4 +178,9 @@ public final class BukkitTest extends JavaPlugin {
player.sendMessage(ChatColor.GOLD + "Your input was: " + ChatColor.AQUA + input + ChatColor.GREEN + " (" + number + ")");
}
@Nonnull
private SimpleCommandMeta metaWithDescription(@Nonnull final String description) {
return BukkitCommandMetaBuilder.builder().withDescription(description).build();
}
}

View file

@ -48,10 +48,10 @@ final class BukkitCommand<C> extends org.bukkit.command.Command implements Plugi
private final CommandArgument<C, ?> command;
private final BukkitCommandManager<C> bukkitCommandManager;
private final Command<C, BukkitCommandMeta> cloudCommand;
private final Command<C> cloudCommand;
@SuppressWarnings("unchecked")
BukkitCommand(@Nonnull final Command<C, BukkitCommandMeta> cloudCommand,
BukkitCommand(@Nonnull final Command<C> cloudCommand,
@Nonnull final CommandArgument<C, ?> command,
@Nonnull final BukkitCommandManager<C> bukkitCommandManager) {
super(command.getName(),
@ -76,9 +76,9 @@ final class BukkitCommand<C> extends org.bukkit.command.Command implements Plugi
if (throwable != null) {
if (throwable instanceof InvalidSyntaxException) {
commandSender.sendMessage(ChatColor.RED + "Invalid Command Syntax. "
+ "Correct command syntax is: "
+ ChatColor.GRAY + "/"
+ ((InvalidSyntaxException) throwable).getCorrectSyntax());
+ "Correct command syntax is: "
+ ChatColor.GRAY + "/"
+ ((InvalidSyntaxException) throwable).getCorrectSyntax());
} else if (throwable instanceof InvalidCommandSenderException) {
commandSender.sendMessage(ChatColor.RED + throwable.getMessage());
} else if (throwable instanceof NoPermissionException) {
@ -87,7 +87,8 @@ final class BukkitCommand<C> extends org.bukkit.command.Command implements Plugi
commandSender.sendMessage(MESSAGE_UNKNOWN_COMMAND);
} else if (throwable instanceof ArgumentParseException) {
commandSender.sendMessage(ChatColor.RED + "Invalid Command Argument: "
+ ChatColor.GRAY + throwable.getCause().getMessage());
+ ChatColor.GRAY + throwable.getCause()
.getMessage());
} else {
commandSender.sendMessage(throwable.getMessage());
throwable.printStackTrace();

View file

@ -43,8 +43,7 @@ import java.util.function.Function;
*
* @param <C> Command sender type
*/
public class BukkitCommandManager<C>
extends CommandManager<C, BukkitCommandMeta> {
public class BukkitCommandManager<C> extends CommandManager<C> {
private final Plugin owningPlugin;
@ -61,8 +60,8 @@ public class BukkitCommandManager<C>
* @throws Exception If the construction of the manager fails
*/
public BukkitCommandManager(@Nonnull final Plugin owningPlugin,
@Nonnull final Function<CommandTree<C, BukkitCommandMeta>,
CommandExecutionCoordinator<C, BukkitCommandMeta>> commandExecutionCoordinator,
@Nonnull final Function<CommandTree<C>,
CommandExecutionCoordinator<C>> commandExecutionCoordinator,
@Nonnull final Function<CommandSender, C> commandSenderMapper,
@Nonnull final Function<C, CommandSender> backwardsCommandSenderMapper)
throws Exception {

View file

@ -37,7 +37,8 @@ public final class BukkitCommandMetaBuilder {
*
* @return Builder instance
*/
@Nonnull public static BuilderStage1 builder() {
@Nonnull
public static BuilderStage1 builder() {
return new BuilderStage1();
}
@ -53,7 +54,8 @@ public final class BukkitCommandMetaBuilder {
* @param description Command description
* @return Builder instance
*/
@Nonnull public BuilderStage2 withDescription(@Nonnull final String description) {
@Nonnull
public BuilderStage2 withDescription(@Nonnull final String description) {
return new BuilderStage2(description);
}
@ -73,7 +75,8 @@ public final class BukkitCommandMetaBuilder {
*
* @return Meta instance
*/
@Nonnull public BukkitCommandMeta build() {
@Nonnull
public BukkitCommandMeta build() {
return new BukkitCommandMeta(CommandMeta.simple().with("description", this.description).build());
}

View file

@ -37,7 +37,7 @@ import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
final class BukkitPluginRegistrationHandler<C> implements CommandRegistrationHandler<BukkitCommandMeta> {
final class BukkitPluginRegistrationHandler<C> implements CommandRegistrationHandler {
private final Map<CommandArgument<?, ?>, org.bukkit.command.Command> registeredCommands = new HashMap<>();
@ -62,7 +62,7 @@ final class BukkitPluginRegistrationHandler<C> implements CommandRegistrationHan
}
@Override
public boolean registerCommand(@Nonnull final Command<?, BukkitCommandMeta> command) {
public boolean registerCommand(@Nonnull final Command<?> command) {
/* We only care about the root command argument */
final CommandArgument<?, ?> commandArgument = command.getArguments().get(0);
if (this.registeredCommands.containsKey(commandArgument)) {
@ -75,7 +75,7 @@ final class BukkitPluginRegistrationHandler<C> implements CommandRegistrationHan
label = commandArgument.getName();
}
@SuppressWarnings("unchecked") final BukkitCommand<C> bukkitCommand = new BukkitCommand<>(
(Command<C, BukkitCommandMeta>) command,
(Command<C>) command,
(CommandArgument<C, ?>) commandArgument,
this.bukkitCommandManager);
this.registeredCommands.put(commandArgument, bukkitCommand);

View file

@ -88,7 +88,7 @@ public class MaterialArgument<C> extends CommandArgument<C, Material> {
*
* @param name Argument name
* @param material Default value
* @param <C> Command sender type
* @param <C> Command sender type
* @return Created argument
*/
@Nonnull

View file

@ -94,7 +94,7 @@ public class WorldArgument<C> extends CommandArgument<C, World> {
*/
@Nonnull
public static <C> CommandArgument<C, World> optional(@Nonnull final String name,
@Nonnull final String defaultValue) {
@Nonnull final String defaultValue) {
return WorldArgument.<C>newBuilder(name).asOptionalWithDefault(defaultValue).build();
}

View file

@ -30,7 +30,6 @@ import com.intellectualsites.commands.exceptions.InvalidCommandSenderException;
import com.intellectualsites.commands.exceptions.InvalidSyntaxException;
import com.intellectualsites.commands.exceptions.NoPermissionException;
import com.intellectualsites.commands.exceptions.NoSuchCommandException;
import com.intellectualsites.commands.meta.SimpleCommandMeta;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.chat.ComponentBuilder;
@ -42,16 +41,16 @@ import javax.annotation.Nonnull;
public final class BungeeCommand<C> extends Command implements TabExecutor {
private static final String MESSAGE_NO_PERMS =
"I'm sorry, but you do not have permission to perform this command. "
+ "Please contact the server administrators if you believe that this is in error.";
"I'm sorry, but you do not have permission to perform this command. "
+ "Please contact the server administrators if you believe that this is in error.";
private static final String MESSAGE_UNKNOWN_COMMAND = "Unknown command. Type \"/help\" for help.";
private final BungeeCommandManager<C> bungeeCommandManager;
private final CommandArgument<C, ?> command;
private final com.intellectualsites.commands.Command<C, SimpleCommandMeta> cloudCommand;
private final com.intellectualsites.commands.Command<C> cloudCommand;
@SuppressWarnings("unchecked")
BungeeCommand(@Nonnull final com.intellectualsites.commands.Command<C, SimpleCommandMeta> cloudCommand,
BungeeCommand(@Nonnull final com.intellectualsites.commands.Command<C> cloudCommand,
@Nonnull final CommandArgument<C, ?> command,
@Nonnull final BungeeCommandManager<C> bungeeCommandManager) {
super(command.getName(),
@ -71,41 +70,41 @@ public final class BungeeCommand<C> extends Command implements TabExecutor {
}
this.bungeeCommandManager.executeCommand(this.bungeeCommandManager.getCommandSenderMapper().apply(commandSender),
builder.toString())
.whenComplete(((commandResult, throwable) -> {
if (throwable != null) {
if (throwable instanceof InvalidSyntaxException) {
commandSender.sendMessage(
new ComponentBuilder("Invalid Command Syntax. Correct command syntax is: ")
.color(ChatColor.RED)
.append("/")
.color(ChatColor.GRAY)
.append(((InvalidSyntaxException) throwable).getCorrectSyntax())
.color(ChatColor.GRAY)
.create()
);
} else if (throwable instanceof InvalidCommandSenderException) {
commandSender.sendMessage(new ComponentBuilder(throwable.getMessage())
.color(ChatColor.RED)
.create());
} else if (throwable instanceof NoPermissionException) {
commandSender.sendMessage(new ComponentBuilder(MESSAGE_NO_PERMS)
.color(ChatColor.WHITE)
.create());
} else if (throwable instanceof NoSuchCommandException) {
commandSender.sendMessage(new ComponentBuilder(MESSAGE_UNKNOWN_COMMAND)
.color(ChatColor.WHITE)
.create());
} else if (throwable instanceof ArgumentParseException) {
commandSender.sendMessage(new ComponentBuilder("Invalid Command Argument: ")
.color(ChatColor.GRAY)
.append(throwable.getCause().getMessage())
.create());
} else {
commandSender.sendMessage(new ComponentBuilder(throwable.getMessage()).create());
throwable.printStackTrace();
}
}
}));
.whenComplete(((commandResult, throwable) -> {
if (throwable != null) {
if (throwable instanceof InvalidSyntaxException) {
commandSender.sendMessage(
new ComponentBuilder("Invalid Command Syntax. Correct command syntax is: ")
.color(ChatColor.RED)
.append("/")
.color(ChatColor.GRAY)
.append(((InvalidSyntaxException) throwable).getCorrectSyntax())
.color(ChatColor.GRAY)
.create()
);
} else if (throwable instanceof InvalidCommandSenderException) {
commandSender.sendMessage(new ComponentBuilder(throwable.getMessage())
.color(ChatColor.RED)
.create());
} else if (throwable instanceof NoPermissionException) {
commandSender.sendMessage(new ComponentBuilder(MESSAGE_NO_PERMS)
.color(ChatColor.WHITE)
.create());
} else if (throwable instanceof NoSuchCommandException) {
commandSender.sendMessage(new ComponentBuilder(MESSAGE_UNKNOWN_COMMAND)
.color(ChatColor.WHITE)
.create());
} else if (throwable instanceof ArgumentParseException) {
commandSender.sendMessage(new ComponentBuilder("Invalid Command Argument: ")
.color(ChatColor.GRAY)
.append(throwable.getCause().getMessage())
.create());
} else {
commandSender.sendMessage(new ComponentBuilder(throwable.getMessage()).create());
throwable.printStackTrace();
}
}
}));
}
@Override

View file

@ -33,7 +33,7 @@ import net.md_5.bungee.api.plugin.Plugin;
import javax.annotation.Nonnull;
import java.util.function.Function;
public class BungeeCommandManager<C> extends CommandManager<C, SimpleCommandMeta> {
public class BungeeCommandManager<C> extends CommandManager<C> {
private final Plugin owningPlugin;
private final Function<CommandSender, C> commandSenderMapper;
@ -49,8 +49,8 @@ public class BungeeCommandManager<C> extends CommandManager<C, SimpleCommandMeta
* @throws Exception If the construction of the manager fails
*/
public BungeeCommandManager(@Nonnull final Plugin owningPlugin,
@Nonnull final Function<CommandTree<C, SimpleCommandMeta>,
CommandExecutionCoordinator<C, SimpleCommandMeta>> commandExecutionCoordinator,
@Nonnull final Function<CommandTree<C>,
CommandExecutionCoordinator<C>> commandExecutionCoordinator,
@Nonnull final Function<CommandSender, C> commandSenderMapper,
@Nonnull final Function<C, CommandSender> backwardsCommandSenderMapper)
throws Exception {
@ -63,7 +63,7 @@ public class BungeeCommandManager<C> extends CommandManager<C, SimpleCommandMeta
@Override
public final boolean hasPermission(@Nonnull final C sender,
@Nonnull final String permission) {
@Nonnull final String permission) {
return this.backwardsCommandSenderMapper.apply(sender).hasPermission(permission);
}

View file

@ -26,14 +26,12 @@ package com.intellectualsites.commands.bungee;
import com.intellectualsites.commands.Command;
import com.intellectualsites.commands.arguments.CommandArgument;
import com.intellectualsites.commands.internal.CommandRegistrationHandler;
import com.intellectualsites.commands.meta.SimpleCommandMeta;
import javax.annotation.Nonnull;
import java.util.HashMap;
import java.util.Map;
final class BungeePluginRegistrationHandler<C> implements
CommandRegistrationHandler<SimpleCommandMeta> {
final class BungeePluginRegistrationHandler<C> implements CommandRegistrationHandler {
private final Map<CommandArgument<?, ?>, net.md_5.bungee.api.plugin.Command> registeredCommands = new HashMap<>();
@ -47,19 +45,19 @@ final class BungeePluginRegistrationHandler<C> implements
}
@Override
public boolean registerCommand(@Nonnull final Command<?, SimpleCommandMeta> command) {
public boolean registerCommand(@Nonnull final Command<?> command) {
/* We only care about the root command argument */
final CommandArgument<?, ?> commandArgument = command.getArguments().get(0);
if (this.registeredCommands.containsKey(commandArgument)) {
return false;
}
@SuppressWarnings("unchecked") final BungeeCommand<C> bungeeCommand = new BungeeCommand<>(
(Command<C, SimpleCommandMeta>) command,
(Command<C>) command,
(CommandArgument<C, ?>) commandArgument,
this.bungeeCommandManager);
this.registeredCommands.put(commandArgument, bungeeCommand);
this.bungeeCommandManager.getOwningPlugin().getProxy().getPluginManager()
.registerCommand(this.bungeeCommandManager.getOwningPlugin(), bungeeCommand);
.registerCommand(this.bungeeCommandManager.getOwningPlugin(), bungeeCommand);
return true;
}

View file

@ -25,10 +25,9 @@ package com.intellectualsites.commands.paper;
import com.destroystokyo.paper.brigadier.BukkitBrigadierCommandSource;
import com.destroystokyo.paper.event.brigadier.CommandRegisteredEvent;
import com.intellectualsites.commands.bukkit.BukkitCommandMeta;
import com.intellectualsites.commands.CommandTree;
import com.intellectualsites.commands.brigadier.CloudBrigadierManager;
import com.intellectualsites.commands.arguments.CommandArgument;
import com.intellectualsites.commands.brigadier.CloudBrigadierManager;
import com.intellectualsites.commands.context.CommandContext;
import com.mojang.brigadier.arguments.ArgumentType;
import org.bukkit.Bukkit;
@ -52,8 +51,9 @@ class PaperBrigadierListener<C> implements Listener {
PaperBrigadierListener(@Nonnull final PaperCommandManager<C> paperCommandManager) throws Exception {
this.paperCommandManager = paperCommandManager;
this.brigadierManager = new CloudBrigadierManager<>(this.paperCommandManager,
() -> new CommandContext<>(this.paperCommandManager.getCommandSenderMapper()
.apply(Bukkit.getConsoleSender())));
() -> new CommandContext<>(
this.paperCommandManager.getCommandSenderMapper()
.apply(Bukkit.getConsoleSender())));
/* Register default mappings */
final String version = Bukkit.getServer().getClass().getPackage().getName();
this.nmsVersion = version.substring(version.lastIndexOf(".") + 1);
@ -112,7 +112,7 @@ class PaperBrigadierListener<C> implements Listener {
@EventHandler
public void onCommandRegister(@Nonnull final CommandRegisteredEvent<BukkitBrigadierCommandSource> event) {
final CommandTree<C, BukkitCommandMeta> commandTree = this.paperCommandManager.getCommandTree();
final CommandTree<C> commandTree = this.paperCommandManager.getCommandTree();
final CommandTree.Node<CommandArgument<C, ?>> node = commandTree.getNamedNode(event.getCommandLabel());
if (node == null) {
return;

View file

@ -23,9 +23,8 @@
//
package com.intellectualsites.commands.paper;
import com.intellectualsites.commands.bukkit.BukkitCommandManager;
import com.intellectualsites.commands.bukkit.BukkitCommandMeta;
import com.intellectualsites.commands.CommandTree;
import com.intellectualsites.commands.bukkit.BukkitCommandManager;
import com.intellectualsites.commands.execution.CommandExecutionCoordinator;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
@ -46,15 +45,15 @@ public class PaperCommandManager<C>
/**
* Construct a new Paper command manager
*
* @param owningPlugin Plugin that is constructing the manager
* @param commandExecutionCoordinator Coordinator provider
* @param commandSenderMapper Function that maps {@link CommandSender} to the command sender type
* @param owningPlugin Plugin that is constructing the manager
* @param commandExecutionCoordinator Coordinator provider
* @param commandSenderMapper Function that maps {@link CommandSender} to the command sender type
* @param backwardsCommandSenderMapper Function that maps the command sender type to {@link CommandSender}
* @throws Exception If the construction of the manager fails
*/
public PaperCommandManager(@Nonnull final Plugin owningPlugin,
@Nonnull final Function<CommandTree<C, BukkitCommandMeta>,
CommandExecutionCoordinator<C, BukkitCommandMeta>> commandExecutionCoordinator,
@Nonnull final Function<CommandTree<C>,
CommandExecutionCoordinator<C>> commandExecutionCoordinator,
@Nonnull final Function<CommandSender, C> commandSenderMapper,
@Nonnull final Function<C, CommandSender> backwardsCommandSenderMapper) throws
Exception {
@ -65,7 +64,7 @@ public class PaperCommandManager<C>
* Attempt to register the Brigadier mapper, and return it.
*
* @return {@link PaperBrigadierListener} instance, if it could be created. If it cannot
* be created {@code null} is returned
* be created {@code null} is returned
*/
@Nullable
public PaperBrigadierListener<C> registerBrigadier() {